blob: fa9f64c9a61663c65cee6edf9160da2b480878f2 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -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_writer.h"
18
Mathieu Chartierceb07b32015-12-10 09:33:21 -080019#include <lz4.h>
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -080020#include <lz4hc.h>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include <sys/stat.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Vladimir Marko20f85592015-03-19 10:07:02 +000024#include <numeric>
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080025#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070026#include <vector>
27
Mathieu Chartierc7853442015-03-27 14:35:38 -070028#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070029#include "art_method-inl.h"
Andreas Gampe8228cdf2017-05-30 15:03:54 -070030#include "base/callee_save_type.h"
31#include "base/enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "base/logging.h"
33#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010034#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070035#include "compiled_method.h"
36#include "dex_file-inl.h"
Andreas Gampea5b09a62016-11-17 15:21:22 -080037#include "dex_file_types.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070039#include "elf_file.h"
40#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "elf_writer.h"
42#include "gc/accounting/card_table-inl.h"
43#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070044#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier36a270a2016-07-28 18:08:51 -070045#include "gc/collector/concurrent_copying.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070046#include "gc/heap-visit-objects-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070047#include "gc/heap.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070048#include "gc/space/large_object_space.h"
49#include "gc/space/space-inl.h"
Mathieu Chartier4f5e3cb2017-06-12 13:10:01 -070050#include "gc/verification.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "globals.h"
Mathieu Chartier4f5e3cb2017-06-12 13:10:01 -070052#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070053#include "image.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070054#include "imt_conflict_table.h"
Mathieu Chartier3738e982017-05-12 16:07:28 -070055#include "jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070056#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070057#include "lock_word.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "mirror/array-inl.h"
59#include "mirror/class-inl.h"
Alex Lightd6251582016-10-31 11:12:30 -070060#include "mirror/class_ext.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "mirror/class_loader.h"
62#include "mirror/dex_cache-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070063#include "mirror/dex_cache.h"
Neil Fuller0e844392016-09-08 13:43:31 +010064#include "mirror/executable.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070065#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080067#include "mirror/object-refvisitor-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070069#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070070#include "oat.h"
71#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070072#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070074#include "scoped_thread_state_change-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000075#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070076
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070077using ::art::mirror::Class;
78using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070079using ::art::mirror::Object;
80using ::art::mirror::ObjectArray;
81using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070082
83namespace art {
84
Igor Murashkinf5b4c502014-11-14 15:01:59 -080085// Separate objects into multiple bins to optimize dirty memory use.
86static constexpr bool kBinObjects = true;
87
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080088// Return true if an object is already in an image space.
89bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080090 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080091 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080092 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080093 return false;
94 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080095 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
96 const uint8_t* image_begin = boot_image_space->Begin();
97 // Real image end including ArtMethods and ArtField sections.
98 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
99 if (image_begin <= obj && obj < image_end) {
100 return true;
101 }
102 }
103 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800104}
105
106bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800107 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800108 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800109 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800110 return false;
111 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800112 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
113 const ImageHeader& image_header = boot_image_space->GetImageHeader();
114 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
115 return true;
116 }
117 }
118 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800119}
120
Mathieu Chartier3738e982017-05-12 16:07:28 -0700121static void ClearDexFileCookies() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe1c158a02017-07-13 17:26:19 -0700122 auto visitor = [](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
123 DCHECK(obj != nullptr);
124 Class* klass = obj->GetClass();
125 if (klass == WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_DexFile)) {
126 ArtField* field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
127 // Null out the cookie to enable determinism. b/34090128
128 field->SetObject</*kTransactionActive*/false>(obj, nullptr);
129 }
130 };
131 Runtime::Current()->GetHeap()->VisitObjects(visitor);
Andreas Gampedd9d0552015-03-09 12:57:41 -0700132}
133
Vladimir Markof4da6752014-08-01 19:04:18 +0100134bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800135 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800136 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100137 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700138 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100139 PruneNonImageClasses(); // Remove junk
Mathieu Chartier3738e982017-05-12 16:07:28 -0700140 if (compile_app_image_) {
141 // Clear dex file cookies for app images to enable app image determinism. This is required
142 // since the cookie field contains long pointers to DexFiles which are not deterministic.
143 // b/34090128
144 ClearDexFileCookies();
145 } else {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800146 // Avoid for app image since this may increase RAM and image size.
147 ComputeLazyFieldsForImageClasses(); // Add useful information
148 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100149 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100150 heap->CollectGarbage(false); // Remove garbage.
151
Vladimir Markof4da6752014-08-01 19:04:18 +0100152 if (kIsDebugBuild) {
153 ScopedObjectAccess soa(Thread::Current());
154 CheckNonImageClassesRemoved();
155 }
156
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700157 {
158 ScopedObjectAccess soa(Thread::Current());
159 CalculateNewObjectOffsets();
160 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100161
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700162 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
163 // bin size sums being calculated.
164 if (!AllocMemory()) {
165 return false;
166 }
167
Vladimir Markof4da6752014-08-01 19:04:18 +0100168 return true;
169}
170
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700171bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800172 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000173 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800174 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
175 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800176 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800177 if (image_fd != kInvalidFd) {
178 CHECK_EQ(image_filenames.size(), 1u);
179 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800180 CHECK(!oat_filenames.empty());
181 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700182
Vladimir Marko944da602016-02-19 12:27:55 +0000183 {
184 ScopedObjectAccess soa(Thread::Current());
185 for (size_t i = 0; i < oat_filenames.size(); ++i) {
186 CreateHeader(i);
187 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800188 }
189 }
Alex Light53cb16b2014-06-12 11:26:29 -0700190
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700191 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700192 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800193 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700194 Runtime::Current()->GetHeap()->DisableObjectValidation();
195 CopyAndFixupObjects();
196 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700197
Jeff Haodcdc85b2015-12-04 14:06:18 -0800198 for (size_t i = 0; i < image_filenames.size(); ++i) {
199 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000200 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800201 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800202 if (image_fd != kInvalidFd) {
203 if (strlen(image_filename) == 0u) {
204 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800205 // Empty the file in case it already exists.
206 if (image_file != nullptr) {
207 TEMP_FAILURE_RETRY(image_file->SetLength(0));
208 TEMP_FAILURE_RETRY(image_file->Flush());
209 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800210 } else {
211 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
212 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800213 } else {
214 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800215 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800216
Jeff Haodcdc85b2015-12-04 14:06:18 -0800217 if (image_file == nullptr) {
218 LOG(ERROR) << "Failed to open image file " << image_filename;
219 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800220 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800221
222 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800223 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
224 image_file->Erase();
225 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800226 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800227
Jeff Haodcdc85b2015-12-04 14:06:18 -0800228 std::unique_ptr<char[]> compressed_data;
229 // Image data size excludes the bitmap and the header.
230 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
231 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
232 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
233 size_t data_size;
234 const char* image_data_to_write;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800235 const uint64_t compress_start_time = NanoTime();
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000236
Jeff Haodcdc85b2015-12-04 14:06:18 -0800237 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
238 switch (image_storage_mode_) {
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700239 case ImageHeader::kStorageModeLZ4HC: // Fall-through.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800240 case ImageHeader::kStorageModeLZ4: {
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800241 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800242 compressed_data.reset(new char[compressed_max_size]);
David Lin915ec552017-02-23 15:36:06 -0800243 data_size = LZ4_compress_default(
Jeff Haodcdc85b2015-12-04 14:06:18 -0800244 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
245 &compressed_data[0],
David Lin915ec552017-02-23 15:36:06 -0800246 image_data_size,
247 compressed_max_size);
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800248
249 break;
250 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700251 /*
252 * Disabled due to image_test64 flakyness. Both use same decompression. b/27560444
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800253 case ImageHeader::kStorageModeLZ4HC: {
254 // Bound is same as non HC.
255 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
256 compressed_data.reset(new char[compressed_max_size]);
257 data_size = LZ4_compressHC(
258 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
259 &compressed_data[0],
260 image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800261 break;
262 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700263 */
Jeff Haodcdc85b2015-12-04 14:06:18 -0800264 case ImageHeader::kStorageModeUncompressed: {
265 data_size = image_data_size;
266 image_data_to_write = image_data;
267 break;
268 }
269 default: {
270 LOG(FATAL) << "Unsupported";
271 UNREACHABLE();
272 }
273 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800274
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800275 if (compressed_data != nullptr) {
276 image_data_to_write = &compressed_data[0];
277 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
278 << PrettyDuration(NanoTime() - compress_start_time);
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700279 if (kIsDebugBuild) {
280 std::unique_ptr<uint8_t[]> temp(new uint8_t[image_data_size]);
281 const size_t decompressed_size = LZ4_decompress_safe(
282 reinterpret_cast<char*>(&compressed_data[0]),
283 reinterpret_cast<char*>(&temp[0]),
284 data_size,
285 image_data_size);
286 CHECK_EQ(decompressed_size, image_data_size);
287 CHECK_EQ(memcmp(image_data, &temp[0], image_data_size), 0) << image_storage_mode_;
288 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800289 }
290
Jeff Haodcdc85b2015-12-04 14:06:18 -0800291 // Write out the image + fields + methods.
292 const bool is_compressed = compressed_data != nullptr;
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800293 if (!image_file->PwriteFully(image_data_to_write, data_size, sizeof(ImageHeader))) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800294 PLOG(ERROR) << "Failed to write image file data " << image_filename;
295 image_file->Erase();
296 return false;
297 }
298
299 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
300 // convenience.
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100301 const ImageSection& bitmap_section = image_header->GetImageBitmapSection();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800302 // Align up since data size may be unaligned if the image is compressed.
303 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
304 if (!is_compressed) {
305 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
306 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800307 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
308 bitmap_section.Size(),
309 bitmap_position_in_file)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800310 PLOG(ERROR) << "Failed to write image file " << image_filename;
311 image_file->Erase();
312 return false;
313 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800314
315 int err = image_file->Flush();
316 if (err < 0) {
317 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
318 image_file->Erase();
319 return false;
320 }
321
322 // Write header last in case the compiler gets killed in the middle of image writing.
323 // We do not want to have a corrupted image with a valid header.
324 // The header is uncompressed since it contains whether the image is compressed or not.
325 image_header->data_size_ = data_size;
326 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
327 sizeof(ImageHeader),
328 0)) {
329 PLOG(ERROR) << "Failed to write image file header " << image_filename;
330 image_file->Erase();
331 return false;
332 }
333
Jeff Haodcdc85b2015-12-04 14:06:18 -0800334 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
335 static_cast<size_t>(image_file->GetLength()));
336 if (image_file->FlushCloseOrErase() != 0) {
337 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
338 return false;
339 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800340 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700341 return true;
342}
343
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700344void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700345 DCHECK(object != nullptr);
346 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800347
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800348 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700349 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700350 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700351 DCHECK(IsImageOffsetAssigned(object));
352}
353
Mathieu Chartiere401d142015-04-22 13:56:20 -0700354void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
355 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
356 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
357 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
358}
359
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800360void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700361 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800362 DCHECK_NE(image_objects_offset_begin_, 0u);
363
Vladimir Marko944da602016-02-19 12:27:55 +0000364 size_t oat_index = GetOatIndex(object);
365 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800366 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100367 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800368 DCHECK_ALIGNED(new_offset, kObjectAlignment);
369
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700370 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800371 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700372}
373
Ian Rogersef7d42f2014-01-06 12:55:46 -0800374bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800375 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700376 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700377 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700378}
379
Ian Rogersef7d42f2014-01-06 12:55:46 -0800380size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700381 DCHECK(object != nullptr);
382 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700383 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700384 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000385 size_t oat_index = GetOatIndex(object);
386 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800387 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700388 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700389}
390
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800391void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
392 DCHECK(object != nullptr);
393 DCHECK(!IsImageOffsetAssigned(object));
394 DCHECK(!IsImageBinSlotAssigned(object));
395
396 // Before we stomp over the lock word, save the hash code for later.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800397 LockWord lw(object->GetLockWord(false));
398 switch (lw.GetState()) {
Ian Rogers23e81a12017-07-05 09:36:27 -0700399 case LockWord::kFatLocked:
400 FALLTHROUGH_INTENDED;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800401 case LockWord::kThinLocked: {
Ian Rogers23e81a12017-07-05 09:36:27 -0700402 std::ostringstream oss;
403 bool thin = (lw.GetState() == LockWord::kThinLocked);
404 oss << (thin ? "Thin" : "Fat")
405 << " locked object " << object << "(" << object->PrettyTypeOf()
406 << ") found during object copy";
407 if (thin) {
408 oss << ". Lock owner:" << lw.ThinLockOwner();
409 }
410 LOG(FATAL) << oss.str();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800411 break;
412 }
413 case LockWord::kUnlocked:
414 // No hash, don't need to save it.
415 break;
416 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700417 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
418 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800419 break;
420 default:
421 LOG(FATAL) << "Unreachable.";
422 UNREACHABLE();
423 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700424 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700425 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800426 DCHECK(IsImageBinSlotAssigned(object));
427}
428
Vladimir Marko20f85592015-03-19 10:07:02 +0000429void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000430 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000431 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
432 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800433 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000434 auto it = dex_file_oat_index_map_.find(dex_file);
435 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800436 ImageInfo& image_info = GetImageInfo(it->second);
437 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
438 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
439 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
440 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000441
Vladimir Marko20f85592015-03-19 10:07:02 +0000442 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700443 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -0800444 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800445 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700446 ObjPtr<mirror::DexCache> dex_cache =
447 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
448 if (dex_cache == nullptr || IsInBootImage(dex_cache.Ptr())) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700449 continue;
450 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000451 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartier0b490842016-05-25 15:05:59 -0700452 CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
453 << "Dex cache should have been pruned " << dex_file->GetLocation()
454 << "; possibly in class path";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700455 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000456 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000457 size_t oat_index = GetOatIndexForDexCache(dex_cache);
458 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800459 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100460 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800461 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
462 start + layout.TypesOffset(),
463 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100464 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800465 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
466 start + layout.MethodsOffset(),
467 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100468 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800469 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
470 start + layout.FieldsOffset(),
471 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100472 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800473 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Narayan Kamath7fe56582016-10-14 18:49:12 +0100474
475 if (dex_cache->GetResolvedMethodTypes() != nullptr) {
476 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethodTypes(),
477 start + layout.MethodTypesOffset(),
478 dex_cache);
479 }
Orion Hodson631827d2017-04-10 14:53:47 +0100480 if (dex_cache->GetResolvedCallSites() != nullptr) {
481 AddDexCacheArrayRelocation(dex_cache->GetResolvedCallSites(),
482 start + layout.CallSitesOffset(),
483 dex_cache);
484 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000485 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000486}
487
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700488void ImageWriter::AddDexCacheArrayRelocation(void* array,
489 size_t offset,
490 ObjPtr<mirror::DexCache> dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100491 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800492 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000493 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800494 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000495 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100496 }
497}
498
Mathieu Chartiere401d142015-04-22 13:56:20 -0700499void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
500 DCHECK(arr != nullptr);
501 if (kIsDebugBuild) {
502 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800503 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700504 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800505 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800506 CHECK(klass == nullptr || KeepClass(klass))
David Sehr709b0702016-10-13 09:12:37 -0700507 << Class::PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700508 }
509 }
510 }
511 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
512 // ArtMethods.
513 pointer_arrays_.emplace(arr, kBinArtMethodClean);
514}
515
Mathieu Chartier496577f2016-09-20 15:33:31 -0700516void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800517 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800518 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800519
520 // The magic happens here. We segregate objects into different bins based
521 // on how likely they are to get dirty at runtime.
522 //
523 // Likely-to-dirty objects get packed together into the same bin so that
524 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
525 // maximized.
526 //
527 // This means more pages will stay either clean or shared dirty (with zygote) and
528 // the app will use less of its own (private) memory.
529 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000530 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800531
532 if (kBinObjects) {
533 //
534 // Changing the bin of an object is purely a memory-use tuning.
535 // It has no change on runtime correctness.
536 //
537 // Memory analysis has determined that the following types of objects get dirtied
538 // the most:
539 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000540 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
541 // a fixed layout which helps improve generated code (using PC-relative addressing),
542 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
543 // Since these arrays are huge, most pages do not overlap other objects and it's not
544 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100545 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800546 // * Class'es which are verified [their clinit runs only at runtime]
547 // - classes in general [because their static fields get overwritten]
548 // - initialized classes with all-final statics are unlikely to be ever dirty,
549 // so bin them separately
550 // * Art Methods that are:
551 // - native [their native entry point is not looked up until runtime]
552 // - have declaring classes that aren't initialized
553 // [their interpreter/quick entry points are trampolines until the class
554 // becomes initialized]
555 //
556 // We also assume the following objects get dirtied either never or extremely rarely:
557 // * Strings (they are immutable)
558 // * Art methods that aren't native and have initialized declared classes
559 //
560 // We assume that "regular" bin objects are highly unlikely to become dirtied,
561 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
562 //
563 if (object->IsClass()) {
564 bin = kBinClassVerified;
565 mirror::Class* klass = object->AsClass();
566
Mathieu Chartiere401d142015-04-22 13:56:20 -0700567 // Add non-embedded vtable to the pointer array table if there is one.
568 auto* vtable = klass->GetVTable();
569 if (vtable != nullptr) {
570 AddMethodPointerArray(vtable);
571 }
572 auto* iftable = klass->GetIfTable();
573 if (iftable != nullptr) {
574 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
575 if (iftable->GetMethodArrayCount(i) > 0) {
576 AddMethodPointerArray(iftable->GetMethodArray(i));
577 }
578 }
579 }
580
Jeff Haoc23b0c02017-07-27 18:19:38 -0700581 // Move known dirty objects into their own sections. This includes:
582 // - classes with dirty static fields.
583 if (dirty_image_objects_ != nullptr &&
584 dirty_image_objects_->find(klass->PrettyDescriptor()) != dirty_image_objects_->end()) {
585 bin = kBinKnownDirty;
586 } else if (klass->GetStatus() == Class::kStatusInitialized) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800587 bin = kBinClassInitialized;
588
589 // If the class's static fields are all final, put it into a separate bin
590 // since it's very likely it will stay clean.
591 uint32_t num_static_fields = klass->NumStaticFields();
592 if (num_static_fields == 0) {
593 bin = kBinClassInitializedFinalStatics;
594 } else {
595 // Maybe all the statics are final?
596 bool all_final = true;
597 for (uint32_t i = 0; i < num_static_fields; ++i) {
598 ArtField* field = klass->GetStaticField(i);
599 if (!field->IsFinal()) {
600 all_final = false;
601 break;
602 }
603 }
604
605 if (all_final) {
606 bin = kBinClassInitializedFinalStatics;
607 }
608 }
609 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800610 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
611 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700612 } else if (object->GetClass<kVerifyNone>() ==
613 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
614 // Instance of java lang object, probably a lock object. This means it will be dirty when we
615 // synchronize on it.
616 bin = kBinMiscDirty;
617 } else if (object->IsDexCache()) {
618 // Dex file field becomes dirty when the image is loaded.
619 bin = kBinMiscDirty;
620 }
621 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800622 }
623
Mathieu Chartier496577f2016-09-20 15:33:31 -0700624 // Assign the oat index too.
625 DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
626 oat_index_map_.emplace(object, oat_index);
627
Vladimir Marko944da602016-02-19 12:27:55 +0000628 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800629
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800630 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800631 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
632 // Move the current bin size up to accommodate the object we just assigned a bin slot.
633 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800634
635 BinSlot new_bin_slot(bin, current_offset);
636 SetImageBinSlot(object, new_bin_slot);
637
Jeff Haodcdc85b2015-12-04 14:06:18 -0800638 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800639
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800640 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800641 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800642}
643
Mathieu Chartiere401d142015-04-22 13:56:20 -0700644bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
645 if (m->IsNative()) {
646 return true;
647 }
648 mirror::Class* declaring_class = m->GetDeclaringClass();
649 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
650 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
651}
652
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800653bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
654 DCHECK(object != nullptr);
655
656 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
657 // If it's in some other state, then we haven't yet assigned an image bin slot.
658 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
659 return false;
660 } else if (kIsDebugBuild) {
661 LockWord lock_word = object->GetLockWord(false);
662 size_t offset = lock_word.ForwardingAddress();
663 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000664 size_t oat_index = GetOatIndex(object);
665 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800666 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800667 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800668 }
669 return true;
670}
671
672ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
673 DCHECK(object != nullptr);
674 DCHECK(IsImageBinSlotAssigned(object));
675
676 LockWord lock_word = object->GetLockWord(false);
677 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
678 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
679
680 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000681 size_t oat_index = GetOatIndex(object);
682 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800683 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800684
685 return bin_slot;
686}
687
Brian Carlstrom7940e442013-07-12 13:46:57 -0700688bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000689 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800690 ImageSection unused_sections[ImageHeader::kSectionCount];
691 const size_t length = RoundUp(
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100692 image_info.CreateImageSections(unused_sections, compile_app_image_), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800693
Jeff Haodcdc85b2015-12-04 14:06:18 -0800694 std::string error_msg;
695 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
696 nullptr,
697 length,
698 PROT_READ | PROT_WRITE,
699 false,
700 false,
701 &error_msg));
702 if (UNLIKELY(image_info.image_.get() == nullptr)) {
703 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
704 return false;
705 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700706
Jeff Haodcdc85b2015-12-04 14:06:18 -0800707 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
708 CHECK_LE(image_info.image_end_, length);
709 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
710 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
711 if (image_info.image_bitmap_.get() == nullptr) {
712 LOG(ERROR) << "Failed to allocate memory for image bitmap";
713 return false;
714 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700715 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700716 return true;
717}
718
Vladimir Markoad06b982016-11-17 16:38:59 +0000719class ImageWriter::ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700720 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700721 bool operator()(ObjPtr<Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700722 StackHandleScope<1> hs(Thread::Current());
723 mirror::Class::ComputeName(hs.NewHandle(c));
724 return true;
725 }
726};
727
Brian Carlstrom7940e442013-07-12 13:46:57 -0700728void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700729 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700730 ComputeLazyFieldsForClassesVisitor visitor;
731 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700732}
733
Vladimir Markof25cc732017-03-16 16:18:15 +0000734static bool IsBootClassLoaderClass(ObjPtr<mirror::Class> klass)
735 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800736 return klass->GetClassLoader() == nullptr;
737}
738
739bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
740 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
741}
742
Chang Xingb2e8adc2017-07-07 17:35:37 -0700743// This visitor follows the references of an instance, recursively then prune this class
744// if a type of any field is pruned.
745class ImageWriter::PruneObjectReferenceVisitor {
746 public:
747 PruneObjectReferenceVisitor(ImageWriter* image_writer,
748 bool* early_exit,
749 std::unordered_set<mirror::Object*>* visited,
750 bool* result)
751 : image_writer_(image_writer), early_exit_(early_exit), visited_(visited), result_(result) {}
752
753 ALWAYS_INLINE void VisitRootIfNonNull(
754 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const
755 REQUIRES_SHARED(Locks::mutator_lock_) { }
756
757 ALWAYS_INLINE void VisitRoot(
758 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const
759 REQUIRES_SHARED(Locks::mutator_lock_) { }
760
761 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
762 MemberOffset offset,
763 bool is_static ATTRIBUTE_UNUSED) const
764 REQUIRES_SHARED(Locks::mutator_lock_) {
765 mirror::Object* ref =
766 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
767 if (ref == nullptr || visited_->find(ref) != visited_->end()) {
768 return;
769 }
770
771 ObjPtr<mirror::Class> klass = ref->IsClass() ? ref->AsClass() : ref->GetClass();
772 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
773 // Prune all classes using reflection because the content they held will not be fixup.
774 *result_ = true;
775 }
776
Chang Xingb2e8adc2017-07-07 17:35:37 -0700777 if (ref->IsClass()) {
778 *result_ = *result_ ||
779 image_writer_->PruneAppImageClassInternal(ref->AsClass(), early_exit_, visited_);
780 } else {
Chang Xingec373252017-07-13 17:51:52 -0700781 // Record the object visited in case of circular reference.
782 visited_->emplace(ref);
Chang Xingb2e8adc2017-07-07 17:35:37 -0700783 *result_ = *result_ ||
784 image_writer_->PruneAppImageClassInternal(klass, early_exit_, visited_);
785 ref->VisitReferences(*this, *this);
Chang Xingec373252017-07-13 17:51:52 -0700786 // Clean up before exit for next call of this function.
787 visited_->erase(ref);
Chang Xingb2e8adc2017-07-07 17:35:37 -0700788 }
Chang Xingb2e8adc2017-07-07 17:35:37 -0700789 }
790
791 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
792 ObjPtr<mirror::Reference> ref) const
793 REQUIRES_SHARED(Locks::mutator_lock_) {
794 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
795 }
796
797 ALWAYS_INLINE bool GetResult() const {
798 return result_;
799 }
800
801 private:
802 ImageWriter* image_writer_;
803 bool* early_exit_;
804 std::unordered_set<mirror::Object*>* visited_;
805 bool* const result_;
806};
807
808
Vladimir Markof25cc732017-03-16 16:18:15 +0000809bool ImageWriter::PruneAppImageClass(ObjPtr<mirror::Class> klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800810 bool early_exit = false;
Chang Xingb2e8adc2017-07-07 17:35:37 -0700811 std::unordered_set<mirror::Object*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800812 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800813}
814
Mathieu Chartier901e0702016-02-19 13:42:48 -0800815bool ImageWriter::PruneAppImageClassInternal(
Vladimir Markof25cc732017-03-16 16:18:15 +0000816 ObjPtr<mirror::Class> klass,
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800817 bool* early_exit,
Chang Xingb2e8adc2017-07-07 17:35:37 -0700818 std::unordered_set<mirror::Object*>* visited) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800819 DCHECK(early_exit != nullptr);
820 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800821 DCHECK(compile_app_image_);
Vladimir Markof25cc732017-03-16 16:18:15 +0000822 if (klass == nullptr || IsInBootImage(klass.Ptr())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700823 return false;
824 }
Vladimir Markof25cc732017-03-16 16:18:15 +0000825 auto found = prune_class_memo_.find(klass.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800826 if (found != prune_class_memo_.end()) {
827 // Already computed, return the found value.
828 return found->second;
829 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800830 // Circular dependencies, return false but do not store the result in the memoization table.
Vladimir Markof25cc732017-03-16 16:18:15 +0000831 if (visited->find(klass.Ptr()) != visited->end()) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800832 *early_exit = true;
833 return false;
834 }
Vladimir Markof25cc732017-03-16 16:18:15 +0000835 visited->emplace(klass.Ptr());
Mathieu Chartier901e0702016-02-19 13:42:48 -0800836 bool result = IsBootClassLoaderClass(klass);
837 std::string temp;
838 // Prune if not an image class, this handles any broken sets of image classes such as having a
839 // class in the set but not it's superclass.
840 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800841 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800842 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
843 // app image.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000844 if (klass->IsErroneous()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800845 result = true;
846 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700847 ObjPtr<mirror::ClassExt> ext(klass->GetExtData());
848 CHECK(ext.IsNull() || ext->GetVerifyError() == nullptr) << klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800849 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800850 if (!result) {
851 // Check interfaces since these wont be visited through VisitReferences.)
852 mirror::IfTable* if_table = klass->GetIfTable();
853 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800854 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
855 &my_early_exit,
856 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800857 }
858 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800859 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800860 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
861 &my_early_exit,
862 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800863 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800864 // Check static fields and their classes.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000865 if (klass->IsResolved() && klass->NumReferenceStaticFields() != 0) {
866 size_t num_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800867 // Presumably GC can happen when we are cross compiling, it should not cause performance
868 // problems to do pointer size logic.
869 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
870 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
871 for (size_t i = 0u; i < num_static_fields; ++i) {
872 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
873 if (ref != nullptr) {
874 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800875 result = result || PruneAppImageClassInternal(ref->AsClass(),
876 &my_early_exit,
877 visited);
878 } else {
Chang Xingb2e8adc2017-07-07 17:35:37 -0700879 mirror::Class* type = ref->GetClass();
880 result = result || PruneAppImageClassInternal(type,
Mathieu Chartier901e0702016-02-19 13:42:48 -0800881 &my_early_exit,
882 visited);
Chang Xingb2e8adc2017-07-07 17:35:37 -0700883 if (!result) {
884 // For non-class case, also go through all the types mentioned by it's fields'
885 // references recursively to decide whether to keep this class.
886 bool tmp = false;
887 PruneObjectReferenceVisitor visitor(this, &my_early_exit, visited, &tmp);
888 ref->VisitReferences(visitor, visitor);
889 result = result || tmp;
890 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800891 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800892 }
893 field_offset = MemberOffset(field_offset.Uint32Value() +
894 sizeof(mirror::HeapReference<mirror::Object>));
895 }
896 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800897 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
898 &my_early_exit,
899 visited);
Mathieu Chartierc27bc402016-08-05 16:09:09 -0700900 // Remove the class if the dex file is not in the set of dex files. This happens for classes that
Mathieu Chartier72041a02017-07-14 18:23:25 -0700901 // are from uses-library if there is no profile. b/30688277
Mathieu Chartierc27bc402016-08-05 16:09:09 -0700902 mirror::DexCache* dex_cache = klass->GetDexCache();
903 if (dex_cache != nullptr) {
904 result = result ||
905 dex_file_oat_index_map_.find(dex_cache->GetDexFile()) == dex_file_oat_index_map_.end();
906 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800907 // Erase the element we stored earlier since we are exiting the function.
Vladimir Markof25cc732017-03-16 16:18:15 +0000908 auto it = visited->find(klass.Ptr());
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800909 DCHECK(it != visited->end());
910 visited->erase(it);
911 // Only store result if it is true or none of the calls early exited due to circular
912 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
913 // a child call and we can remember the result.
914 if (result == true || !my_early_exit || visited->empty()) {
Vladimir Markof25cc732017-03-16 16:18:15 +0000915 prune_class_memo_[klass.Ptr()] = result;
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800916 }
917 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800918 return result;
919}
920
Vladimir Markof25cc732017-03-16 16:18:15 +0000921bool ImageWriter::KeepClass(ObjPtr<mirror::Class> klass) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800922 if (klass == nullptr) {
923 return false;
924 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800925 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
926 // Already in boot image, return true.
927 return true;
928 }
929 std::string temp;
930 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
931 return false;
932 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800933 if (compile_app_image_) {
934 // For app images, we need to prune boot loader classes that are not in the boot image since
935 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800936 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800937 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800938 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800939 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700940}
941
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000942class ImageWriter::PruneClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700943 public:
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000944 PruneClassesVisitor(ImageWriter* image_writer, ObjPtr<mirror::ClassLoader> class_loader)
945 : image_writer_(image_writer),
946 class_loader_(class_loader),
947 classes_to_prune_(),
948 defined_class_count_(0u) { }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700949
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000950 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700951 if (!image_writer_->KeepClass(klass.Ptr())) {
952 classes_to_prune_.insert(klass.Ptr());
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000953 if (klass->GetClassLoader() == class_loader_) {
954 ++defined_class_count_;
955 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700956 }
957 return true;
958 }
959
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000960 size_t Prune() REQUIRES_SHARED(Locks::mutator_lock_) {
961 ClassTable* class_table =
962 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader_);
963 for (mirror::Class* klass : classes_to_prune_) {
964 std::string storage;
965 const char* descriptor = klass->GetDescriptor(&storage);
966 bool result = class_table->Remove(descriptor);
967 DCHECK(result);
968 DCHECK(!class_table->Remove(descriptor)) << descriptor;
969 }
970 return defined_class_count_;
971 }
972
973 private:
Vladimir Markocb5ab352016-11-30 15:31:13 +0000974 ImageWriter* const image_writer_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000975 const ObjPtr<mirror::ClassLoader> class_loader_;
976 std::unordered_set<mirror::Class*> classes_to_prune_;
977 size_t defined_class_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700978};
979
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000980class ImageWriter::PruneClassLoaderClassesVisitor : public ClassLoaderVisitor {
981 public:
982 explicit PruneClassLoaderClassesVisitor(ImageWriter* image_writer)
983 : image_writer_(image_writer), removed_class_count_(0) {}
984
985 virtual void Visit(ObjPtr<mirror::ClassLoader> class_loader) OVERRIDE
986 REQUIRES_SHARED(Locks::mutator_lock_) {
987 PruneClassesVisitor classes_visitor(image_writer_, class_loader);
988 ClassTable* class_table =
989 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader);
990 class_table->Visit(classes_visitor);
991 removed_class_count_ += classes_visitor.Prune();
Vladimir Markof25cc732017-03-16 16:18:15 +0000992
993 // Record app image class loader. The fake boot class loader should not get registered
994 // and we should end up with only one class loader for an app and none for boot image.
995 if (class_loader != nullptr && class_table != nullptr) {
996 DCHECK(class_loader_ == nullptr);
997 class_loader_ = class_loader;
998 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000999 }
1000
1001 size_t GetRemovedClassCount() const {
1002 return removed_class_count_;
1003 }
1004
Vladimir Markof25cc732017-03-16 16:18:15 +00001005 ObjPtr<mirror::ClassLoader> GetClassLoader() const REQUIRES_SHARED(Locks::mutator_lock_) {
1006 return class_loader_;
1007 }
1008
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001009 private:
1010 ImageWriter* const image_writer_;
1011 size_t removed_class_count_;
Vladimir Markof25cc732017-03-16 16:18:15 +00001012 ObjPtr<mirror::ClassLoader> class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001013};
1014
1015void ImageWriter::VisitClassLoaders(ClassLoaderVisitor* visitor) {
1016 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1017 visitor->Visit(nullptr); // Visit boot class loader.
1018 Runtime::Current()->GetClassLinker()->VisitClassLoaders(visitor);
1019}
1020
Vladimir Markof25cc732017-03-16 16:18:15 +00001021void ImageWriter::PruneAndPreloadDexCache(ObjPtr<mirror::DexCache> dex_cache,
1022 ObjPtr<mirror::ClassLoader> class_loader) {
1023 // To ensure deterministic contents of the hash-based arrays, each slot shall contain
1024 // the candidate with the lowest index. As we're processing entries in increasing index
1025 // order, this means trying to look up the entry for the current index if the slot is
1026 // empty or if it contains a higher index.
1027
1028 Runtime* runtime = Runtime::Current();
1029 ClassLinker* class_linker = runtime->GetClassLinker();
Vladimir Markof25cc732017-03-16 16:18:15 +00001030 const DexFile& dex_file = *dex_cache->GetDexFile();
1031 // Prune methods.
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001032 mirror::MethodDexCacheType* resolved_methods = dex_cache->GetResolvedMethods();
1033 dex::TypeIndex last_class_idx; // Initialized to invalid index.
1034 ObjPtr<mirror::Class> last_class = nullptr;
1035 for (size_t i = 0, num = dex_cache->GetDexFile()->NumMethodIds(); i != num; ++i) {
1036 uint32_t slot_idx = dex_cache->MethodSlotIndex(i);
1037 auto pair =
1038 mirror::DexCache::GetNativePairPtrSize(resolved_methods, slot_idx, target_ptr_size_);
1039 uint32_t stored_index = pair.index;
1040 ArtMethod* method = pair.object;
1041 if (method != nullptr && i > stored_index) {
1042 continue; // Already checked.
1043 }
Vladimir Marko3b155452017-07-05 11:41:33 +01001044 // Check if the referenced class is in the image. Note that we want to check the referenced
1045 // class rather than the declaring class to preserve the semantics, i.e. using a MethodId
1046 // results in resolving the referenced class and that can for example throw OOME.
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001047 const DexFile::MethodId& method_id = dex_file.GetMethodId(i);
1048 if (method_id.class_idx_ != last_class_idx) {
1049 last_class_idx = method_id.class_idx_;
1050 last_class = class_linker->LookupResolvedType(
1051 dex_file, last_class_idx, dex_cache, class_loader);
1052 if (last_class != nullptr && !KeepClass(last_class)) {
1053 last_class = nullptr;
1054 }
1055 }
1056 if (method == nullptr || i < stored_index) {
1057 if (last_class != nullptr) {
1058 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
1059 Signature signature = dex_file.GetMethodSignature(method_id);
1060 if (last_class->IsInterface()) {
1061 method = last_class->FindInterfaceMethod(name, signature, target_ptr_size_);
1062 } else {
1063 method = last_class->FindClassMethod(name, signature, target_ptr_size_);
1064 }
1065 if (method != nullptr) {
1066 // If the referenced class is in the image, the defining class must also be there.
1067 DCHECK(KeepClass(method->GetDeclaringClass()));
1068 dex_cache->SetResolvedMethod(i, method, target_ptr_size_);
1069 }
1070 }
1071 } else {
1072 DCHECK_EQ(i, stored_index);
1073 if (last_class == nullptr) {
1074 dex_cache->ClearResolvedMethod(stored_index, target_ptr_size_);
1075 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001076 }
1077 }
1078 // Prune fields and make the contents of the field array deterministic.
1079 mirror::FieldDexCacheType* resolved_fields = dex_cache->GetResolvedFields();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001080 last_class_idx = dex::TypeIndex(); // Initialized to invalid index.
1081 last_class = nullptr;
Vladimir Markof25cc732017-03-16 16:18:15 +00001082 for (size_t i = 0, end = dex_file.NumFieldIds(); i < end; ++i) {
1083 uint32_t slot_idx = dex_cache->FieldSlotIndex(i);
1084 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_fields, slot_idx, target_ptr_size_);
1085 uint32_t stored_index = pair.index;
1086 ArtField* field = pair.object;
1087 if (field != nullptr && i > stored_index) {
1088 continue; // Already checked.
1089 }
1090 // Check if the referenced class is in the image. Note that we want to check the referenced
1091 // class rather than the declaring class to preserve the semantics, i.e. using a FieldId
1092 // results in resolving the referenced class and that can for example throw OOME.
1093 const DexFile::FieldId& field_id = dex_file.GetFieldId(i);
1094 if (field_id.class_idx_ != last_class_idx) {
1095 last_class_idx = field_id.class_idx_;
1096 last_class = class_linker->LookupResolvedType(
1097 dex_file, last_class_idx, dex_cache, class_loader);
1098 if (last_class != nullptr && !KeepClass(last_class)) {
1099 last_class = nullptr;
1100 }
1101 }
1102 if (field == nullptr || i < stored_index) {
1103 if (last_class != nullptr) {
1104 const char* name = dex_file.StringDataByIdx(field_id.name_idx_);
1105 const char* type = dex_file.StringByTypeIdx(field_id.type_idx_);
1106 field = mirror::Class::FindField(Thread::Current(), last_class, name, type);
1107 if (field != nullptr) {
1108 // If the referenced class is in the image, the defining class must also be there.
1109 DCHECK(KeepClass(field->GetDeclaringClass()));
1110 dex_cache->SetResolvedField(i, field, target_ptr_size_);
1111 }
1112 }
1113 } else {
1114 DCHECK_EQ(i, stored_index);
1115 if (last_class == nullptr) {
1116 dex_cache->ClearResolvedField(stored_index, target_ptr_size_);
1117 }
1118 }
1119 }
1120 // Prune types and make the contents of the type array deterministic.
1121 // This is done after fields and methods as their lookup can touch the types array.
1122 for (size_t i = 0, end = dex_cache->GetDexFile()->NumTypeIds(); i < end; ++i) {
1123 dex::TypeIndex type_idx(i);
1124 uint32_t slot_idx = dex_cache->TypeSlotIndex(type_idx);
1125 mirror::TypeDexCachePair pair =
1126 dex_cache->GetResolvedTypes()[slot_idx].load(std::memory_order_relaxed);
1127 uint32_t stored_index = pair.index;
1128 ObjPtr<mirror::Class> klass = pair.object.Read();
1129 if (klass == nullptr || i < stored_index) {
1130 klass = class_linker->LookupResolvedType(dex_file, type_idx, dex_cache, class_loader);
1131 if (klass != nullptr) {
1132 DCHECK_EQ(dex_cache->GetResolvedType(type_idx), klass);
1133 stored_index = i; // For correct clearing below if not keeping the `klass`.
1134 }
1135 } else if (i == stored_index && !KeepClass(klass)) {
1136 dex_cache->ClearResolvedType(dex::TypeIndex(stored_index));
1137 }
1138 }
1139 // Strings do not need pruning, but the contents of the string array must be deterministic.
1140 for (size_t i = 0, end = dex_cache->GetDexFile()->NumStringIds(); i < end; ++i) {
1141 dex::StringIndex string_idx(i);
1142 uint32_t slot_idx = dex_cache->StringSlotIndex(string_idx);
1143 mirror::StringDexCachePair pair =
1144 dex_cache->GetStrings()[slot_idx].load(std::memory_order_relaxed);
1145 uint32_t stored_index = pair.index;
1146 ObjPtr<mirror::String> string = pair.object.Read();
1147 if (string == nullptr || i < stored_index) {
1148 string = class_linker->LookupString(dex_file, string_idx, dex_cache);
1149 DCHECK(string == nullptr || dex_cache->GetResolvedString(string_idx) == string);
1150 }
1151 }
1152}
1153
Brian Carlstrom7940e442013-07-12 13:46:57 -07001154void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001155 Runtime* runtime = Runtime::Current();
1156 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001157 Thread* self = Thread::Current();
Vladimir Markof25cc732017-03-16 16:18:15 +00001158 ScopedAssertNoThreadSuspension sa(__FUNCTION__);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001159
Mathieu Chartier72041a02017-07-14 18:23:25 -07001160 // Prune uses-library dex caches. Only prune the uses-library dex caches since we want to make
1161 // sure the other ones don't get unloaded before the OatWriter runs.
1162 class_linker->VisitClassTables(
1163 [&](ClassTable* table) REQUIRES_SHARED(Locks::mutator_lock_) {
1164 table->RemoveStrongRoots(
1165 [&](GcRoot<mirror::Object> root) REQUIRES_SHARED(Locks::mutator_lock_) {
1166 ObjPtr<mirror::Object> obj = root.Read();
1167 if (obj->IsDexCache()) {
1168 // Return true if the dex file is not one of the ones in the map.
1169 return dex_file_oat_index_map_.find(obj->AsDexCache()->GetDexFile()) ==
1170 dex_file_oat_index_map_.end();
1171 }
1172 // Return false to avoid removing.
1173 return false;
1174 });
1175 });
Mathieu Chartier696632e2016-06-03 17:47:32 -07001176
Brian Carlstrom7940e442013-07-12 13:46:57 -07001177 // Remove the undesired classes from the class roots.
Vladimir Markof25cc732017-03-16 16:18:15 +00001178 ObjPtr<mirror::ClassLoader> class_loader;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001179 {
1180 PruneClassLoaderClassesVisitor class_loader_visitor(this);
1181 VisitClassLoaders(&class_loader_visitor);
1182 VLOG(compiler) << "Pruned " << class_loader_visitor.GetRemovedClassCount() << " classes";
Vladimir Markof25cc732017-03-16 16:18:15 +00001183 class_loader = class_loader_visitor.GetClassLoader();
1184 DCHECK_EQ(class_loader != nullptr, compile_app_image_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001185 }
1186
1187 // Clear references to removed classes from the DexCaches.
Vladimir Markof25cc732017-03-16 16:18:15 +00001188 std::vector<ObjPtr<mirror::DexCache>> dex_caches;
1189 {
1190 ReaderMutexLock mu2(self, *Locks::dex_lock_);
1191 dex_caches.reserve(class_linker->GetDexCachesData().size());
1192 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1193 if (self->IsJWeakCleared(data.weak_root)) {
1194 continue;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001195 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001196 dex_caches.push_back(self->DecodeJObject(data.weak_root)->AsDexCache());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001197 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001198 }
1199 for (ObjPtr<mirror::DexCache> dex_cache : dex_caches) {
1200 PruneAndPreloadDexCache(dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001201 }
Andreas Gampe8ac75952015-06-02 21:01:45 -07001202
1203 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
1204 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001205
1206 // Clear to save RAM.
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00001207 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001208}
1209
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001210void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001211 if (compiler_driver_.GetImageClasses() != nullptr) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001212 auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1213 if (obj->IsClass() && !IsInBootImage(obj)) {
1214 Class* klass = obj->AsClass();
1215 if (!KeepClass(klass)) {
1216 DumpImageClasses();
1217 std::string temp;
1218 CHECK(KeepClass(klass))
1219 << Runtime::Current()->GetHeap()->GetVerification()->FirstPathFromRootSet(klass);
1220 }
1221 }
1222 };
Mathieu Chartier590fee92013-09-13 13:46:47 -07001223 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001224 heap->VisitObjects(visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001225 }
1226}
1227
1228void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001229 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001230 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001231 for (const std::string& image_class : *image_classes) {
1232 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001233 }
1234}
1235
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001236mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
1237 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +00001238 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001239 ObjPtr<mirror::String> const found = image_info.intern_table_->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001240 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
1241 << string->ToModifiedUtf8();
1242 if (found != nullptr) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001243 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001244 }
1245 }
1246 if (compile_app_image_) {
1247 Runtime* const runtime = Runtime::Current();
Mathieu Chartier9e868092016-10-31 14:58:04 -07001248 ObjPtr<mirror::String> found = runtime->GetInternTable()->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001249 // If we found it in the runtime intern table it could either be in the boot image or interned
1250 // during app image compilation. If it was in the boot image return that, otherwise return null
1251 // since it belongs to another image space.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001252 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found.Ptr())) {
1253 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001254 }
1255 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
1256 << string->ToModifiedUtf8();
1257 }
1258 return nullptr;
1259}
1260
Brian Carlstrom7940e442013-07-12 13:46:57 -07001261
Vladimir Marko944da602016-02-19 12:27:55 +00001262ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001263 Runtime* runtime = Runtime::Current();
1264 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001265 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001266 StackHandleScope<3> hs(self);
1267 Handle<Class> object_array_class(hs.NewHandle(
1268 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001269
Jeff Haodcdc85b2015-12-04 14:06:18 -08001270 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +00001271 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001272 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +00001273 size_t image_oat_index = pair.second;
1274 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001275 image_dex_files.insert(image_dex_file);
1276 }
1277 }
1278
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001279 // build an Object[] of all the DexCaches used in the source_space_.
1280 // Since we can't hold the dex lock when allocating the dex_caches
1281 // ObjectArray, we lock the dex lock twice, first to get the number
1282 // of dex caches first and then lock it again to copy the dex
1283 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001284 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001285 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001286 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001287 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001288 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001289 ObjPtr<mirror::DexCache> dex_cache =
1290 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001291 if (dex_cache == nullptr) {
1292 continue;
1293 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001294 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001295 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001296 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1297 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001298 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001299 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001300 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001301 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001302 CHECK(dex_caches != nullptr) << "Failed to allocate a dex cache array.";
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001303 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001304 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001305 size_t non_image_dex_caches = 0;
1306 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001307 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001308 ObjPtr<mirror::DexCache> dex_cache =
1309 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001310 if (dex_cache == nullptr) {
1311 continue;
1312 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001313 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001314 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001315 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1316 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001317 }
1318 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1319 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001320 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001321 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001322 ObjPtr<mirror::DexCache> dex_cache =
1323 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001324 if (dex_cache == nullptr) {
1325 continue;
1326 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001327 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001328 if (!IsInBootImage(dex_cache.Ptr()) &&
1329 image_dex_files.find(dex_file) != image_dex_files.end()) {
1330 dex_caches->Set<false>(i, dex_cache.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001331 ++i;
1332 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001333 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001334 }
1335
1336 // build an Object[] of the roots needed to restore the runtime
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001337 int32_t image_roots_size = ImageHeader::NumberOfImageRoots(compile_app_image_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001338 auto image_roots(hs.NewHandle(
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001339 ObjectArray<Object>::Alloc(self, object_array_class.Get(), image_roots_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001340 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001341 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001342 // image_roots[ImageHeader::kClassLoader] will be set later for app image.
1343 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1344 "Class loader should be the last image root.");
1345 for (int32_t i = 0; i < ImageHeader::kImageRootsMax - 1; ++i) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001346 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001347 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001348 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001349}
1350
Mathieu Chartier496577f2016-09-20 15:33:31 -07001351mirror::Object* ImageWriter::TryAssignBinSlot(WorkStack& work_stack,
1352 mirror::Object* obj,
1353 size_t oat_index) {
1354 if (obj == nullptr || IsInBootImage(obj)) {
1355 // Object is null or already in the image, there is no work to do.
1356 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001357 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001358 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001359 // We want to intern all strings but also assign offsets for the source string. Since the
1360 // pruning phase has already happened, if we intern a string to one in the image we still
1361 // end up copying an unreachable string.
1362 if (obj->IsString()) {
1363 // Need to check if the string is already interned in another image info so that we don't have
1364 // the intern tables of two different images contain the same string.
1365 mirror::String* interned = FindInternedString(obj->AsString());
1366 if (interned == nullptr) {
1367 // Not in another image space, insert to our table.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001368 interned =
1369 GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString()).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001370 DCHECK_EQ(interned, obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001371 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001372 } else if (obj->IsDexCache()) {
1373 oat_index = GetOatIndexForDexCache(obj->AsDexCache());
1374 } else if (obj->IsClass()) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001375 // Visit and assign offsets for fields and field arrays.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001376 mirror::Class* as_klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001377 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Vladimir Marko72ab6842017-01-20 19:32:50 +00001378 DCHECK(!as_klass->IsErroneous()) << as_klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001379 if (compile_app_image_) {
1380 // Extra sanity, no boot loader classes should be left!
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00001381 CHECK(!IsBootClassLoaderClass(as_klass)) << as_klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001382 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001383 LengthPrefixedArray<ArtField>* fields[] = {
1384 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1385 };
Mathieu Chartier496577f2016-09-20 15:33:31 -07001386 // Overwrite the oat index value since the class' dex cache is more accurate of where it
1387 // belongs.
1388 oat_index = GetOatIndexForDexCache(dex_cache);
Vladimir Marko944da602016-02-19 12:27:55 +00001389 ImageInfo& image_info = GetImageInfo(oat_index);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001390 if (!compile_app_image_) {
1391 // Note: Avoid locking to prevent lock order violations from root visiting;
1392 // image_info.class_table_ is only accessed from the image writer.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001393 image_info.class_table_->InsertWithoutLocks(as_klass);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001394 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001395 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1396 // Total array length including header.
1397 if (cur_fields != nullptr) {
1398 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1399 // Forward the entire array at once.
1400 auto it = native_object_relocations_.find(cur_fields);
1401 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1402 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001403 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001404 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001405 native_object_relocations_.emplace(
1406 cur_fields,
1407 NativeObjectRelocation {
1408 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1409 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001410 offset += header_size;
1411 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001412 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001413 // Need to forward arrays separate of fields.
1414 ArtField* field = &cur_fields->At(i);
1415 auto it2 = native_object_relocations_.find(field);
1416 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
David Sehr709b0702016-10-13 09:12:37 -07001417 << " already assigned " << field->PrettyField() << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001418 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001419 native_object_relocations_.emplace(
1420 field,
1421 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001422 offset += sizeof(ArtField);
1423 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001424 }
1425 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001426 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001427 size_t num_methods = as_klass->NumMethods();
1428 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001429 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001430 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1431 if (WillMethodBeDirty(&m)) {
1432 any_dirty = true;
1433 break;
1434 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001435 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001436 NativeObjectRelocationType type = any_dirty
1437 ? kNativeObjectRelocationTypeArtMethodDirty
1438 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001439 Bin bin_type = BinTypeForNativeRelocationType(type);
1440 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001441 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1442 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001443 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1444 method_size,
1445 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001446 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001447 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001448 CHECK(it == native_object_relocations_.end())
1449 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001450 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001451 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001452 native_object_relocations_.emplace(array,
1453 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001454 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001455 offset,
1456 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1457 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001458 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001459 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001460 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001461 }
Alex Lighte64300b2015-12-15 15:02:47 -08001462 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001463 }
1464 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1465 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001466 if (as_klass->ShouldHaveImt()) {
1467 ImTable* imt = as_klass->GetImt(target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001468 if (TryAssignImTableOffset(imt, oat_index)) {
1469 // Since imt's can be shared only do this the first time to not double count imt method
1470 // fixups.
1471 for (size_t i = 0; i < ImTable::kSize; ++i) {
1472 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
1473 DCHECK(imt_method != nullptr);
1474 if (imt_method->IsRuntimeMethod() &&
1475 !IsInBootImage(imt_method) &&
1476 !NativeRelocationAssigned(imt_method)) {
1477 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
1478 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001479 }
1480 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001481 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001482 } else if (obj->IsClassLoader()) {
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001483 // Register the class loader if it has a class table.
1484 // The fake boot class loader should not get registered and we should end up with only one
1485 // class loader.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001486 mirror::ClassLoader* class_loader = obj->AsClassLoader();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001487 if (class_loader->GetClassTable() != nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001488 DCHECK(compile_app_image_);
1489 DCHECK(class_loaders_.empty());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001490 class_loaders_.insert(class_loader);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001491 ImageInfo& image_info = GetImageInfo(oat_index);
1492 // Note: Avoid locking to prevent lock order violations from root visiting;
1493 // image_info.class_table_ table is only accessed from the image writer
1494 // and class_loader->GetClassTable() is iterated but not modified.
1495 image_info.class_table_->CopyWithoutLocks(*class_loader->GetClassTable());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001496 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001497 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001498 AssignImageBinSlot(obj, oat_index);
1499 work_stack.emplace(obj, oat_index);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001500 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001501 if (obj->IsString()) {
1502 // Always return the interned string if there exists one.
1503 mirror::String* interned = FindInternedString(obj->AsString());
1504 if (interned != nullptr) {
1505 return interned;
1506 }
1507 }
1508 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001509}
1510
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001511bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1512 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1513}
1514
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001515bool ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001516 // No offset, or already assigned.
1517 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001518 return false;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001519 }
1520 // If the method is a conflict method we also want to assign the conflict table offset.
1521 ImageInfo& image_info = GetImageInfo(oat_index);
1522 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1523 native_object_relocations_.emplace(
1524 imt,
1525 NativeObjectRelocation {
1526 oat_index,
1527 image_info.bin_slot_sizes_[kBinImTable],
1528 kNativeObjectRelocationTypeIMTable});
1529 image_info.bin_slot_sizes_[kBinImTable] += size;
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001530 return true;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001531}
1532
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001533void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1534 // No offset, or already assigned.
1535 if (table == nullptr || NativeRelocationAssigned(table)) {
1536 return;
1537 }
1538 CHECK(!IsInBootImage(table));
1539 // If the method is a conflict method we also want to assign the conflict table offset.
1540 ImageInfo& image_info = GetImageInfo(oat_index);
1541 const size_t size = table->ComputeSize(target_ptr_size_);
1542 native_object_relocations_.emplace(
1543 table,
1544 NativeObjectRelocation {
1545 oat_index,
1546 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1547 kNativeObjectRelocationTypeIMTConflictTable});
1548 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1549}
1550
Jeff Haodcdc85b2015-12-04 14:06:18 -08001551void ImageWriter::AssignMethodOffset(ArtMethod* method,
1552 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001553 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001554 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001555 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
David Sehr709b0702016-10-13 09:12:37 -07001556 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001557 if (method->IsRuntimeMethod()) {
1558 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1559 }
Vladimir Marko944da602016-02-19 12:27:55 +00001560 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001561 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001562 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001563 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001564}
1565
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001566void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001567 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001568 CHECK(obj != nullptr);
1569
1570 // We know the bin slot, and the total bin sizes for all objects by now,
1571 // so calculate the object's final image offset.
1572
1573 DCHECK(IsImageBinSlotAssigned(obj));
1574 BinSlot bin_slot = GetImageBinSlot(obj);
1575 // Change the lockword from a bin slot into an offset
1576 AssignImageOffset(obj, bin_slot);
1577}
1578
Mathieu Chartier496577f2016-09-20 15:33:31 -07001579class ImageWriter::VisitReferencesVisitor {
1580 public:
1581 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index)
1582 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {}
1583
1584 // Fix up separately since we also need to fix up method entrypoints.
1585 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1586 REQUIRES_SHARED(Locks::mutator_lock_) {
1587 if (!root->IsNull()) {
1588 VisitRoot(root);
1589 }
1590 }
1591
1592 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1593 REQUIRES_SHARED(Locks::mutator_lock_) {
1594 root->Assign(VisitReference(root->AsMirrorPtr()));
1595 }
1596
Mathieu Chartier31e88222016-10-14 18:43:19 -07001597 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
Mathieu Chartier496577f2016-09-20 15:33:31 -07001598 MemberOffset offset,
1599 bool is_static ATTRIBUTE_UNUSED) const
1600 REQUIRES_SHARED(Locks::mutator_lock_) {
1601 mirror::Object* ref =
1602 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1603 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1604 }
1605
Mathieu Chartier31e88222016-10-14 18:43:19 -07001606 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1607 ObjPtr<mirror::Reference> ref) const
Mathieu Chartier496577f2016-09-20 15:33:31 -07001608 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001609 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001610 }
1611
1612 private:
1613 mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1614 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_);
1615 }
1616
1617 ImageWriter* const image_writer_;
1618 WorkStack* const work_stack_;
1619 const size_t oat_index_;
1620};
1621
1622class ImageWriter::GetRootsVisitor : public RootVisitor {
1623 public:
1624 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {}
1625
1626 void VisitRoots(mirror::Object*** roots,
1627 size_t count,
1628 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1629 REQUIRES_SHARED(Locks::mutator_lock_) {
1630 for (size_t i = 0; i < count; ++i) {
1631 roots_->push_back(*roots[i]);
1632 }
1633 }
1634
1635 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1636 size_t count,
1637 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1638 REQUIRES_SHARED(Locks::mutator_lock_) {
1639 for (size_t i = 0; i < count; ++i) {
1640 roots_->push_back(roots[i]->AsMirrorPtr());
1641 }
1642 }
1643
1644 private:
1645 std::vector<mirror::Object*>* const roots_;
1646};
1647
1648void ImageWriter::ProcessWorkStack(WorkStack* work_stack) {
1649 while (!work_stack->empty()) {
1650 std::pair<mirror::Object*, size_t> pair(work_stack->top());
1651 work_stack->pop();
1652 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second);
1653 // Walk references and assign bin slots for them.
1654 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1655 visitor,
1656 visitor);
1657 }
1658}
1659
Vladimir Markof4da6752014-08-01 19:04:18 +01001660void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001661 Thread* const self = Thread::Current();
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07001662 VariableSizedHandleScope handles(self);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001663 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001664 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1665 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001666 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001667
Mathieu Chartier496577f2016-09-20 15:33:31 -07001668 Runtime* const runtime = Runtime::Current();
1669 gc::Heap* const heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001670
Mathieu Chartier31e89252013-08-28 11:29:12 -07001671 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001672 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001673 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001674
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001675 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001676 // Write the image runtime methods.
1677 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1678 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1679 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001680 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001681 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves);
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001682 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001683 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly);
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001684 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001685 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001686 image_methods_[ImageHeader::kSaveEverythingMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001687 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything);
Mingyao Yang0a87a652017-04-12 13:43:15 -07001688 image_methods_[ImageHeader::kSaveEverythingMethodForClinit] =
1689 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForClinit);
1690 image_methods_[ImageHeader::kSaveEverythingMethodForSuspendCheck] =
1691 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForSuspendCheck);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001692 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001693 for (auto* m : image_methods_) {
1694 CHECK(m != nullptr);
1695 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001696 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1697 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001698 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001699 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001700 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001701
Mathieu Chartier496577f2016-09-20 15:33:31 -07001702 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
1703 // this lock while holding other locks may cause lock order violations.
Andreas Gampe1c158a02017-07-13 17:26:19 -07001704 {
1705 auto deflate_monitor = [](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1706 Monitor::Deflate(Thread::Current(), obj);
1707 };
1708 heap->VisitObjects(deflate_monitor);
1709 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001710
1711 // Work list of <object, oat_index> for objects. Everything on the stack must already be
1712 // assigned a bin slot.
1713 WorkStack work_stack;
1714
1715 // Special case interned strings to put them in the image they are likely to be resolved from.
1716 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
1717 auto it = dex_file_oat_index_map_.find(dex_file);
1718 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1719 const size_t oat_index = it->second;
1720 InternTable* const intern_table = runtime->GetInternTable();
1721 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
1722 uint32_t utf16_length;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001723 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(dex::StringIndex(i),
1724 &utf16_length);
Mathieu Chartier9e868092016-10-31 14:58:04 -07001725 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001726 TryAssignBinSlot(work_stack, string, oat_index);
1727 }
1728 }
1729
1730 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor
1731 // visits roots while holding various locks.
1732 {
1733 std::vector<mirror::Object*> roots;
1734 GetRootsVisitor root_visitor(&roots);
1735 runtime->VisitRoots(&root_visitor);
1736 for (mirror::Object* obj : roots) {
1737 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex());
1738 }
1739 }
1740 ProcessWorkStack(&work_stack);
1741
1742 // For app images, there may be objects that are only held live by the by the boot image. One
1743 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback
1744 // does not fail any checks. TODO: We should probably avoid copying these objects.
1745 if (compile_app_image_) {
1746 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) {
1747 DCHECK(space->IsImageSpace());
1748 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1749 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1750 reinterpret_cast<uintptr_t>(space->Limit()),
1751 [this, &work_stack](mirror::Object* obj)
1752 REQUIRES_SHARED(Locks::mutator_lock_) {
1753 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex());
1754 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot).
1755 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1756 visitor,
1757 visitor);
1758 });
1759 }
1760 // Process the work stack in case anything was added by TryAssignBinSlot.
1761 ProcessWorkStack(&work_stack);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001762
1763 // Store the class loader in the class roots.
1764 CHECK_EQ(class_loaders_.size(), 1u);
1765 CHECK_EQ(image_roots.size(), 1u);
1766 CHECK(*class_loaders_.begin() != nullptr);
1767 image_roots[0]->Set<false>(ImageHeader::kClassLoader, *class_loaders_.begin());
Mathieu Chartier496577f2016-09-20 15:33:31 -07001768 }
1769
1770 // Verify that all objects have assigned image bin slots.
Andreas Gampe1c158a02017-07-13 17:26:19 -07001771 {
1772 auto ensure_bin_slots_assigned = [&](mirror::Object* obj)
1773 REQUIRES_SHARED(Locks::mutator_lock_) {
1774 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) {
1775 CHECK(IsImageBinSlotAssigned(obj)) << mirror::Object::PrettyTypeOf(obj) << " " << obj;
1776 }
1777 };
1778 heap->VisitObjects(ensure_bin_slots_assigned);
1779 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001780
Vladimir Marko05792b92015-08-03 11:56:49 +01001781 // Calculate size of the dex cache arrays slot and prepare offsets.
1782 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001783
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001784 // Calculate the sizes of the intern tables, class tables, and fixup tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001785 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001786 // Calculate how big the intern table will be after being serialized.
1787 InternTable* const intern_table = image_info.intern_table_.get();
1788 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
Vladimir Marko1a1de672016-10-13 12:53:15 +01001789 if (intern_table->StrongSize() != 0u) {
1790 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1791 }
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001792
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001793 // Calculate the size of the class table.
1794 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001795 DCHECK_EQ(image_info.class_table_->NumReferencedZygoteClasses(), 0u);
1796 if (image_info.class_table_->NumReferencedNonZygoteClasses() != 0u) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001797 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
1798 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001799 }
1800
Vladimir Markocf36d492015-08-12 19:27:26 +01001801 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001802 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001803 size_t bin_offset = image_objects_offset_begin_;
1804 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001805 switch (i) {
1806 case kBinArtMethodClean:
1807 case kBinArtMethodDirty: {
1808 bin_offset = RoundUp(bin_offset, method_alignment);
1809 break;
1810 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001811 case kBinDexCacheArray:
Vladimir Markof44d36c2017-03-14 14:18:46 +00001812 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment(target_ptr_size_));
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001813 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001814 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001815 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001816 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001817 break;
1818 }
1819 default: {
1820 // Normal alignment.
1821 }
1822 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001823 image_info.bin_slot_offsets_[i] = bin_offset;
1824 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001825 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001826 // NOTE: There may be additional padding between the bin slots and the intern table.
1827 DCHECK_EQ(image_info.image_end_,
1828 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001829 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001830
Jeff Haodcdc85b2015-12-04 14:06:18 -08001831 // Calculate image offsets.
1832 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001833 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001834 image_info.image_begin_ = global_image_begin_ + image_offset;
1835 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001836 ImageSection unused_sections[ImageHeader::kSectionCount];
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001837 image_info.image_size_ =
1838 RoundUp(image_info.CreateImageSections(unused_sections, compile_app_image_), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001839 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001840 image_offset += image_info.image_size_;
1841 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001842
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001843 // Transform each object's bin slot into an offset which will be used to do the final copy.
Andreas Gampe1c158a02017-07-13 17:26:19 -07001844 {
1845 auto unbin_objects_into_offset = [&](mirror::Object* obj)
1846 REQUIRES_SHARED(Locks::mutator_lock_) {
1847 if (!IsInBootImage(obj)) {
1848 UnbinObjectsIntoOffset(obj);
1849 }
1850 };
1851 heap->VisitObjects(unbin_objects_into_offset);
1852 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001853
Jeff Haodcdc85b2015-12-04 14:06:18 -08001854 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001855 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001856 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1857 i++;
1858 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001859
Mathieu Chartiere401d142015-04-22 13:56:20 -07001860 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001861 for (auto& pair : native_object_relocations_) {
1862 NativeObjectRelocation& relocation = pair.second;
1863 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001864 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001865 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001866 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001867}
1868
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001869size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections,
1870 bool app_image) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001871 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001872
1873 // Do not round up any sections here that are represented by the bins since it will break
1874 // offsets.
1875
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001876 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001877 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001878 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001879
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001880 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001881 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1882 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001883 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001884
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001885 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001886 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1887 *methods_section = ImageSection(
1888 bin_slot_offsets_[kBinArtMethodClean],
1889 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1890
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001891 // IMT section.
1892 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1893 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1894
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001895 // Conflict tables section.
1896 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1897 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1898 bin_slot_sizes_[kBinIMTConflictTable]);
1899
1900 // Runtime methods section.
1901 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1902 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1903 bin_slot_sizes_[kBinRuntimeMethod]);
1904
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001905 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001906 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1907 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1908 bin_slot_sizes_[kBinDexCacheArray]);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001909 // For boot image, round up to the page boundary to separate the interned strings and
1910 // class table from the modifiable data. We shall mprotect() these pages read-only when
1911 // we load the boot image. This is more than sufficient for the string table alignment,
1912 // namely sizeof(uint64_t). See HashSet::WriteToMemory.
1913 static_assert(IsAligned<sizeof(uint64_t)>(kPageSize), "String table alignment check.");
1914 size_t cur_pos =
1915 RoundUp(dex_cache_arrays_section->End(), app_image ? sizeof(uint64_t) : kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001916 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001917 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001918 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1919 cur_pos = interned_strings_section->End();
1920 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1921 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1922 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001923 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001924 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001925 cur_pos = class_table_section->End();
1926 // Image end goes right before the start of the image bitmap.
1927 return cur_pos;
1928}
1929
Vladimir Marko944da602016-02-19 12:27:55 +00001930void ImageWriter::CreateHeader(size_t oat_index) {
1931 ImageInfo& image_info = GetImageInfo(oat_index);
1932 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1933 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1934 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001935
1936 // Create the image sections.
1937 ImageSection sections[ImageHeader::kSectionCount];
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +01001938 const size_t image_end = image_info.CreateImageSections(sections, compile_app_image_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001939
Mathieu Chartiere401d142015-04-22 13:56:20 -07001940 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001941 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001942 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001943 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001944 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001945 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001946 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001947 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001948 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1949 ++idx;
1950 }
1951 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001952 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1953 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1954 << " Image offset=" << image_info.image_offset_ << std::dec;
1955 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1956 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1957 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1958 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001959 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001960 // Store boot image info for app image so that we can relocate.
1961 uint32_t boot_image_begin = 0;
1962 uint32_t boot_image_end = 0;
1963 uint32_t boot_oat_begin = 0;
1964 uint32_t boot_oat_end = 0;
1965 gc::Heap* const heap = Runtime::Current()->GetHeap();
1966 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001967
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001968 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1969 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001970 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1971 image_end,
1972 sections,
1973 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001974 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001975 PointerToLowMemUInt32(oat_file_begin),
1976 PointerToLowMemUInt32(image_info.oat_data_begin_),
1977 PointerToLowMemUInt32(oat_data_end),
1978 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001979 boot_image_begin,
1980 boot_image_end - boot_image_begin,
1981 boot_oat_begin,
1982 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001983 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001984 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001985 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001986 image_storage_mode_,
1987 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001988}
1989
1990ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001991 auto it = native_object_relocations_.find(method);
David Sehr709b0702016-10-13 09:12:37 -07001992 CHECK(it != native_object_relocations_.end()) << ArtMethod::PrettyMethod(method) << " @ "
1993 << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001994 size_t oat_index = GetOatIndex(method->GetDexCache());
1995 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001996 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1997 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001998}
1999
Vladimir Markoad06b982016-11-17 16:38:59 +00002000class ImageWriter::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002001 public:
2002 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
2003 }
2004
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002005 void VisitRoots(mirror::Object*** roots ATTRIBUTE_UNUSED,
2006 size_t count ATTRIBUTE_UNUSED,
2007 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002008 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002009 LOG(FATAL) << "Unsupported";
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002010 }
2011
2012 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
2013 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002014 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002015 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002016 image_writer_->CopyReference(roots[i], roots[i]->AsMirrorPtr());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002017 }
2018 }
2019
2020 private:
2021 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002022};
2023
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002024void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
2025 for (size_t i = 0; i < ImTable::kSize; ++i) {
2026 ArtMethod* method = orig->Get(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002027 void** address = reinterpret_cast<void**>(copy->AddressOfElement(i, target_ptr_size_));
2028 CopyAndFixupPointer(address, method);
2029 DCHECK_EQ(copy->Get(i, target_ptr_size_), NativeLocationInImage(method));
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002030 }
2031}
2032
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002033void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
2034 const size_t count = orig->NumEntries(target_ptr_size_);
2035 for (size_t i = 0; i < count; ++i) {
2036 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
2037 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002038 CopyAndFixupPointer(copy->AddressOfInterfaceMethod(i, target_ptr_size_), interface_method);
2039 CopyAndFixupPointer(copy->AddressOfImplementationMethod(i, target_ptr_size_),
2040 implementation_method);
2041 DCHECK_EQ(copy->GetInterfaceMethod(i, target_ptr_size_),
2042 NativeLocationInImage(interface_method));
2043 DCHECK_EQ(copy->GetImplementationMethod(i, target_ptr_size_),
2044 NativeLocationInImage(implementation_method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002045 }
2046}
2047
Vladimir Marko944da602016-02-19 12:27:55 +00002048void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002049 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002050 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002051 for (auto& pair : native_object_relocations_) {
2052 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002053 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00002054 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002055 continue;
2056 }
2057 auto* dest = image_info.image_->Begin() + relocation.offset;
2058 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002059 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002060 switch (relocation.type) {
2061 case kNativeObjectRelocationTypeArtField: {
2062 memcpy(dest, pair.first, sizeof(ArtField));
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002063 CopyReference(
2064 reinterpret_cast<ArtField*>(dest)->GetDeclaringClassAddressWithoutBarrier(),
2065 reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass().Ptr());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002066 break;
2067 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002068 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002069 case kNativeObjectRelocationTypeArtMethodClean:
2070 case kNativeObjectRelocationTypeArtMethodDirty: {
2071 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08002072 reinterpret_cast<ArtMethod*>(dest),
2073 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002074 break;
2075 }
2076 // For arrays, copy just the header since the elements will get copied by their corresponding
2077 // relocations.
2078 case kNativeObjectRelocationTypeArtFieldArray: {
2079 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
2080 break;
2081 }
2082 case kNativeObjectRelocationTypeArtMethodArrayClean:
2083 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00002084 size_t size = ArtMethod::Size(target_ptr_size_);
2085 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
2086 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
2087 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
2088 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002089 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00002090 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002091 case kNativeObjectRelocationTypeDexCacheArray:
2092 // Nothing to copy here, everything is done in FixupDexCache().
2093 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002094 case kNativeObjectRelocationTypeIMTable: {
2095 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
2096 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
2097 CopyAndFixupImTable(orig_imt, dest_imt);
2098 break;
2099 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002100 case kNativeObjectRelocationTypeIMTConflictTable: {
2101 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
2102 CopyAndFixupImtConflictTable(
2103 orig_table,
2104 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
2105 break;
2106 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002107 }
2108 }
2109 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002110 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002111 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002112 ArtMethod* method = image_methods_[i];
2113 CHECK(method != nullptr);
2114 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002115 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002116 }
2117 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002118 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002119 FixupRootVisitor root_visitor(this);
2120
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002121 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002122 if (image_info.intern_table_bytes_ > 0) {
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002123 const ImageSection& intern_table_section = image_header->GetInternedStringsSection();
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002124 InternTable* const intern_table = image_info.intern_table_.get();
2125 uint8_t* const intern_table_memory_ptr =
2126 image_info.image_->Begin() + intern_table_section.Offset();
2127 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
2128 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
2129 // Fixup the pointers in the newly written intern table to contain image addresses.
2130 InternTable temp_intern_table;
2131 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
2132 // the VisitRoots() will update the memory directly rather than the copies.
2133 // This also relies on visit roots not doing any verification which could fail after we update
2134 // the roots to be the image addresses.
2135 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
2136 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
2137 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
2138 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002139 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
2140 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002141 if (image_info.class_table_bytes_ > 0u) {
Vladimir Markocd87c3e2017-09-05 13:11:57 +01002142 const ImageSection& class_table_section = image_header->GetClassTableSection();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002143 uint8_t* const class_table_memory_ptr =
2144 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002145 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002146
2147 ClassTable* table = image_info.class_table_.get();
2148 CHECK(table != nullptr);
2149 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
2150 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
2151 // Fixup the pointers in the newly written class table to contain image addresses. See
2152 // above comment for intern tables.
2153 ClassTable temp_class_table;
2154 temp_class_table.ReadFromMemory(class_table_memory_ptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002155 CHECK_EQ(temp_class_table.NumReferencedZygoteClasses(),
2156 table->NumReferencedNonZygoteClasses() + table->NumReferencedZygoteClasses());
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002157 UnbufferedRootVisitor visitor(&root_visitor, RootInfo(kRootUnknown));
2158 temp_class_table.VisitRoots(visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002159 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002160}
2161
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08002162void ImageWriter::CopyAndFixupObjects() {
Andreas Gampe1c158a02017-07-13 17:26:19 -07002163 auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2164 DCHECK(obj != nullptr);
2165 CopyAndFixupObject(obj);
2166 };
2167 Runtime::Current()->GetHeap()->VisitObjects(visitor);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002168 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002169 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08002170 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07002171 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
2172 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002173 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002174 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002175}
2176
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002177void ImageWriter::FixupPointerArray(mirror::Object* dst,
2178 mirror::PointerArray* arr,
2179 mirror::Class* klass,
2180 Bin array_type) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002181 CHECK(klass->IsArrayClass());
David Sehr709b0702016-10-13 09:12:37 -07002182 CHECK(arr->IsIntArray() || arr->IsLongArray()) << klass->PrettyClass() << " " << arr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002183 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07002184 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002185 dst->SetClass(GetImageAddress(arr->GetClass()));
2186 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002187 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002188 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002189 if (kIsDebugBuild && elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002190 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01002191 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002192 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002193 auto* method = reinterpret_cast<ArtMethod*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07002194 LOG(FATAL) << "No relocation entry for ArtMethod " << method->PrettyMethod() << " @ "
2195 << method << " idx=" << i << "/" << num_elements << " with declaring class "
2196 << Class::PrettyClass(method->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002197 } else {
2198 CHECK_EQ(array_type, kBinArtField);
2199 auto* field = reinterpret_cast<ArtField*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07002200 LOG(FATAL) << "No relocation entry for ArtField " << field->PrettyField() << " @ "
Mathieu Chartiere401d142015-04-22 13:56:20 -07002201 << field << " idx=" << i << "/" << num_elements << " with declaring class "
David Sehr709b0702016-10-13 09:12:37 -07002202 << Class::PrettyClass(field->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002203 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002204 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002205 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002206 }
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002207 CopyAndFixupPointer(dest_array->ElementAddress(i, target_ptr_size_), elem);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002208 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002209}
2210
2211void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002212 if (IsInBootImage(obj)) {
2213 return;
2214 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002215 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00002216 size_t oat_index = GetOatIndex(obj);
2217 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002218 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
2219 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002220 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002221
Jeff Haodcdc85b2015-12-04 14:06:18 -08002222 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002223
2224 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002225 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002226 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002227
Mathieu Chartierad2541a2013-10-25 10:05:23 -07002228 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
2229 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002230 const auto it = saved_hashcode_map_.find(obj);
2231 dst->SetLockWord(it != saved_hashcode_map_.end() ?
2232 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002233 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
2234 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
2235 // safe since we mark all of the objects that may reference non immune objects as gray.
2236 CHECK(dst->AtomicSetMarkBit(0, 1));
2237 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002238 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002239}
2240
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002241// Rewrite all the references in the copied object to point to their image address equivalent
Vladimir Markoad06b982016-11-17 16:38:59 +00002242class ImageWriter::FixupVisitor {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002243 public:
2244 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
2245 }
2246
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002247 // Ignore class roots since we don't have a way to map them to the destination. These are handled
2248 // with other logic.
2249 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
2250 const {}
2251 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
2252
2253
Mathieu Chartier31e88222016-10-14 18:43:19 -07002254 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002255 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07002256 ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002257 // Copy the reference and record the fixup if necessary.
2258 image_writer_->CopyReference(
2259 copy_->GetFieldObjectReferenceAddr<kVerifyNone>(offset),
2260 ref.Ptr());
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002261 }
2262
2263 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07002264 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2265 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002266 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002267 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002268 }
2269
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002270 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002271 ImageWriter* const image_writer_;
2272 mirror::Object* const copy_;
2273};
2274
Vladimir Markoad06b982016-11-17 16:38:59 +00002275class ImageWriter::FixupClassVisitor FINAL : public FixupVisitor {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002276 public:
2277 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
2278 }
2279
Mathieu Chartier31e88222016-10-14 18:43:19 -07002280 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07002281 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002282 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002283 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002284 }
2285
Mathieu Chartier31e88222016-10-14 18:43:19 -07002286 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2287 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002288 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002289 LOG(FATAL) << "Reference not expected here.";
2290 }
2291};
2292
Vladimir Marko05792b92015-08-03 11:56:49 +01002293uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
2294 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002295 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002296 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002297 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
2298 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002299 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01002300 return relocation.offset;
2301}
2302
2303template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002304std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002305 std::ostringstream oss;
2306 oss << ptr;
2307 return oss.str();
2308}
2309
2310template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002311std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07002312 return ArtMethod::PrettyMethod(method);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002313}
2314
2315template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002316T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002317 if (obj == nullptr || IsInBootImage(obj)) {
2318 return obj;
2319 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002320 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002321 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
2322 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002323 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00002324 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002325 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002326 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002327}
2328
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002329template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08002330T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
2331 if (obj == nullptr || IsInBootImage(obj)) {
2332 return obj;
2333 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002334 size_t oat_index = GetOatIndexForDexCache(dex_cache);
2335 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002336 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
2337 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002338}
2339
Vladimir Markoad06b982016-11-17 16:38:59 +00002340class ImageWriter::NativeLocationVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002341 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002342 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002343
2344 template <typename T>
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002345 T* operator()(T* ptr, void** dest_addr = nullptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
2346 if (dest_addr != nullptr) {
2347 image_writer_->CopyAndFixupPointer(dest_addr, ptr);
2348 }
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002349 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002350 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002351
2352 private:
2353 ImageWriter* const image_writer_;
2354};
2355
2356void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002357 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002358 FixupClassVisitor visitor(this, copy);
Mathieu Chartier31e88222016-10-14 18:43:19 -07002359 ObjPtr<mirror::Object>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002360
2361 // Remove the clinitThreadId. This is required for image determinism.
2362 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002363}
2364
Ian Rogersef7d42f2014-01-06 12:55:46 -08002365void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002366 DCHECK(orig != nullptr);
2367 DCHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002368 if (kUseBakerReadBarrier) {
2369 orig->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002370 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002371 auto* klass = orig->GetClass();
2372 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002373 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07002374 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
2375 if (it != pointer_arrays_.end()) {
2376 // Should only need to fixup every pointer array exactly once.
2377 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
2378 pointer_arrays_.erase(it);
2379 return;
2380 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002381 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002382 if (orig->IsClass()) {
2383 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002384 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002385 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
2386 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01002387 auto* dest = down_cast<mirror::Executable*>(copy);
2388 auto* src = down_cast<mirror::Executable*>(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002389 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05002390 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01002391 } else if (!klass->IsArrayClass()) {
2392 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2393 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
2394 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002395 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002396 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002397 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2398 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002399 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002400 // Also set allocator to null to be safe. The allocator is created when we create the class
2401 // table. We also never expect to unload things in the image since they are held live as
2402 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002403 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002404 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002405 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002406 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002407 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002408 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002409}
2410
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002411class ImageWriter::ImageAddressVisitorForDexCacheArray {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002412 public:
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002413 explicit ImageAddressVisitorForDexCacheArray(ImageWriter* image_writer)
2414 : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002415
2416 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002417 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002418 return image_writer_->GetImageAddress(ptr);
2419 }
2420
2421 private:
2422 ImageWriter* const image_writer_;
2423};
2424
Vladimir Marko05792b92015-08-03 11:56:49 +01002425void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2426 mirror::DexCache* copy_dex_cache) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002427 ImageAddressVisitorForDexCacheArray fixup_visitor(this);
Vladimir Marko05792b92015-08-03 11:56:49 +01002428 // Though the DexCache array fields are usually treated as native pointers, we set the full
2429 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2430 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2431 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002432 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002433 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002434 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002435 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002436 PointerSize::k64);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002437 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache), fixup_visitor);
Vladimir Marko05792b92015-08-03 11:56:49 +01002438 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002439 mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
Vladimir Marko05792b92015-08-03 11:56:49 +01002440 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002441 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002442 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002443 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002444 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002445 fixup_visitor);
Vladimir Marko05792b92015-08-03 11:56:49 +01002446 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002447 mirror::MethodDexCacheType* orig_methods = orig_dex_cache->GetResolvedMethods();
Vladimir Marko05792b92015-08-03 11:56:49 +01002448 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002449 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002450 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002451 PointerSize::k64);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002452 mirror::MethodDexCacheType* copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002453 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002454 mirror::MethodDexCachePair orig_pair =
2455 mirror::DexCache::GetNativePairPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002456 // NativeLocationInImage also handles runtime methods since these have relocation info.
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002457 mirror::MethodDexCachePair copy_pair(NativeLocationInImage(orig_pair.object),
2458 orig_pair.index);
2459 mirror::DexCache::SetNativePairPtrSize(copy_methods, i, copy_pair, target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002460 }
2461 }
Vladimir Markof44d36c2017-03-14 14:18:46 +00002462 mirror::FieldDexCacheType* orig_fields = orig_dex_cache->GetResolvedFields();
Vladimir Marko05792b92015-08-03 11:56:49 +01002463 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002464 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002465 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002466 PointerSize::k64);
Vladimir Markof44d36c2017-03-14 14:18:46 +00002467 mirror::FieldDexCacheType* copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002468 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00002469 mirror::FieldDexCachePair orig =
2470 mirror::DexCache::GetNativePairPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002471 mirror::FieldDexCachePair copy = orig;
2472 copy.object = NativeLocationInImage(orig.object);
Vladimir Markof44d36c2017-03-14 14:18:46 +00002473 mirror::DexCache::SetNativePairPtrSize(copy_fields, i, copy, target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002474 }
2475 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01002476 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
2477 if (orig_method_types != nullptr) {
2478 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodTypesOffset(),
2479 NativeLocationInImage(orig_method_types),
2480 PointerSize::k64);
2481 orig_dex_cache->FixupResolvedMethodTypes(NativeCopyLocation(orig_method_types, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002482 fixup_visitor);
Narayan Kamath7fe56582016-10-14 18:49:12 +01002483 }
Orion Hodsonc069a302017-01-18 09:23:12 +00002484 GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
2485 if (orig_call_sites != nullptr) {
2486 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedCallSitesOffset(),
2487 NativeLocationInImage(orig_call_sites),
2488 PointerSize::k64);
2489 orig_dex_cache->FixupResolvedCallSites(NativeCopyLocation(orig_call_sites, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002490 fixup_visitor);
Orion Hodsonc069a302017-01-18 09:23:12 +00002491 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002492
2493 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2494 // compiler pointers in here will make the output non-deterministic.
2495 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002496}
2497
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002498const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2499 DCHECK_LT(type, kOatAddressCount);
2500 // If we are compiling an app image, we need to use the stubs of the boot image.
2501 if (compile_app_image_) {
2502 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002503 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002504 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2505 DCHECK(!image_spaces.empty());
2506 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002507 CHECK(oat_file != nullptr);
2508 const OatHeader& header = oat_file->GetOatHeader();
2509 switch (type) {
2510 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2511 case kOatAddressQuickGenericJNITrampoline:
2512 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2513 case kOatAddressInterpreterToInterpreterBridge:
2514 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2515 case kOatAddressInterpreterToCompiledCodeBridge:
2516 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2517 case kOatAddressJNIDlsymLookup:
2518 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2519 case kOatAddressQuickIMTConflictTrampoline:
2520 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2521 case kOatAddressQuickResolutionTrampoline:
2522 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2523 case kOatAddressQuickToInterpreterBridge:
2524 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2525 default:
2526 UNREACHABLE();
2527 }
2528 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002529 const ImageInfo& primary_image_info = GetImageInfo(0);
2530 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002531}
2532
Jeff Haodcdc85b2015-12-04 14:06:18 -08002533const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2534 const ImageInfo& image_info,
2535 bool* quick_is_interpreted) {
David Sehr709b0702016-10-13 09:12:37 -07002536 DCHECK(!method->IsResolutionMethod()) << method->PrettyMethod();
2537 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << method->PrettyMethod();
2538 DCHECK(!method->IsImtUnimplementedMethod()) << method->PrettyMethod();
2539 DCHECK(method->IsInvokable()) << method->PrettyMethod();
2540 DCHECK(!IsInBootImage(method)) << method->PrettyMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002541
2542 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2543 // trampoline.
2544
2545 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002546 const void* quick_oat_entry_point =
2547 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2548 const uint8_t* quick_code;
2549
2550 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2551 DCHECK(method->IsCopied());
2552 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2553 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2554 } else {
2555 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2556 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2557 }
2558
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002559 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002560 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2561 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002562 // We have code for a non-static or initialized method, just use the code.
2563 } else if (quick_code == nullptr && method->IsNative() &&
2564 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2565 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002566 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002567 } else if (quick_code == nullptr && !method->IsNative()) {
2568 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002569 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002570 *quick_is_interpreted = true;
2571 } else {
2572 CHECK(!method->GetDeclaringClass()->IsInitialized());
2573 // We have code for a static method, but need to go through the resolution stub for class
2574 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002575 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2576 }
2577 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002578 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002579 }
2580 return quick_code;
2581}
2582
Jeff Haodcdc85b2015-12-04 14:06:18 -08002583void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2584 ArtMethod* copy,
2585 const ImageInfo& image_info) {
Mingyao Yange8fcd012017-01-20 10:43:30 -08002586 if (orig->IsAbstract()) {
2587 // Ignore the single-implementation info for abstract method.
2588 // Do this on orig instead of copy, otherwise there is a crash due to methods
2589 // are copied before classes.
2590 // TODO: handle fixup of single-implementation method for abstract method.
2591 orig->SetHasSingleImplementation(false);
2592 orig->SetSingleImplementation(
2593 nullptr, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
2594 }
2595
Vladimir Marko14632852015-08-17 12:07:23 +01002596 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002597
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002598 CopyReference(copy->GetDeclaringClassAddressWithoutBarrier(), orig->GetDeclaringClassUnchecked());
2599
Ian Rogers848871b2013-08-05 10:56:33 -07002600 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2601 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002602
Ian Rogers848871b2013-08-05 10:56:33 -07002603 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002604 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002605 if (orig->IsRuntimeMethod()) {
2606 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2607 if (orig_table != nullptr) {
2608 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2609 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2610 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2611 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2612 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2613 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2614 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2615 } else {
2616 bool found_one = false;
Andreas Gampe8228cdf2017-05-30 15:03:54 -07002617 for (size_t i = 0; i < static_cast<size_t>(CalleeSaveType::kLastCalleeSaveType); ++i) {
2618 auto idx = static_cast<CalleeSaveType>(i);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002619 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2620 found_one = true;
2621 break;
2622 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002623 }
David Sehr709b0702016-10-13 09:12:37 -07002624 CHECK(found_one) << "Expected to find callee save method but got " << orig->PrettyMethod();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002625 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002626 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002627 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002628 // We assume all methods have code. If they don't currently then we set them to the use the
2629 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2630 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002631 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002632 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002633 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002634 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002635 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002636 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002637 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002638
Sebastien Hertze1d07812014-05-21 15:44:09 +02002639 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002640 if (orig->IsNative()) {
2641 // The native method's pointer is set to a stub to lookup via dlsym.
2642 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002643 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002644 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002645 }
2646 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002647 }
2648}
2649
Jeff Haodcdc85b2015-12-04 14:06:18 -08002650size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002651 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002652 return std::accumulate(&image_info.bin_slot_sizes_[0],
2653 &image_info.bin_slot_sizes_[up_to],
2654 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002655}
2656
2657ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2658 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002659 static_assert(kBinBits == 3, "wrong number of bin bits");
2660 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002661 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2662
2663 DCHECK_LT(GetBin(), kBinSize);
2664 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2665}
2666
2667ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2668 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2669 DCHECK_EQ(index, GetIndex());
2670}
2671
2672ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2673 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2674}
2675
2676uint32_t ImageWriter::BinSlot::GetIndex() const {
2677 return lockword_ & ~kBinMask;
2678}
2679
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002680ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2681 switch (type) {
2682 case kNativeObjectRelocationTypeArtField:
2683 case kNativeObjectRelocationTypeArtFieldArray:
2684 return kBinArtField;
2685 case kNativeObjectRelocationTypeArtMethodClean:
2686 case kNativeObjectRelocationTypeArtMethodArrayClean:
2687 return kBinArtMethodClean;
2688 case kNativeObjectRelocationTypeArtMethodDirty:
2689 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2690 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002691 case kNativeObjectRelocationTypeDexCacheArray:
2692 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002693 case kNativeObjectRelocationTypeRuntimeMethod:
2694 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002695 case kNativeObjectRelocationTypeIMTable:
2696 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002697 case kNativeObjectRelocationTypeIMTConflictTable:
2698 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002699 }
2700 UNREACHABLE();
2701}
2702
Vladimir Marko944da602016-02-19 12:27:55 +00002703size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002704 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002705 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002706 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002707 auto it = oat_index_map_.find(obj);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002708 DCHECK(it != oat_index_map_.end()) << obj;
Mathieu Chartier496577f2016-09-20 15:33:31 -07002709 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002710}
2711
Vladimir Marko944da602016-02-19 12:27:55 +00002712size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002713 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002714 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002715 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002716 auto it = dex_file_oat_index_map_.find(dex_file);
2717 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2718 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002719}
2720
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002721size_t ImageWriter::GetOatIndexForDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
2722 return (dex_cache == nullptr)
2723 ? GetDefaultOatIndex()
2724 : GetOatIndexForDexFile(dex_cache->GetDexFile());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002725}
2726
Vladimir Marko944da602016-02-19 12:27:55 +00002727void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2728 size_t oat_loaded_size,
2729 size_t oat_data_offset,
2730 size_t oat_data_size) {
2731 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2732 for (const ImageInfo& info : image_infos_) {
2733 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2734 }
2735 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002736
Vladimir Marko944da602016-02-19 12:27:55 +00002737 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2738 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2739 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2740 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2741 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002742
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002743 if (compile_app_image_) {
2744 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2745 return;
2746 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002747
2748 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002749 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002750 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002751 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002752 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2753 }
2754}
2755
Vladimir Marko944da602016-02-19 12:27:55 +00002756void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2757 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2758 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2759
2760 if (oat_index == GetDefaultOatIndex()) {
2761 // Primary oat file, read the trampolines.
2762 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2763 oat_header.GetInterpreterToInterpreterBridgeOffset();
2764 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2765 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2766 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2767 oat_header.GetJniDlsymLookupOffset();
2768 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2769 oat_header.GetQuickGenericJniTrampolineOffset();
2770 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2771 oat_header.GetQuickImtConflictTrampolineOffset();
2772 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2773 oat_header.GetQuickResolutionTrampolineOffset();
2774 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2775 oat_header.GetQuickToInterpreterBridgeOffset();
2776 }
2777}
2778
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002779ImageWriter::ImageWriter(
2780 const CompilerDriver& compiler_driver,
2781 uintptr_t image_begin,
2782 bool compile_pic,
2783 bool compile_app_image,
2784 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002785 const std::vector<const char*>& oat_filenames,
Jeff Haoc23b0c02017-07-27 18:19:38 -07002786 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map,
2787 const std::unordered_set<std::string>* dirty_image_objects)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002788 : compiler_driver_(compiler_driver),
2789 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2790 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002791 compile_pic_(compile_pic),
2792 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002793 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002794 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002795 dirty_methods_(0u),
2796 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002797 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002798 oat_filenames_(oat_filenames),
Jeff Haoc23b0c02017-07-27 18:19:38 -07002799 dex_file_oat_index_map_(dex_file_oat_index_map),
2800 dirty_image_objects_(dirty_image_objects) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002801 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002802 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002803 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2804 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002805}
2806
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002807ImageWriter::ImageInfo::ImageInfo()
2808 : intern_table_(new InternTable),
2809 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002810
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002811void ImageWriter::CopyReference(mirror::HeapReference<mirror::Object>* dest,
2812 ObjPtr<mirror::Object> src) {
2813 dest->Assign(GetImageAddress(src.Ptr()));
2814}
2815
2816void ImageWriter::CopyReference(mirror::CompressedReference<mirror::Object>* dest,
2817 ObjPtr<mirror::Object> src) {
2818 dest->Assign(GetImageAddress(src.Ptr()));
2819}
2820
2821void ImageWriter::CopyAndFixupPointer(void** target, void* value) {
2822 void* new_value = value;
2823 if (value != nullptr && !IsInBootImage(value)) {
2824 auto it = native_object_relocations_.find(value);
2825 CHECK(it != native_object_relocations_.end()) << value;
2826 const NativeObjectRelocation& relocation = it->second;
2827 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2828 new_value = reinterpret_cast<void*>(image_info.image_begin_ + relocation.offset);
2829 }
2830 if (target_ptr_size_ == PointerSize::k32) {
2831 *reinterpret_cast<uint32_t*>(target) = PointerToLowMemUInt32(new_value);
2832 } else {
2833 *reinterpret_cast<uint64_t*>(target) = reinterpret_cast<uintptr_t>(new_value);
2834 }
2835}
2836
2837
Brian Carlstrom7940e442013-07-12 13:46:57 -07002838} // namespace art