blob: f92bf95065e9d2017f7a262151a5d3a08a84b312 [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
19#include <sys/stat.h>
Mathieu Chartierceb07b32015-12-10 09:33:21 -080020#include <lz4.h>
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -080021#include <lz4hc.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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "gc/heap.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070047#include "gc/heap-visit-objects-inl.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"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070062#include "mirror/dex_cache.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063#include "mirror/dex_cache-inl.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.
301 const ImageSection& bitmap_section = image_header->GetImageSection(
302 ImageHeader::kSectionImageBitmap);
303 // Align up since data size may be unaligned if the image is compressed.
304 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
305 if (!is_compressed) {
306 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
307 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800308 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
309 bitmap_section.Size(),
310 bitmap_position_in_file)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800311 PLOG(ERROR) << "Failed to write image file " << image_filename;
312 image_file->Erase();
313 return false;
314 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800315
316 int err = image_file->Flush();
317 if (err < 0) {
318 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
319 image_file->Erase();
320 return false;
321 }
322
323 // Write header last in case the compiler gets killed in the middle of image writing.
324 // We do not want to have a corrupted image with a valid header.
325 // The header is uncompressed since it contains whether the image is compressed or not.
326 image_header->data_size_ = data_size;
327 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
328 sizeof(ImageHeader),
329 0)) {
330 PLOG(ERROR) << "Failed to write image file header " << image_filename;
331 image_file->Erase();
332 return false;
333 }
334
Jeff Haodcdc85b2015-12-04 14:06:18 -0800335 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
336 static_cast<size_t>(image_file->GetLength()));
337 if (image_file->FlushCloseOrErase() != 0) {
338 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
339 return false;
340 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800341 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700342 return true;
343}
344
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700345void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700346 DCHECK(object != nullptr);
347 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800348
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800349 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700350 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700351 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700352 DCHECK(IsImageOffsetAssigned(object));
353}
354
Mathieu Chartiere401d142015-04-22 13:56:20 -0700355void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
356 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
357 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
358 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
359}
360
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800361void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700362 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800363 DCHECK_NE(image_objects_offset_begin_, 0u);
364
Vladimir Marko944da602016-02-19 12:27:55 +0000365 size_t oat_index = GetOatIndex(object);
366 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800367 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100368 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800369 DCHECK_ALIGNED(new_offset, kObjectAlignment);
370
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700371 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800372 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700373}
374
Ian Rogersef7d42f2014-01-06 12:55:46 -0800375bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800376 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700377 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700378 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700379}
380
Ian Rogersef7d42f2014-01-06 12:55:46 -0800381size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700382 DCHECK(object != nullptr);
383 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700384 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700385 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000386 size_t oat_index = GetOatIndex(object);
387 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800388 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700389 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700390}
391
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800392void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
393 DCHECK(object != nullptr);
394 DCHECK(!IsImageOffsetAssigned(object));
395 DCHECK(!IsImageBinSlotAssigned(object));
396
397 // Before we stomp over the lock word, save the hash code for later.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800398 LockWord lw(object->GetLockWord(false));
399 switch (lw.GetState()) {
Ian Rogers23e81a12017-07-05 09:36:27 -0700400 case LockWord::kFatLocked:
401 FALLTHROUGH_INTENDED;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800402 case LockWord::kThinLocked: {
Ian Rogers23e81a12017-07-05 09:36:27 -0700403 std::ostringstream oss;
404 bool thin = (lw.GetState() == LockWord::kThinLocked);
405 oss << (thin ? "Thin" : "Fat")
406 << " locked object " << object << "(" << object->PrettyTypeOf()
407 << ") found during object copy";
408 if (thin) {
409 oss << ". Lock owner:" << lw.ThinLockOwner();
410 }
411 LOG(FATAL) << oss.str();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800412 break;
413 }
414 case LockWord::kUnlocked:
415 // No hash, don't need to save it.
416 break;
417 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700418 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
419 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800420 break;
421 default:
422 LOG(FATAL) << "Unreachable.";
423 UNREACHABLE();
424 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700425 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700426 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800427 DCHECK(IsImageBinSlotAssigned(object));
428}
429
Vladimir Marko20f85592015-03-19 10:07:02 +0000430void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000431 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000432 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
433 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800434 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000435 auto it = dex_file_oat_index_map_.find(dex_file);
436 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800437 ImageInfo& image_info = GetImageInfo(it->second);
438 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
439 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
440 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
441 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000442
Vladimir Marko20f85592015-03-19 10:07:02 +0000443 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700444 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -0800445 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800446 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700447 ObjPtr<mirror::DexCache> dex_cache =
448 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
449 if (dex_cache == nullptr || IsInBootImage(dex_cache.Ptr())) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700450 continue;
451 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000452 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartier0b490842016-05-25 15:05:59 -0700453 CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
454 << "Dex cache should have been pruned " << dex_file->GetLocation()
455 << "; possibly in class path";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700456 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000457 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000458 size_t oat_index = GetOatIndexForDexCache(dex_cache);
459 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800460 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100461 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800462 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
463 start + layout.TypesOffset(),
464 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100465 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800466 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
467 start + layout.MethodsOffset(),
468 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100469 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800470 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
471 start + layout.FieldsOffset(),
472 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100473 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800474 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Narayan Kamath7fe56582016-10-14 18:49:12 +0100475
476 if (dex_cache->GetResolvedMethodTypes() != nullptr) {
477 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethodTypes(),
478 start + layout.MethodTypesOffset(),
479 dex_cache);
480 }
Orion Hodson631827d2017-04-10 14:53:47 +0100481 if (dex_cache->GetResolvedCallSites() != nullptr) {
482 AddDexCacheArrayRelocation(dex_cache->GetResolvedCallSites(),
483 start + layout.CallSitesOffset(),
484 dex_cache);
485 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000486 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000487}
488
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700489void ImageWriter::AddDexCacheArrayRelocation(void* array,
490 size_t offset,
491 ObjPtr<mirror::DexCache> dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100492 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800493 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000494 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800495 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000496 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100497 }
498}
499
Mathieu Chartiere401d142015-04-22 13:56:20 -0700500void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
501 DCHECK(arr != nullptr);
502 if (kIsDebugBuild) {
503 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800504 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700505 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800506 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800507 CHECK(klass == nullptr || KeepClass(klass))
David Sehr709b0702016-10-13 09:12:37 -0700508 << Class::PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700509 }
510 }
511 }
512 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
513 // ArtMethods.
514 pointer_arrays_.emplace(arr, kBinArtMethodClean);
515}
516
Mathieu Chartier496577f2016-09-20 15:33:31 -0700517void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800518 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800519 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800520
521 // The magic happens here. We segregate objects into different bins based
522 // on how likely they are to get dirty at runtime.
523 //
524 // Likely-to-dirty objects get packed together into the same bin so that
525 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
526 // maximized.
527 //
528 // This means more pages will stay either clean or shared dirty (with zygote) and
529 // the app will use less of its own (private) memory.
530 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000531 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800532
533 if (kBinObjects) {
534 //
535 // Changing the bin of an object is purely a memory-use tuning.
536 // It has no change on runtime correctness.
537 //
538 // Memory analysis has determined that the following types of objects get dirtied
539 // the most:
540 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000541 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
542 // a fixed layout which helps improve generated code (using PC-relative addressing),
543 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
544 // Since these arrays are huge, most pages do not overlap other objects and it's not
545 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100546 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800547 // * Class'es which are verified [their clinit runs only at runtime]
548 // - classes in general [because their static fields get overwritten]
549 // - initialized classes with all-final statics are unlikely to be ever dirty,
550 // so bin them separately
551 // * Art Methods that are:
552 // - native [their native entry point is not looked up until runtime]
553 // - have declaring classes that aren't initialized
554 // [their interpreter/quick entry points are trampolines until the class
555 // becomes initialized]
556 //
557 // We also assume the following objects get dirtied either never or extremely rarely:
558 // * Strings (they are immutable)
559 // * Art methods that aren't native and have initialized declared classes
560 //
561 // We assume that "regular" bin objects are highly unlikely to become dirtied,
562 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
563 //
564 if (object->IsClass()) {
565 bin = kBinClassVerified;
566 mirror::Class* klass = object->AsClass();
567
Mathieu Chartiere401d142015-04-22 13:56:20 -0700568 // Add non-embedded vtable to the pointer array table if there is one.
569 auto* vtable = klass->GetVTable();
570 if (vtable != nullptr) {
571 AddMethodPointerArray(vtable);
572 }
573 auto* iftable = klass->GetIfTable();
574 if (iftable != nullptr) {
575 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
576 if (iftable->GetMethodArrayCount(i) > 0) {
577 AddMethodPointerArray(iftable->GetMethodArray(i));
578 }
579 }
580 }
581
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800582 if (klass->GetStatus() == Class::kStatusInitialized) {
583 bin = kBinClassInitialized;
584
585 // If the class's static fields are all final, put it into a separate bin
586 // since it's very likely it will stay clean.
587 uint32_t num_static_fields = klass->NumStaticFields();
588 if (num_static_fields == 0) {
589 bin = kBinClassInitializedFinalStatics;
590 } else {
591 // Maybe all the statics are final?
592 bool all_final = true;
593 for (uint32_t i = 0; i < num_static_fields; ++i) {
594 ArtField* field = klass->GetStaticField(i);
595 if (!field->IsFinal()) {
596 all_final = false;
597 break;
598 }
599 }
600
601 if (all_final) {
602 bin = kBinClassInitializedFinalStatics;
603 }
604 }
605 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800606 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
607 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700608 } else if (object->GetClass<kVerifyNone>() ==
609 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
610 // Instance of java lang object, probably a lock object. This means it will be dirty when we
611 // synchronize on it.
612 bin = kBinMiscDirty;
613 } else if (object->IsDexCache()) {
614 // Dex file field becomes dirty when the image is loaded.
615 bin = kBinMiscDirty;
616 }
617 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800618 }
619
Mathieu Chartier496577f2016-09-20 15:33:31 -0700620 // Assign the oat index too.
621 DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
622 oat_index_map_.emplace(object, oat_index);
623
Vladimir Marko944da602016-02-19 12:27:55 +0000624 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800625
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800626 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800627 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
628 // Move the current bin size up to accommodate the object we just assigned a bin slot.
629 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800630
631 BinSlot new_bin_slot(bin, current_offset);
632 SetImageBinSlot(object, new_bin_slot);
633
Jeff Haodcdc85b2015-12-04 14:06:18 -0800634 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800635
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800636 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800637 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800638}
639
Mathieu Chartiere401d142015-04-22 13:56:20 -0700640bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
641 if (m->IsNative()) {
642 return true;
643 }
644 mirror::Class* declaring_class = m->GetDeclaringClass();
645 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
646 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
647}
648
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800649bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
650 DCHECK(object != nullptr);
651
652 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
653 // If it's in some other state, then we haven't yet assigned an image bin slot.
654 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
655 return false;
656 } else if (kIsDebugBuild) {
657 LockWord lock_word = object->GetLockWord(false);
658 size_t offset = lock_word.ForwardingAddress();
659 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000660 size_t oat_index = GetOatIndex(object);
661 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800662 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800663 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800664 }
665 return true;
666}
667
668ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
669 DCHECK(object != nullptr);
670 DCHECK(IsImageBinSlotAssigned(object));
671
672 LockWord lock_word = object->GetLockWord(false);
673 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
674 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
675
676 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000677 size_t oat_index = GetOatIndex(object);
678 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800679 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800680
681 return bin_slot;
682}
683
Brian Carlstrom7940e442013-07-12 13:46:57 -0700684bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000685 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800686 ImageSection unused_sections[ImageHeader::kSectionCount];
687 const size_t length = RoundUp(
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700688 image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800689
Jeff Haodcdc85b2015-12-04 14:06:18 -0800690 std::string error_msg;
691 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
692 nullptr,
693 length,
694 PROT_READ | PROT_WRITE,
695 false,
696 false,
697 &error_msg));
698 if (UNLIKELY(image_info.image_.get() == nullptr)) {
699 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
700 return false;
701 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700702
Jeff Haodcdc85b2015-12-04 14:06:18 -0800703 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
704 CHECK_LE(image_info.image_end_, length);
705 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
706 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
707 if (image_info.image_bitmap_.get() == nullptr) {
708 LOG(ERROR) << "Failed to allocate memory for image bitmap";
709 return false;
710 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700711 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700712 return true;
713}
714
Vladimir Markoad06b982016-11-17 16:38:59 +0000715class ImageWriter::ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700716 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700717 bool operator()(ObjPtr<Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700718 StackHandleScope<1> hs(Thread::Current());
719 mirror::Class::ComputeName(hs.NewHandle(c));
720 return true;
721 }
722};
723
Brian Carlstrom7940e442013-07-12 13:46:57 -0700724void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700725 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700726 ComputeLazyFieldsForClassesVisitor visitor;
727 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700728}
729
Vladimir Markof25cc732017-03-16 16:18:15 +0000730static bool IsBootClassLoaderClass(ObjPtr<mirror::Class> klass)
731 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800732 return klass->GetClassLoader() == nullptr;
733}
734
735bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
736 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
737}
738
Chang Xingb2e8adc2017-07-07 17:35:37 -0700739// This visitor follows the references of an instance, recursively then prune this class
740// if a type of any field is pruned.
741class ImageWriter::PruneObjectReferenceVisitor {
742 public:
743 PruneObjectReferenceVisitor(ImageWriter* image_writer,
744 bool* early_exit,
745 std::unordered_set<mirror::Object*>* visited,
746 bool* result)
747 : image_writer_(image_writer), early_exit_(early_exit), visited_(visited), result_(result) {}
748
749 ALWAYS_INLINE void VisitRootIfNonNull(
750 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const
751 REQUIRES_SHARED(Locks::mutator_lock_) { }
752
753 ALWAYS_INLINE void VisitRoot(
754 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const
755 REQUIRES_SHARED(Locks::mutator_lock_) { }
756
757 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
758 MemberOffset offset,
759 bool is_static ATTRIBUTE_UNUSED) const
760 REQUIRES_SHARED(Locks::mutator_lock_) {
761 mirror::Object* ref =
762 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
763 if (ref == nullptr || visited_->find(ref) != visited_->end()) {
764 return;
765 }
766
767 ObjPtr<mirror::Class> klass = ref->IsClass() ? ref->AsClass() : ref->GetClass();
768 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
769 // Prune all classes using reflection because the content they held will not be fixup.
770 *result_ = true;
771 }
772
773 // Record the object visited in case of circular reference.
774 visited_->emplace(ref);
775 if (ref->IsClass()) {
776 *result_ = *result_ ||
777 image_writer_->PruneAppImageClassInternal(ref->AsClass(), early_exit_, visited_);
778 } else {
779 *result_ = *result_ ||
780 image_writer_->PruneAppImageClassInternal(klass, early_exit_, visited_);
781 ref->VisitReferences(*this, *this);
782 }
783 // Clean up before exit for next call of this function.
784 visited_->erase(ref);
785 }
786
787 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
788 ObjPtr<mirror::Reference> ref) const
789 REQUIRES_SHARED(Locks::mutator_lock_) {
790 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
791 }
792
793 ALWAYS_INLINE bool GetResult() const {
794 return result_;
795 }
796
797 private:
798 ImageWriter* image_writer_;
799 bool* early_exit_;
800 std::unordered_set<mirror::Object*>* visited_;
801 bool* const result_;
802};
803
804
Vladimir Markof25cc732017-03-16 16:18:15 +0000805bool ImageWriter::PruneAppImageClass(ObjPtr<mirror::Class> klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800806 bool early_exit = false;
Chang Xingb2e8adc2017-07-07 17:35:37 -0700807 std::unordered_set<mirror::Object*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800808 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800809}
810
Mathieu Chartier901e0702016-02-19 13:42:48 -0800811bool ImageWriter::PruneAppImageClassInternal(
Vladimir Markof25cc732017-03-16 16:18:15 +0000812 ObjPtr<mirror::Class> klass,
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800813 bool* early_exit,
Chang Xingb2e8adc2017-07-07 17:35:37 -0700814 std::unordered_set<mirror::Object*>* visited) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800815 DCHECK(early_exit != nullptr);
816 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800817 DCHECK(compile_app_image_);
Vladimir Markof25cc732017-03-16 16:18:15 +0000818 if (klass == nullptr || IsInBootImage(klass.Ptr())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700819 return false;
820 }
Vladimir Markof25cc732017-03-16 16:18:15 +0000821 auto found = prune_class_memo_.find(klass.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800822 if (found != prune_class_memo_.end()) {
823 // Already computed, return the found value.
824 return found->second;
825 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800826 // Circular dependencies, return false but do not store the result in the memoization table.
Vladimir Markof25cc732017-03-16 16:18:15 +0000827 if (visited->find(klass.Ptr()) != visited->end()) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800828 *early_exit = true;
829 return false;
830 }
Vladimir Markof25cc732017-03-16 16:18:15 +0000831 visited->emplace(klass.Ptr());
Mathieu Chartier901e0702016-02-19 13:42:48 -0800832 bool result = IsBootClassLoaderClass(klass);
833 std::string temp;
834 // Prune if not an image class, this handles any broken sets of image classes such as having a
835 // class in the set but not it's superclass.
836 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800837 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800838 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
839 // app image.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000840 if (klass->IsErroneous()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800841 result = true;
842 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700843 ObjPtr<mirror::ClassExt> ext(klass->GetExtData());
844 CHECK(ext.IsNull() || ext->GetVerifyError() == nullptr) << klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800845 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800846 if (!result) {
847 // Check interfaces since these wont be visited through VisitReferences.)
848 mirror::IfTable* if_table = klass->GetIfTable();
849 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800850 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
851 &my_early_exit,
852 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800853 }
854 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800855 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800856 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
857 &my_early_exit,
858 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800859 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800860 // Check static fields and their classes.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000861 if (klass->IsResolved() && klass->NumReferenceStaticFields() != 0) {
862 size_t num_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800863 // Presumably GC can happen when we are cross compiling, it should not cause performance
864 // problems to do pointer size logic.
865 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
866 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
867 for (size_t i = 0u; i < num_static_fields; ++i) {
868 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
869 if (ref != nullptr) {
870 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800871 result = result || PruneAppImageClassInternal(ref->AsClass(),
872 &my_early_exit,
873 visited);
874 } else {
Chang Xingb2e8adc2017-07-07 17:35:37 -0700875 mirror::Class* type = ref->GetClass();
876 result = result || PruneAppImageClassInternal(type,
Mathieu Chartier901e0702016-02-19 13:42:48 -0800877 &my_early_exit,
878 visited);
Chang Xingb2e8adc2017-07-07 17:35:37 -0700879 if (!result) {
880 // For non-class case, also go through all the types mentioned by it's fields'
881 // references recursively to decide whether to keep this class.
882 bool tmp = false;
883 PruneObjectReferenceVisitor visitor(this, &my_early_exit, visited, &tmp);
884 ref->VisitReferences(visitor, visitor);
885 result = result || tmp;
886 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800887 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800888 }
889 field_offset = MemberOffset(field_offset.Uint32Value() +
890 sizeof(mirror::HeapReference<mirror::Object>));
891 }
892 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800893 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
894 &my_early_exit,
895 visited);
Mathieu Chartierc27bc402016-08-05 16:09:09 -0700896 // Remove the class if the dex file is not in the set of dex files. This happens for classes that
897 // are from uses library if there is no profile. b/30688277
898 mirror::DexCache* dex_cache = klass->GetDexCache();
899 if (dex_cache != nullptr) {
900 result = result ||
901 dex_file_oat_index_map_.find(dex_cache->GetDexFile()) == dex_file_oat_index_map_.end();
902 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800903 // Erase the element we stored earlier since we are exiting the function.
Vladimir Markof25cc732017-03-16 16:18:15 +0000904 auto it = visited->find(klass.Ptr());
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800905 DCHECK(it != visited->end());
906 visited->erase(it);
907 // Only store result if it is true or none of the calls early exited due to circular
908 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
909 // a child call and we can remember the result.
910 if (result == true || !my_early_exit || visited->empty()) {
Vladimir Markof25cc732017-03-16 16:18:15 +0000911 prune_class_memo_[klass.Ptr()] = result;
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800912 }
913 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800914 return result;
915}
916
Vladimir Markof25cc732017-03-16 16:18:15 +0000917bool ImageWriter::KeepClass(ObjPtr<mirror::Class> klass) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800918 if (klass == nullptr) {
919 return false;
920 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800921 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
922 // Already in boot image, return true.
923 return true;
924 }
925 std::string temp;
926 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
927 return false;
928 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800929 if (compile_app_image_) {
930 // For app images, we need to prune boot loader classes that are not in the boot image since
931 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800932 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800933 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800934 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800935 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700936}
937
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000938class ImageWriter::PruneClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700939 public:
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000940 PruneClassesVisitor(ImageWriter* image_writer, ObjPtr<mirror::ClassLoader> class_loader)
941 : image_writer_(image_writer),
942 class_loader_(class_loader),
943 classes_to_prune_(),
944 defined_class_count_(0u) { }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700945
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000946 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700947 if (!image_writer_->KeepClass(klass.Ptr())) {
948 classes_to_prune_.insert(klass.Ptr());
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000949 if (klass->GetClassLoader() == class_loader_) {
950 ++defined_class_count_;
951 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700952 }
953 return true;
954 }
955
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000956 size_t Prune() REQUIRES_SHARED(Locks::mutator_lock_) {
957 ClassTable* class_table =
958 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader_);
959 for (mirror::Class* klass : classes_to_prune_) {
960 std::string storage;
961 const char* descriptor = klass->GetDescriptor(&storage);
962 bool result = class_table->Remove(descriptor);
963 DCHECK(result);
964 DCHECK(!class_table->Remove(descriptor)) << descriptor;
965 }
966 return defined_class_count_;
967 }
968
969 private:
Vladimir Markocb5ab352016-11-30 15:31:13 +0000970 ImageWriter* const image_writer_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000971 const ObjPtr<mirror::ClassLoader> class_loader_;
972 std::unordered_set<mirror::Class*> classes_to_prune_;
973 size_t defined_class_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700974};
975
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000976class ImageWriter::PruneClassLoaderClassesVisitor : public ClassLoaderVisitor {
977 public:
978 explicit PruneClassLoaderClassesVisitor(ImageWriter* image_writer)
979 : image_writer_(image_writer), removed_class_count_(0) {}
980
981 virtual void Visit(ObjPtr<mirror::ClassLoader> class_loader) OVERRIDE
982 REQUIRES_SHARED(Locks::mutator_lock_) {
983 PruneClassesVisitor classes_visitor(image_writer_, class_loader);
984 ClassTable* class_table =
985 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader);
986 class_table->Visit(classes_visitor);
987 removed_class_count_ += classes_visitor.Prune();
Vladimir Markof25cc732017-03-16 16:18:15 +0000988
989 // Record app image class loader. The fake boot class loader should not get registered
990 // and we should end up with only one class loader for an app and none for boot image.
991 if (class_loader != nullptr && class_table != nullptr) {
992 DCHECK(class_loader_ == nullptr);
993 class_loader_ = class_loader;
994 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000995 }
996
997 size_t GetRemovedClassCount() const {
998 return removed_class_count_;
999 }
1000
Vladimir Markof25cc732017-03-16 16:18:15 +00001001 ObjPtr<mirror::ClassLoader> GetClassLoader() const REQUIRES_SHARED(Locks::mutator_lock_) {
1002 return class_loader_;
1003 }
1004
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001005 private:
1006 ImageWriter* const image_writer_;
1007 size_t removed_class_count_;
Vladimir Markof25cc732017-03-16 16:18:15 +00001008 ObjPtr<mirror::ClassLoader> class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001009};
1010
1011void ImageWriter::VisitClassLoaders(ClassLoaderVisitor* visitor) {
1012 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1013 visitor->Visit(nullptr); // Visit boot class loader.
1014 Runtime::Current()->GetClassLinker()->VisitClassLoaders(visitor);
1015}
1016
Vladimir Markof25cc732017-03-16 16:18:15 +00001017void ImageWriter::PruneAndPreloadDexCache(ObjPtr<mirror::DexCache> dex_cache,
1018 ObjPtr<mirror::ClassLoader> class_loader) {
1019 // To ensure deterministic contents of the hash-based arrays, each slot shall contain
1020 // the candidate with the lowest index. As we're processing entries in increasing index
1021 // order, this means trying to look up the entry for the current index if the slot is
1022 // empty or if it contains a higher index.
1023
1024 Runtime* runtime = Runtime::Current();
1025 ClassLinker* class_linker = runtime->GetClassLinker();
1026 ArtMethod* resolution_method = runtime->GetResolutionMethod();
1027 const DexFile& dex_file = *dex_cache->GetDexFile();
1028 // Prune methods.
1029 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
1030 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
1031 ArtMethod* method =
1032 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
1033 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
Vladimir Marko3b155452017-07-05 11:41:33 +01001034 // Check if the referenced class is in the image. Note that we want to check the referenced
1035 // class rather than the declaring class to preserve the semantics, i.e. using a MethodId
1036 // results in resolving the referenced class and that can for example throw OOME.
1037 ObjPtr<mirror::Class> referencing_class = class_linker->LookupResolvedType(
1038 dex_file,
1039 dex_file.GetMethodId(i).class_idx_,
1040 dex_cache,
1041 class_loader);
Vladimir Markof25cc732017-03-16 16:18:15 +00001042 // Copied methods may be held live by a class which was not an image class but have a
1043 // declaring class which is an image class. Set it to the resolution method to be safe and
1044 // prevent dangling pointers.
Vladimir Marko3b155452017-07-05 11:41:33 +01001045 if (method->IsCopied() || !KeepClass(referencing_class)) {
Vladimir Markof25cc732017-03-16 16:18:15 +00001046 mirror::DexCache::SetElementPtrSize(resolved_methods,
1047 i,
1048 resolution_method,
1049 target_ptr_size_);
1050 } else if (kIsDebugBuild) {
1051 // Check that the class is still in the classes table.
1052 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Vladimir Marko3b155452017-07-05 11:41:33 +01001053 CHECK(class_linker->ClassInClassTable(referencing_class)) << "Class "
1054 << Class::PrettyClass(referencing_class) << " not in class linker table";
Vladimir Markof25cc732017-03-16 16:18:15 +00001055 }
1056 }
1057 // Prune fields and make the contents of the field array deterministic.
1058 mirror::FieldDexCacheType* resolved_fields = dex_cache->GetResolvedFields();
1059 dex::TypeIndex last_class_idx; // Initialized to invalid index.
1060 ObjPtr<mirror::Class> last_class = nullptr;
1061 for (size_t i = 0, end = dex_file.NumFieldIds(); i < end; ++i) {
1062 uint32_t slot_idx = dex_cache->FieldSlotIndex(i);
1063 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_fields, slot_idx, target_ptr_size_);
1064 uint32_t stored_index = pair.index;
1065 ArtField* field = pair.object;
1066 if (field != nullptr && i > stored_index) {
1067 continue; // Already checked.
1068 }
1069 // Check if the referenced class is in the image. Note that we want to check the referenced
1070 // class rather than the declaring class to preserve the semantics, i.e. using a FieldId
1071 // results in resolving the referenced class and that can for example throw OOME.
1072 const DexFile::FieldId& field_id = dex_file.GetFieldId(i);
1073 if (field_id.class_idx_ != last_class_idx) {
1074 last_class_idx = field_id.class_idx_;
1075 last_class = class_linker->LookupResolvedType(
1076 dex_file, last_class_idx, dex_cache, class_loader);
1077 if (last_class != nullptr && !KeepClass(last_class)) {
1078 last_class = nullptr;
1079 }
1080 }
1081 if (field == nullptr || i < stored_index) {
1082 if (last_class != nullptr) {
1083 const char* name = dex_file.StringDataByIdx(field_id.name_idx_);
1084 const char* type = dex_file.StringByTypeIdx(field_id.type_idx_);
1085 field = mirror::Class::FindField(Thread::Current(), last_class, name, type);
1086 if (field != nullptr) {
1087 // If the referenced class is in the image, the defining class must also be there.
1088 DCHECK(KeepClass(field->GetDeclaringClass()));
1089 dex_cache->SetResolvedField(i, field, target_ptr_size_);
1090 }
1091 }
1092 } else {
1093 DCHECK_EQ(i, stored_index);
1094 if (last_class == nullptr) {
1095 dex_cache->ClearResolvedField(stored_index, target_ptr_size_);
1096 }
1097 }
1098 }
1099 // Prune types and make the contents of the type array deterministic.
1100 // This is done after fields and methods as their lookup can touch the types array.
1101 for (size_t i = 0, end = dex_cache->GetDexFile()->NumTypeIds(); i < end; ++i) {
1102 dex::TypeIndex type_idx(i);
1103 uint32_t slot_idx = dex_cache->TypeSlotIndex(type_idx);
1104 mirror::TypeDexCachePair pair =
1105 dex_cache->GetResolvedTypes()[slot_idx].load(std::memory_order_relaxed);
1106 uint32_t stored_index = pair.index;
1107 ObjPtr<mirror::Class> klass = pair.object.Read();
1108 if (klass == nullptr || i < stored_index) {
1109 klass = class_linker->LookupResolvedType(dex_file, type_idx, dex_cache, class_loader);
1110 if (klass != nullptr) {
1111 DCHECK_EQ(dex_cache->GetResolvedType(type_idx), klass);
1112 stored_index = i; // For correct clearing below if not keeping the `klass`.
1113 }
1114 } else if (i == stored_index && !KeepClass(klass)) {
1115 dex_cache->ClearResolvedType(dex::TypeIndex(stored_index));
1116 }
1117 }
1118 // Strings do not need pruning, but the contents of the string array must be deterministic.
1119 for (size_t i = 0, end = dex_cache->GetDexFile()->NumStringIds(); i < end; ++i) {
1120 dex::StringIndex string_idx(i);
1121 uint32_t slot_idx = dex_cache->StringSlotIndex(string_idx);
1122 mirror::StringDexCachePair pair =
1123 dex_cache->GetStrings()[slot_idx].load(std::memory_order_relaxed);
1124 uint32_t stored_index = pair.index;
1125 ObjPtr<mirror::String> string = pair.object.Read();
1126 if (string == nullptr || i < stored_index) {
1127 string = class_linker->LookupString(dex_file, string_idx, dex_cache);
1128 DCHECK(string == nullptr || dex_cache->GetResolvedString(string_idx) == string);
1129 }
1130 }
1131}
1132
Brian Carlstrom7940e442013-07-12 13:46:57 -07001133void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001134 Runtime* runtime = Runtime::Current();
1135 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001136 Thread* self = Thread::Current();
Vladimir Markof25cc732017-03-16 16:18:15 +00001137 ScopedAssertNoThreadSuspension sa(__FUNCTION__);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001138
Mathieu Chartier696632e2016-06-03 17:47:32 -07001139 // Clear class table strong roots so that dex caches can get pruned. We require pruning the class
1140 // path dex caches.
1141 class_linker->ClearClassTableStrongRoots();
1142
Brian Carlstrom7940e442013-07-12 13:46:57 -07001143 // Remove the undesired classes from the class roots.
Vladimir Markof25cc732017-03-16 16:18:15 +00001144 ObjPtr<mirror::ClassLoader> class_loader;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001145 {
1146 PruneClassLoaderClassesVisitor class_loader_visitor(this);
1147 VisitClassLoaders(&class_loader_visitor);
1148 VLOG(compiler) << "Pruned " << class_loader_visitor.GetRemovedClassCount() << " classes";
Vladimir Markof25cc732017-03-16 16:18:15 +00001149 class_loader = class_loader_visitor.GetClassLoader();
1150 DCHECK_EQ(class_loader != nullptr, compile_app_image_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001151 }
1152
1153 // Clear references to removed classes from the DexCaches.
Vladimir Markof25cc732017-03-16 16:18:15 +00001154 std::vector<ObjPtr<mirror::DexCache>> dex_caches;
1155 {
1156 ReaderMutexLock mu2(self, *Locks::dex_lock_);
1157 dex_caches.reserve(class_linker->GetDexCachesData().size());
1158 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1159 if (self->IsJWeakCleared(data.weak_root)) {
1160 continue;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001161 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001162 dex_caches.push_back(self->DecodeJObject(data.weak_root)->AsDexCache());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001163 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001164 }
1165 for (ObjPtr<mirror::DexCache> dex_cache : dex_caches) {
1166 PruneAndPreloadDexCache(dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001167 }
Andreas Gampe8ac75952015-06-02 21:01:45 -07001168
1169 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
1170 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001171
1172 // Clear to save RAM.
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00001173 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001174}
1175
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001176void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001177 if (compiler_driver_.GetImageClasses() != nullptr) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001178 auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1179 if (obj->IsClass() && !IsInBootImage(obj)) {
1180 Class* klass = obj->AsClass();
1181 if (!KeepClass(klass)) {
1182 DumpImageClasses();
1183 std::string temp;
1184 CHECK(KeepClass(klass))
1185 << Runtime::Current()->GetHeap()->GetVerification()->FirstPathFromRootSet(klass);
1186 }
1187 }
1188 };
Mathieu Chartier590fee92013-09-13 13:46:47 -07001189 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001190 heap->VisitObjects(visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001191 }
1192}
1193
1194void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001195 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001196 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001197 for (const std::string& image_class : *image_classes) {
1198 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001199 }
1200}
1201
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001202mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
1203 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +00001204 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001205 ObjPtr<mirror::String> const found = image_info.intern_table_->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001206 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
1207 << string->ToModifiedUtf8();
1208 if (found != nullptr) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001209 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001210 }
1211 }
1212 if (compile_app_image_) {
1213 Runtime* const runtime = Runtime::Current();
Mathieu Chartier9e868092016-10-31 14:58:04 -07001214 ObjPtr<mirror::String> found = runtime->GetInternTable()->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001215 // If we found it in the runtime intern table it could either be in the boot image or interned
1216 // during app image compilation. If it was in the boot image return that, otherwise return null
1217 // since it belongs to another image space.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001218 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found.Ptr())) {
1219 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001220 }
1221 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
1222 << string->ToModifiedUtf8();
1223 }
1224 return nullptr;
1225}
1226
Brian Carlstrom7940e442013-07-12 13:46:57 -07001227
Vladimir Marko944da602016-02-19 12:27:55 +00001228ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001229 Runtime* runtime = Runtime::Current();
1230 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001231 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001232 StackHandleScope<3> hs(self);
1233 Handle<Class> object_array_class(hs.NewHandle(
1234 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001235
Jeff Haodcdc85b2015-12-04 14:06:18 -08001236 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +00001237 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001238 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +00001239 size_t image_oat_index = pair.second;
1240 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001241 image_dex_files.insert(image_dex_file);
1242 }
1243 }
1244
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001245 // build an Object[] of all the DexCaches used in the source_space_.
1246 // Since we can't hold the dex lock when allocating the dex_caches
1247 // ObjectArray, we lock the dex lock twice, first to get the number
1248 // of dex caches first and then lock it again to copy the dex
1249 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001250 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001251 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001252 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001253 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001254 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001255 ObjPtr<mirror::DexCache> dex_cache =
1256 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001257 if (dex_cache == nullptr) {
1258 continue;
1259 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001260 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001261 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001262 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1263 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001264 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001265 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001266 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001267 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001268 CHECK(dex_caches != nullptr) << "Failed to allocate a dex cache array.";
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001269 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001270 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001271 size_t non_image_dex_caches = 0;
1272 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001273 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001274 ObjPtr<mirror::DexCache> dex_cache =
1275 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001276 if (dex_cache == nullptr) {
1277 continue;
1278 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001279 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001280 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001281 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1282 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001283 }
1284 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1285 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001286 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001287 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001288 ObjPtr<mirror::DexCache> dex_cache =
1289 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001290 if (dex_cache == nullptr) {
1291 continue;
1292 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001293 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001294 if (!IsInBootImage(dex_cache.Ptr()) &&
1295 image_dex_files.find(dex_file) != image_dex_files.end()) {
1296 dex_caches->Set<false>(i, dex_cache.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001297 ++i;
1298 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001299 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001300 }
1301
1302 // build an Object[] of the roots needed to restore the runtime
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001303 int32_t image_roots_size = ImageHeader::NumberOfImageRoots(compile_app_image_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001304 auto image_roots(hs.NewHandle(
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001305 ObjectArray<Object>::Alloc(self, object_array_class.Get(), image_roots_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001306 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001307 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001308 // image_roots[ImageHeader::kClassLoader] will be set later for app image.
1309 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1310 "Class loader should be the last image root.");
1311 for (int32_t i = 0; i < ImageHeader::kImageRootsMax - 1; ++i) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001312 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001313 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001314 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001315}
1316
Mathieu Chartier496577f2016-09-20 15:33:31 -07001317mirror::Object* ImageWriter::TryAssignBinSlot(WorkStack& work_stack,
1318 mirror::Object* obj,
1319 size_t oat_index) {
1320 if (obj == nullptr || IsInBootImage(obj)) {
1321 // Object is null or already in the image, there is no work to do.
1322 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001323 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001324 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001325 // We want to intern all strings but also assign offsets for the source string. Since the
1326 // pruning phase has already happened, if we intern a string to one in the image we still
1327 // end up copying an unreachable string.
1328 if (obj->IsString()) {
1329 // Need to check if the string is already interned in another image info so that we don't have
1330 // the intern tables of two different images contain the same string.
1331 mirror::String* interned = FindInternedString(obj->AsString());
1332 if (interned == nullptr) {
1333 // Not in another image space, insert to our table.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001334 interned =
1335 GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString()).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001336 DCHECK_EQ(interned, obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001337 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001338 } else if (obj->IsDexCache()) {
1339 oat_index = GetOatIndexForDexCache(obj->AsDexCache());
1340 } else if (obj->IsClass()) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001341 // Visit and assign offsets for fields and field arrays.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001342 mirror::Class* as_klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001343 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Vladimir Marko72ab6842017-01-20 19:32:50 +00001344 DCHECK(!as_klass->IsErroneous()) << as_klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001345 if (compile_app_image_) {
1346 // Extra sanity, no boot loader classes should be left!
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00001347 CHECK(!IsBootClassLoaderClass(as_klass)) << as_klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001348 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001349 LengthPrefixedArray<ArtField>* fields[] = {
1350 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1351 };
Mathieu Chartier496577f2016-09-20 15:33:31 -07001352 // Overwrite the oat index value since the class' dex cache is more accurate of where it
1353 // belongs.
1354 oat_index = GetOatIndexForDexCache(dex_cache);
Vladimir Marko944da602016-02-19 12:27:55 +00001355 ImageInfo& image_info = GetImageInfo(oat_index);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001356 if (!compile_app_image_) {
1357 // Note: Avoid locking to prevent lock order violations from root visiting;
1358 // image_info.class_table_ is only accessed from the image writer.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001359 image_info.class_table_->InsertWithoutLocks(as_klass);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001360 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001361 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1362 // Total array length including header.
1363 if (cur_fields != nullptr) {
1364 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1365 // Forward the entire array at once.
1366 auto it = native_object_relocations_.find(cur_fields);
1367 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1368 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001369 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001370 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001371 native_object_relocations_.emplace(
1372 cur_fields,
1373 NativeObjectRelocation {
1374 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1375 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001376 offset += header_size;
1377 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001378 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001379 // Need to forward arrays separate of fields.
1380 ArtField* field = &cur_fields->At(i);
1381 auto it2 = native_object_relocations_.find(field);
1382 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
David Sehr709b0702016-10-13 09:12:37 -07001383 << " already assigned " << field->PrettyField() << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001384 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001385 native_object_relocations_.emplace(
1386 field,
1387 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001388 offset += sizeof(ArtField);
1389 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001390 }
1391 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001392 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001393 size_t num_methods = as_klass->NumMethods();
1394 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001395 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001396 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1397 if (WillMethodBeDirty(&m)) {
1398 any_dirty = true;
1399 break;
1400 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001401 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001402 NativeObjectRelocationType type = any_dirty
1403 ? kNativeObjectRelocationTypeArtMethodDirty
1404 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001405 Bin bin_type = BinTypeForNativeRelocationType(type);
1406 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001407 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1408 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001409 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1410 method_size,
1411 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001412 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001413 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001414 CHECK(it == native_object_relocations_.end())
1415 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001416 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001417 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001418 native_object_relocations_.emplace(array,
1419 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001420 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001421 offset,
1422 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1423 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001424 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001425 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001426 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001427 }
Alex Lighte64300b2015-12-15 15:02:47 -08001428 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001429 }
1430 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1431 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001432 if (as_klass->ShouldHaveImt()) {
1433 ImTable* imt = as_klass->GetImt(target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001434 if (TryAssignImTableOffset(imt, oat_index)) {
1435 // Since imt's can be shared only do this the first time to not double count imt method
1436 // fixups.
1437 for (size_t i = 0; i < ImTable::kSize; ++i) {
1438 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
1439 DCHECK(imt_method != nullptr);
1440 if (imt_method->IsRuntimeMethod() &&
1441 !IsInBootImage(imt_method) &&
1442 !NativeRelocationAssigned(imt_method)) {
1443 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
1444 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001445 }
1446 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001447 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001448 } else if (obj->IsClassLoader()) {
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001449 // Register the class loader if it has a class table.
1450 // The fake boot class loader should not get registered and we should end up with only one
1451 // class loader.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001452 mirror::ClassLoader* class_loader = obj->AsClassLoader();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001453 if (class_loader->GetClassTable() != nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001454 DCHECK(compile_app_image_);
1455 DCHECK(class_loaders_.empty());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001456 class_loaders_.insert(class_loader);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001457 ImageInfo& image_info = GetImageInfo(oat_index);
1458 // Note: Avoid locking to prevent lock order violations from root visiting;
1459 // image_info.class_table_ table is only accessed from the image writer
1460 // and class_loader->GetClassTable() is iterated but not modified.
1461 image_info.class_table_->CopyWithoutLocks(*class_loader->GetClassTable());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001462 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001463 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001464 AssignImageBinSlot(obj, oat_index);
1465 work_stack.emplace(obj, oat_index);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001466 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001467 if (obj->IsString()) {
1468 // Always return the interned string if there exists one.
1469 mirror::String* interned = FindInternedString(obj->AsString());
1470 if (interned != nullptr) {
1471 return interned;
1472 }
1473 }
1474 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001475}
1476
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001477bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1478 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1479}
1480
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001481bool ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001482 // No offset, or already assigned.
1483 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001484 return false;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001485 }
1486 // If the method is a conflict method we also want to assign the conflict table offset.
1487 ImageInfo& image_info = GetImageInfo(oat_index);
1488 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1489 native_object_relocations_.emplace(
1490 imt,
1491 NativeObjectRelocation {
1492 oat_index,
1493 image_info.bin_slot_sizes_[kBinImTable],
1494 kNativeObjectRelocationTypeIMTable});
1495 image_info.bin_slot_sizes_[kBinImTable] += size;
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001496 return true;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001497}
1498
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001499void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1500 // No offset, or already assigned.
1501 if (table == nullptr || NativeRelocationAssigned(table)) {
1502 return;
1503 }
1504 CHECK(!IsInBootImage(table));
1505 // If the method is a conflict method we also want to assign the conflict table offset.
1506 ImageInfo& image_info = GetImageInfo(oat_index);
1507 const size_t size = table->ComputeSize(target_ptr_size_);
1508 native_object_relocations_.emplace(
1509 table,
1510 NativeObjectRelocation {
1511 oat_index,
1512 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1513 kNativeObjectRelocationTypeIMTConflictTable});
1514 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1515}
1516
Jeff Haodcdc85b2015-12-04 14:06:18 -08001517void ImageWriter::AssignMethodOffset(ArtMethod* method,
1518 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001519 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001520 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001521 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
David Sehr709b0702016-10-13 09:12:37 -07001522 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001523 if (method->IsRuntimeMethod()) {
1524 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1525 }
Vladimir Marko944da602016-02-19 12:27:55 +00001526 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001527 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001528 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001529 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001530}
1531
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001532void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001533 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001534 CHECK(obj != nullptr);
1535
1536 // We know the bin slot, and the total bin sizes for all objects by now,
1537 // so calculate the object's final image offset.
1538
1539 DCHECK(IsImageBinSlotAssigned(obj));
1540 BinSlot bin_slot = GetImageBinSlot(obj);
1541 // Change the lockword from a bin slot into an offset
1542 AssignImageOffset(obj, bin_slot);
1543}
1544
Mathieu Chartier496577f2016-09-20 15:33:31 -07001545class ImageWriter::VisitReferencesVisitor {
1546 public:
1547 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index)
1548 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {}
1549
1550 // Fix up separately since we also need to fix up method entrypoints.
1551 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1552 REQUIRES_SHARED(Locks::mutator_lock_) {
1553 if (!root->IsNull()) {
1554 VisitRoot(root);
1555 }
1556 }
1557
1558 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1559 REQUIRES_SHARED(Locks::mutator_lock_) {
1560 root->Assign(VisitReference(root->AsMirrorPtr()));
1561 }
1562
Mathieu Chartier31e88222016-10-14 18:43:19 -07001563 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
Mathieu Chartier496577f2016-09-20 15:33:31 -07001564 MemberOffset offset,
1565 bool is_static ATTRIBUTE_UNUSED) const
1566 REQUIRES_SHARED(Locks::mutator_lock_) {
1567 mirror::Object* ref =
1568 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1569 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1570 }
1571
Mathieu Chartier31e88222016-10-14 18:43:19 -07001572 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1573 ObjPtr<mirror::Reference> ref) const
Mathieu Chartier496577f2016-09-20 15:33:31 -07001574 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001575 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001576 }
1577
1578 private:
1579 mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1580 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_);
1581 }
1582
1583 ImageWriter* const image_writer_;
1584 WorkStack* const work_stack_;
1585 const size_t oat_index_;
1586};
1587
1588class ImageWriter::GetRootsVisitor : public RootVisitor {
1589 public:
1590 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {}
1591
1592 void VisitRoots(mirror::Object*** roots,
1593 size_t count,
1594 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1595 REQUIRES_SHARED(Locks::mutator_lock_) {
1596 for (size_t i = 0; i < count; ++i) {
1597 roots_->push_back(*roots[i]);
1598 }
1599 }
1600
1601 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1602 size_t count,
1603 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1604 REQUIRES_SHARED(Locks::mutator_lock_) {
1605 for (size_t i = 0; i < count; ++i) {
1606 roots_->push_back(roots[i]->AsMirrorPtr());
1607 }
1608 }
1609
1610 private:
1611 std::vector<mirror::Object*>* const roots_;
1612};
1613
1614void ImageWriter::ProcessWorkStack(WorkStack* work_stack) {
1615 while (!work_stack->empty()) {
1616 std::pair<mirror::Object*, size_t> pair(work_stack->top());
1617 work_stack->pop();
1618 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second);
1619 // Walk references and assign bin slots for them.
1620 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1621 visitor,
1622 visitor);
1623 }
1624}
1625
Vladimir Markof4da6752014-08-01 19:04:18 +01001626void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001627 Thread* const self = Thread::Current();
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07001628 VariableSizedHandleScope handles(self);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001629 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001630 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1631 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001632 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001633
Mathieu Chartier496577f2016-09-20 15:33:31 -07001634 Runtime* const runtime = Runtime::Current();
1635 gc::Heap* const heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001636
Mathieu Chartier31e89252013-08-28 11:29:12 -07001637 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001638 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001639 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001640
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001641 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001642 // Write the image runtime methods.
1643 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1644 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1645 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001646 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001647 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves);
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001648 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001649 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly);
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001650 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001651 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001652 image_methods_[ImageHeader::kSaveEverythingMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001653 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001654 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001655 for (auto* m : image_methods_) {
1656 CHECK(m != nullptr);
1657 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001658 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1659 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001660 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001661 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001662 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001663
Mathieu Chartier496577f2016-09-20 15:33:31 -07001664 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
1665 // this lock while holding other locks may cause lock order violations.
Andreas Gampe1c158a02017-07-13 17:26:19 -07001666 {
1667 auto deflate_monitor = [](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1668 Monitor::Deflate(Thread::Current(), obj);
1669 };
1670 heap->VisitObjects(deflate_monitor);
1671 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001672
1673 // Work list of <object, oat_index> for objects. Everything on the stack must already be
1674 // assigned a bin slot.
1675 WorkStack work_stack;
1676
1677 // Special case interned strings to put them in the image they are likely to be resolved from.
1678 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
1679 auto it = dex_file_oat_index_map_.find(dex_file);
1680 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1681 const size_t oat_index = it->second;
1682 InternTable* const intern_table = runtime->GetInternTable();
1683 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
1684 uint32_t utf16_length;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001685 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(dex::StringIndex(i),
1686 &utf16_length);
Mathieu Chartier9e868092016-10-31 14:58:04 -07001687 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001688 TryAssignBinSlot(work_stack, string, oat_index);
1689 }
1690 }
1691
1692 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor
1693 // visits roots while holding various locks.
1694 {
1695 std::vector<mirror::Object*> roots;
1696 GetRootsVisitor root_visitor(&roots);
1697 runtime->VisitRoots(&root_visitor);
1698 for (mirror::Object* obj : roots) {
1699 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex());
1700 }
1701 }
1702 ProcessWorkStack(&work_stack);
1703
1704 // For app images, there may be objects that are only held live by the by the boot image. One
1705 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback
1706 // does not fail any checks. TODO: We should probably avoid copying these objects.
1707 if (compile_app_image_) {
1708 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) {
1709 DCHECK(space->IsImageSpace());
1710 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1711 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1712 reinterpret_cast<uintptr_t>(space->Limit()),
1713 [this, &work_stack](mirror::Object* obj)
1714 REQUIRES_SHARED(Locks::mutator_lock_) {
1715 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex());
1716 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot).
1717 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1718 visitor,
1719 visitor);
1720 });
1721 }
1722 // Process the work stack in case anything was added by TryAssignBinSlot.
1723 ProcessWorkStack(&work_stack);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001724
1725 // Store the class loader in the class roots.
1726 CHECK_EQ(class_loaders_.size(), 1u);
1727 CHECK_EQ(image_roots.size(), 1u);
1728 CHECK(*class_loaders_.begin() != nullptr);
1729 image_roots[0]->Set<false>(ImageHeader::kClassLoader, *class_loaders_.begin());
Mathieu Chartier496577f2016-09-20 15:33:31 -07001730 }
1731
1732 // Verify that all objects have assigned image bin slots.
Andreas Gampe1c158a02017-07-13 17:26:19 -07001733 {
1734 auto ensure_bin_slots_assigned = [&](mirror::Object* obj)
1735 REQUIRES_SHARED(Locks::mutator_lock_) {
1736 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) {
1737 CHECK(IsImageBinSlotAssigned(obj)) << mirror::Object::PrettyTypeOf(obj) << " " << obj;
1738 }
1739 };
1740 heap->VisitObjects(ensure_bin_slots_assigned);
1741 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001742
Vladimir Marko05792b92015-08-03 11:56:49 +01001743 // Calculate size of the dex cache arrays slot and prepare offsets.
1744 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001745
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001746 // Calculate the sizes of the intern tables, class tables, and fixup tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001747 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001748 // Calculate how big the intern table will be after being serialized.
1749 InternTable* const intern_table = image_info.intern_table_.get();
1750 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
Vladimir Marko1a1de672016-10-13 12:53:15 +01001751 if (intern_table->StrongSize() != 0u) {
1752 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1753 }
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001754
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001755 // Calculate the size of the class table.
1756 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001757 DCHECK_EQ(image_info.class_table_->NumReferencedZygoteClasses(), 0u);
1758 if (image_info.class_table_->NumReferencedNonZygoteClasses() != 0u) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001759 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
1760 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001761 }
1762
Vladimir Markocf36d492015-08-12 19:27:26 +01001763 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001764 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001765 size_t bin_offset = image_objects_offset_begin_;
1766 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001767 switch (i) {
1768 case kBinArtMethodClean:
1769 case kBinArtMethodDirty: {
1770 bin_offset = RoundUp(bin_offset, method_alignment);
1771 break;
1772 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001773 case kBinDexCacheArray:
Vladimir Markof44d36c2017-03-14 14:18:46 +00001774 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment(target_ptr_size_));
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001775 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001776 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001777 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001778 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001779 break;
1780 }
1781 default: {
1782 // Normal alignment.
1783 }
1784 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001785 image_info.bin_slot_offsets_[i] = bin_offset;
1786 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001787 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001788 // NOTE: There may be additional padding between the bin slots and the intern table.
1789 DCHECK_EQ(image_info.image_end_,
1790 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001791 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001792
Jeff Haodcdc85b2015-12-04 14:06:18 -08001793 // Calculate image offsets.
1794 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001795 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001796 image_info.image_begin_ = global_image_begin_ + image_offset;
1797 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001798 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001799 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001800 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001801 image_offset += image_info.image_size_;
1802 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001803
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001804 // 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 -07001805 {
1806 auto unbin_objects_into_offset = [&](mirror::Object* obj)
1807 REQUIRES_SHARED(Locks::mutator_lock_) {
1808 if (!IsInBootImage(obj)) {
1809 UnbinObjectsIntoOffset(obj);
1810 }
1811 };
1812 heap->VisitObjects(unbin_objects_into_offset);
1813 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001814
Jeff Haodcdc85b2015-12-04 14:06:18 -08001815 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001816 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001817 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1818 i++;
1819 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001820
Mathieu Chartiere401d142015-04-22 13:56:20 -07001821 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001822 for (auto& pair : native_object_relocations_) {
1823 NativeObjectRelocation& relocation = pair.second;
1824 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001825 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001826 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001827 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001828}
1829
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001830size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001831 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001832
1833 // Do not round up any sections here that are represented by the bins since it will break
1834 // offsets.
1835
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001836 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001837 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001838 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001839
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001840 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001841 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1842 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001843 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001844
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001845 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001846 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1847 *methods_section = ImageSection(
1848 bin_slot_offsets_[kBinArtMethodClean],
1849 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1850
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001851 // IMT section.
1852 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1853 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1854
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001855 // Conflict tables section.
1856 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1857 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1858 bin_slot_sizes_[kBinIMTConflictTable]);
1859
1860 // Runtime methods section.
1861 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1862 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1863 bin_slot_sizes_[kBinRuntimeMethod]);
1864
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001865 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001866 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1867 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1868 bin_slot_sizes_[kBinDexCacheArray]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001869 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001870 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001871 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001872 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001873 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1874 cur_pos = interned_strings_section->End();
1875 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1876 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1877 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001878 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001879 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001880 cur_pos = class_table_section->End();
1881 // Image end goes right before the start of the image bitmap.
1882 return cur_pos;
1883}
1884
Vladimir Marko944da602016-02-19 12:27:55 +00001885void ImageWriter::CreateHeader(size_t oat_index) {
1886 ImageInfo& image_info = GetImageInfo(oat_index);
1887 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1888 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1889 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001890
1891 // Create the image sections.
1892 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001893 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001894
Mathieu Chartiere401d142015-04-22 13:56:20 -07001895 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001896 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001897 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001898 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001899 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001900 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001901 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001902 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001903 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1904 ++idx;
1905 }
1906 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001907 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1908 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1909 << " Image offset=" << image_info.image_offset_ << std::dec;
1910 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1911 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1912 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1913 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001914 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001915 // Store boot image info for app image so that we can relocate.
1916 uint32_t boot_image_begin = 0;
1917 uint32_t boot_image_end = 0;
1918 uint32_t boot_oat_begin = 0;
1919 uint32_t boot_oat_end = 0;
1920 gc::Heap* const heap = Runtime::Current()->GetHeap();
1921 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001922
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001923 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1924 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001925 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1926 image_end,
1927 sections,
1928 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001929 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001930 PointerToLowMemUInt32(oat_file_begin),
1931 PointerToLowMemUInt32(image_info.oat_data_begin_),
1932 PointerToLowMemUInt32(oat_data_end),
1933 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001934 boot_image_begin,
1935 boot_image_end - boot_image_begin,
1936 boot_oat_begin,
1937 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001938 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001939 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001940 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001941 image_storage_mode_,
1942 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001943}
1944
1945ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001946 auto it = native_object_relocations_.find(method);
David Sehr709b0702016-10-13 09:12:37 -07001947 CHECK(it != native_object_relocations_.end()) << ArtMethod::PrettyMethod(method) << " @ "
1948 << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001949 size_t oat_index = GetOatIndex(method->GetDexCache());
1950 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001951 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1952 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001953}
1954
Vladimir Markoad06b982016-11-17 16:38:59 +00001955class ImageWriter::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001956 public:
1957 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1958 }
1959
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001960 void VisitRoots(mirror::Object*** roots ATTRIBUTE_UNUSED,
1961 size_t count ATTRIBUTE_UNUSED,
1962 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001963 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001964 LOG(FATAL) << "Unsupported";
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001965 }
1966
1967 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1968 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001969 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001970 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001971 image_writer_->CopyReference(roots[i], roots[i]->AsMirrorPtr());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001972 }
1973 }
1974
1975 private:
1976 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001977};
1978
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001979void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
1980 for (size_t i = 0; i < ImTable::kSize; ++i) {
1981 ArtMethod* method = orig->Get(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001982 void** address = reinterpret_cast<void**>(copy->AddressOfElement(i, target_ptr_size_));
1983 CopyAndFixupPointer(address, method);
1984 DCHECK_EQ(copy->Get(i, target_ptr_size_), NativeLocationInImage(method));
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001985 }
1986}
1987
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001988void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
1989 const size_t count = orig->NumEntries(target_ptr_size_);
1990 for (size_t i = 0; i < count; ++i) {
1991 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
1992 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001993 CopyAndFixupPointer(copy->AddressOfInterfaceMethod(i, target_ptr_size_), interface_method);
1994 CopyAndFixupPointer(copy->AddressOfImplementationMethod(i, target_ptr_size_),
1995 implementation_method);
1996 DCHECK_EQ(copy->GetInterfaceMethod(i, target_ptr_size_),
1997 NativeLocationInImage(interface_method));
1998 DCHECK_EQ(copy->GetImplementationMethod(i, target_ptr_size_),
1999 NativeLocationInImage(implementation_method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002000 }
2001}
2002
Vladimir Marko944da602016-02-19 12:27:55 +00002003void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002004 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002005 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002006 for (auto& pair : native_object_relocations_) {
2007 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002008 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00002009 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002010 continue;
2011 }
2012 auto* dest = image_info.image_->Begin() + relocation.offset;
2013 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002014 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002015 switch (relocation.type) {
2016 case kNativeObjectRelocationTypeArtField: {
2017 memcpy(dest, pair.first, sizeof(ArtField));
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002018 CopyReference(
2019 reinterpret_cast<ArtField*>(dest)->GetDeclaringClassAddressWithoutBarrier(),
2020 reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass().Ptr());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002021 break;
2022 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002023 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002024 case kNativeObjectRelocationTypeArtMethodClean:
2025 case kNativeObjectRelocationTypeArtMethodDirty: {
2026 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08002027 reinterpret_cast<ArtMethod*>(dest),
2028 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002029 break;
2030 }
2031 // For arrays, copy just the header since the elements will get copied by their corresponding
2032 // relocations.
2033 case kNativeObjectRelocationTypeArtFieldArray: {
2034 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
2035 break;
2036 }
2037 case kNativeObjectRelocationTypeArtMethodArrayClean:
2038 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00002039 size_t size = ArtMethod::Size(target_ptr_size_);
2040 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
2041 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
2042 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
2043 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002044 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00002045 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002046 case kNativeObjectRelocationTypeDexCacheArray:
2047 // Nothing to copy here, everything is done in FixupDexCache().
2048 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002049 case kNativeObjectRelocationTypeIMTable: {
2050 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
2051 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
2052 CopyAndFixupImTable(orig_imt, dest_imt);
2053 break;
2054 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002055 case kNativeObjectRelocationTypeIMTConflictTable: {
2056 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
2057 CopyAndFixupImtConflictTable(
2058 orig_table,
2059 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
2060 break;
2061 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002062 }
2063 }
2064 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002065 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002066 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002067 ArtMethod* method = image_methods_[i];
2068 CHECK(method != nullptr);
2069 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002070 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002071 }
2072 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002073 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002074 FixupRootVisitor root_visitor(this);
2075
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002076 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002077 if (image_info.intern_table_bytes_ > 0) {
2078 const ImageSection& intern_table_section = image_header->GetImageSection(
2079 ImageHeader::kSectionInternedStrings);
2080 InternTable* const intern_table = image_info.intern_table_.get();
2081 uint8_t* const intern_table_memory_ptr =
2082 image_info.image_->Begin() + intern_table_section.Offset();
2083 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
2084 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
2085 // Fixup the pointers in the newly written intern table to contain image addresses.
2086 InternTable temp_intern_table;
2087 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
2088 // the VisitRoots() will update the memory directly rather than the copies.
2089 // This also relies on visit roots not doing any verification which could fail after we update
2090 // the roots to be the image addresses.
2091 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
2092 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
2093 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
2094 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002095 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
2096 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002097 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002098 const ImageSection& class_table_section = image_header->GetImageSection(
2099 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002100 uint8_t* const class_table_memory_ptr =
2101 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002102 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002103
2104 ClassTable* table = image_info.class_table_.get();
2105 CHECK(table != nullptr);
2106 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
2107 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
2108 // Fixup the pointers in the newly written class table to contain image addresses. See
2109 // above comment for intern tables.
2110 ClassTable temp_class_table;
2111 temp_class_table.ReadFromMemory(class_table_memory_ptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002112 CHECK_EQ(temp_class_table.NumReferencedZygoteClasses(),
2113 table->NumReferencedNonZygoteClasses() + table->NumReferencedZygoteClasses());
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002114 UnbufferedRootVisitor visitor(&root_visitor, RootInfo(kRootUnknown));
2115 temp_class_table.VisitRoots(visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002116 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002117}
2118
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08002119void ImageWriter::CopyAndFixupObjects() {
Andreas Gampe1c158a02017-07-13 17:26:19 -07002120 auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2121 DCHECK(obj != nullptr);
2122 CopyAndFixupObject(obj);
2123 };
2124 Runtime::Current()->GetHeap()->VisitObjects(visitor);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002125 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002126 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08002127 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07002128 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
2129 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002130 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002131 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002132}
2133
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002134void ImageWriter::FixupPointerArray(mirror::Object* dst,
2135 mirror::PointerArray* arr,
2136 mirror::Class* klass,
2137 Bin array_type) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002138 CHECK(klass->IsArrayClass());
David Sehr709b0702016-10-13 09:12:37 -07002139 CHECK(arr->IsIntArray() || arr->IsLongArray()) << klass->PrettyClass() << " " << arr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002140 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07002141 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002142 dst->SetClass(GetImageAddress(arr->GetClass()));
2143 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002144 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002145 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002146 if (kIsDebugBuild && elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002147 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01002148 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002149 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002150 auto* method = reinterpret_cast<ArtMethod*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07002151 LOG(FATAL) << "No relocation entry for ArtMethod " << method->PrettyMethod() << " @ "
2152 << method << " idx=" << i << "/" << num_elements << " with declaring class "
2153 << Class::PrettyClass(method->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002154 } else {
2155 CHECK_EQ(array_type, kBinArtField);
2156 auto* field = reinterpret_cast<ArtField*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07002157 LOG(FATAL) << "No relocation entry for ArtField " << field->PrettyField() << " @ "
Mathieu Chartiere401d142015-04-22 13:56:20 -07002158 << field << " idx=" << i << "/" << num_elements << " with declaring class "
David Sehr709b0702016-10-13 09:12:37 -07002159 << Class::PrettyClass(field->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002160 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002161 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002162 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002163 }
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002164 CopyAndFixupPointer(dest_array->ElementAddress(i, target_ptr_size_), elem);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002165 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002166}
2167
2168void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002169 if (IsInBootImage(obj)) {
2170 return;
2171 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002172 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00002173 size_t oat_index = GetOatIndex(obj);
2174 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002175 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
2176 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002177 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002178
Jeff Haodcdc85b2015-12-04 14:06:18 -08002179 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002180
2181 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002182 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002183 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002184
Mathieu Chartierad2541a2013-10-25 10:05:23 -07002185 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
2186 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002187 const auto it = saved_hashcode_map_.find(obj);
2188 dst->SetLockWord(it != saved_hashcode_map_.end() ?
2189 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002190 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
2191 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
2192 // safe since we mark all of the objects that may reference non immune objects as gray.
2193 CHECK(dst->AtomicSetMarkBit(0, 1));
2194 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002195 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002196}
2197
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002198// Rewrite all the references in the copied object to point to their image address equivalent
Vladimir Markoad06b982016-11-17 16:38:59 +00002199class ImageWriter::FixupVisitor {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002200 public:
2201 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
2202 }
2203
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002204 // Ignore class roots since we don't have a way to map them to the destination. These are handled
2205 // with other logic.
2206 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
2207 const {}
2208 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
2209
2210
Mathieu Chartier31e88222016-10-14 18:43:19 -07002211 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002212 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07002213 ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002214 // Copy the reference and record the fixup if necessary.
2215 image_writer_->CopyReference(
2216 copy_->GetFieldObjectReferenceAddr<kVerifyNone>(offset),
2217 ref.Ptr());
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002218 }
2219
2220 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07002221 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2222 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002223 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002224 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002225 }
2226
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002227 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002228 ImageWriter* const image_writer_;
2229 mirror::Object* const copy_;
2230};
2231
Vladimir Markoad06b982016-11-17 16:38:59 +00002232class ImageWriter::FixupClassVisitor FINAL : public FixupVisitor {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002233 public:
2234 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
2235 }
2236
Mathieu Chartier31e88222016-10-14 18:43:19 -07002237 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07002238 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002239 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002240 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002241 }
2242
Mathieu Chartier31e88222016-10-14 18:43:19 -07002243 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2244 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002245 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002246 LOG(FATAL) << "Reference not expected here.";
2247 }
2248};
2249
Vladimir Marko05792b92015-08-03 11:56:49 +01002250uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
2251 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002252 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002253 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002254 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
2255 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002256 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01002257 return relocation.offset;
2258}
2259
2260template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002261std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002262 std::ostringstream oss;
2263 oss << ptr;
2264 return oss.str();
2265}
2266
2267template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002268std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07002269 return ArtMethod::PrettyMethod(method);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002270}
2271
2272template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002273T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002274 if (obj == nullptr || IsInBootImage(obj)) {
2275 return obj;
2276 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002277 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002278 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
2279 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002280 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00002281 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002282 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002283 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002284}
2285
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002286template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08002287T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
2288 if (obj == nullptr || IsInBootImage(obj)) {
2289 return obj;
2290 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002291 size_t oat_index = GetOatIndexForDexCache(dex_cache);
2292 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002293 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
2294 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002295}
2296
Vladimir Markoad06b982016-11-17 16:38:59 +00002297class ImageWriter::NativeLocationVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002298 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002299 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002300
2301 template <typename T>
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002302 T* operator()(T* ptr, void** dest_addr = nullptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
2303 if (dest_addr != nullptr) {
2304 image_writer_->CopyAndFixupPointer(dest_addr, ptr);
2305 }
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002306 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002307 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002308
2309 private:
2310 ImageWriter* const image_writer_;
2311};
2312
2313void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002314 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002315 FixupClassVisitor visitor(this, copy);
Mathieu Chartier31e88222016-10-14 18:43:19 -07002316 ObjPtr<mirror::Object>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002317
2318 // Remove the clinitThreadId. This is required for image determinism.
2319 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002320}
2321
Ian Rogersef7d42f2014-01-06 12:55:46 -08002322void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002323 DCHECK(orig != nullptr);
2324 DCHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002325 if (kUseBakerReadBarrier) {
2326 orig->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002327 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002328 auto* klass = orig->GetClass();
2329 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002330 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07002331 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
2332 if (it != pointer_arrays_.end()) {
2333 // Should only need to fixup every pointer array exactly once.
2334 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
2335 pointer_arrays_.erase(it);
2336 return;
2337 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002338 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002339 if (orig->IsClass()) {
2340 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002341 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002342 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
2343 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01002344 auto* dest = down_cast<mirror::Executable*>(copy);
2345 auto* src = down_cast<mirror::Executable*>(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002346 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05002347 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01002348 } else if (!klass->IsArrayClass()) {
2349 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2350 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
2351 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002352 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002353 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002354 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2355 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002356 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002357 // Also set allocator to null to be safe. The allocator is created when we create the class
2358 // table. We also never expect to unload things in the image since they are held live as
2359 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002360 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002361 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002362 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002363 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002364 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002365 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002366}
2367
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002368class ImageWriter::ImageAddressVisitorForDexCacheArray {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002369 public:
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002370 explicit ImageAddressVisitorForDexCacheArray(ImageWriter* image_writer)
2371 : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002372
2373 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002374 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002375 return image_writer_->GetImageAddress(ptr);
2376 }
2377
2378 private:
2379 ImageWriter* const image_writer_;
2380};
2381
Vladimir Marko05792b92015-08-03 11:56:49 +01002382void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2383 mirror::DexCache* copy_dex_cache) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002384 ImageAddressVisitorForDexCacheArray fixup_visitor(this);
Vladimir Marko05792b92015-08-03 11:56:49 +01002385 // Though the DexCache array fields are usually treated as native pointers, we set the full
2386 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2387 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2388 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002389 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002390 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002391 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002392 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002393 PointerSize::k64);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002394 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache), fixup_visitor);
Vladimir Marko05792b92015-08-03 11:56:49 +01002395 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002396 mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
Vladimir Marko05792b92015-08-03 11:56:49 +01002397 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002398 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002399 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002400 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002401 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002402 fixup_visitor);
Vladimir Marko05792b92015-08-03 11:56:49 +01002403 }
2404 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
2405 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002406 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002407 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002408 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002409 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002410 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
2411 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002412 // NativeLocationInImage also handles runtime methods since these have relocation info.
2413 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002414 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
2415 }
2416 }
Vladimir Markof44d36c2017-03-14 14:18:46 +00002417 mirror::FieldDexCacheType* orig_fields = orig_dex_cache->GetResolvedFields();
Vladimir Marko05792b92015-08-03 11:56:49 +01002418 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002419 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002420 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002421 PointerSize::k64);
Vladimir Markof44d36c2017-03-14 14:18:46 +00002422 mirror::FieldDexCacheType* copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002423 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00002424 mirror::FieldDexCachePair orig =
2425 mirror::DexCache::GetNativePairPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002426 mirror::FieldDexCachePair copy = orig;
2427 copy.object = NativeLocationInImage(orig.object);
Vladimir Markof44d36c2017-03-14 14:18:46 +00002428 mirror::DexCache::SetNativePairPtrSize(copy_fields, i, copy, target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002429 }
2430 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01002431 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
2432 if (orig_method_types != nullptr) {
2433 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodTypesOffset(),
2434 NativeLocationInImage(orig_method_types),
2435 PointerSize::k64);
2436 orig_dex_cache->FixupResolvedMethodTypes(NativeCopyLocation(orig_method_types, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002437 fixup_visitor);
Narayan Kamath7fe56582016-10-14 18:49:12 +01002438 }
Orion Hodsonc069a302017-01-18 09:23:12 +00002439 GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
2440 if (orig_call_sites != nullptr) {
2441 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedCallSitesOffset(),
2442 NativeLocationInImage(orig_call_sites),
2443 PointerSize::k64);
2444 orig_dex_cache->FixupResolvedCallSites(NativeCopyLocation(orig_call_sites, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002445 fixup_visitor);
Orion Hodsonc069a302017-01-18 09:23:12 +00002446 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002447
2448 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2449 // compiler pointers in here will make the output non-deterministic.
2450 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002451}
2452
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002453const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2454 DCHECK_LT(type, kOatAddressCount);
2455 // If we are compiling an app image, we need to use the stubs of the boot image.
2456 if (compile_app_image_) {
2457 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002458 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002459 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2460 DCHECK(!image_spaces.empty());
2461 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002462 CHECK(oat_file != nullptr);
2463 const OatHeader& header = oat_file->GetOatHeader();
2464 switch (type) {
2465 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2466 case kOatAddressQuickGenericJNITrampoline:
2467 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2468 case kOatAddressInterpreterToInterpreterBridge:
2469 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2470 case kOatAddressInterpreterToCompiledCodeBridge:
2471 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2472 case kOatAddressJNIDlsymLookup:
2473 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2474 case kOatAddressQuickIMTConflictTrampoline:
2475 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2476 case kOatAddressQuickResolutionTrampoline:
2477 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2478 case kOatAddressQuickToInterpreterBridge:
2479 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2480 default:
2481 UNREACHABLE();
2482 }
2483 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002484 const ImageInfo& primary_image_info = GetImageInfo(0);
2485 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002486}
2487
Jeff Haodcdc85b2015-12-04 14:06:18 -08002488const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2489 const ImageInfo& image_info,
2490 bool* quick_is_interpreted) {
David Sehr709b0702016-10-13 09:12:37 -07002491 DCHECK(!method->IsResolutionMethod()) << method->PrettyMethod();
2492 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << method->PrettyMethod();
2493 DCHECK(!method->IsImtUnimplementedMethod()) << method->PrettyMethod();
2494 DCHECK(method->IsInvokable()) << method->PrettyMethod();
2495 DCHECK(!IsInBootImage(method)) << method->PrettyMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002496
2497 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2498 // trampoline.
2499
2500 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002501 const void* quick_oat_entry_point =
2502 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2503 const uint8_t* quick_code;
2504
2505 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2506 DCHECK(method->IsCopied());
2507 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2508 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2509 } else {
2510 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2511 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2512 }
2513
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002514 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002515 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2516 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002517 // We have code for a non-static or initialized method, just use the code.
2518 } else if (quick_code == nullptr && method->IsNative() &&
2519 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2520 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002521 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002522 } else if (quick_code == nullptr && !method->IsNative()) {
2523 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002524 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002525 *quick_is_interpreted = true;
2526 } else {
2527 CHECK(!method->GetDeclaringClass()->IsInitialized());
2528 // We have code for a static method, but need to go through the resolution stub for class
2529 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002530 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2531 }
2532 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002533 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002534 }
2535 return quick_code;
2536}
2537
Jeff Haodcdc85b2015-12-04 14:06:18 -08002538void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2539 ArtMethod* copy,
2540 const ImageInfo& image_info) {
Mingyao Yange8fcd012017-01-20 10:43:30 -08002541 if (orig->IsAbstract()) {
2542 // Ignore the single-implementation info for abstract method.
2543 // Do this on orig instead of copy, otherwise there is a crash due to methods
2544 // are copied before classes.
2545 // TODO: handle fixup of single-implementation method for abstract method.
2546 orig->SetHasSingleImplementation(false);
2547 orig->SetSingleImplementation(
2548 nullptr, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
2549 }
2550
Vladimir Marko14632852015-08-17 12:07:23 +01002551 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002552
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002553 CopyReference(copy->GetDeclaringClassAddressWithoutBarrier(), orig->GetDeclaringClassUnchecked());
2554
Vladimir Marko05792b92015-08-03 11:56:49 +01002555 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002556 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002557
Ian Rogers848871b2013-08-05 10:56:33 -07002558 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2559 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002560
Ian Rogers848871b2013-08-05 10:56:33 -07002561 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002562 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002563 if (orig->IsRuntimeMethod()) {
2564 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2565 if (orig_table != nullptr) {
2566 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2567 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2568 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2569 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2570 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2571 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2572 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2573 } else {
2574 bool found_one = false;
Andreas Gampe8228cdf2017-05-30 15:03:54 -07002575 for (size_t i = 0; i < static_cast<size_t>(CalleeSaveType::kLastCalleeSaveType); ++i) {
2576 auto idx = static_cast<CalleeSaveType>(i);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002577 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2578 found_one = true;
2579 break;
2580 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002581 }
David Sehr709b0702016-10-13 09:12:37 -07002582 CHECK(found_one) << "Expected to find callee save method but got " << orig->PrettyMethod();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002583 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002584 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002585 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002586 // We assume all methods have code. If they don't currently then we set them to the use the
2587 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2588 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002589 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002590 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002591 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002592 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002593 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002594 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002595 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002596
Sebastien Hertze1d07812014-05-21 15:44:09 +02002597 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002598 if (orig->IsNative()) {
2599 // The native method's pointer is set to a stub to lookup via dlsym.
2600 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002601 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002602 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002603 }
2604 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002605 }
2606}
2607
Jeff Haodcdc85b2015-12-04 14:06:18 -08002608size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002609 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002610 return std::accumulate(&image_info.bin_slot_sizes_[0],
2611 &image_info.bin_slot_sizes_[up_to],
2612 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002613}
2614
2615ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2616 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002617 static_assert(kBinBits == 3, "wrong number of bin bits");
2618 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002619 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2620
2621 DCHECK_LT(GetBin(), kBinSize);
2622 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2623}
2624
2625ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2626 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2627 DCHECK_EQ(index, GetIndex());
2628}
2629
2630ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2631 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2632}
2633
2634uint32_t ImageWriter::BinSlot::GetIndex() const {
2635 return lockword_ & ~kBinMask;
2636}
2637
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002638ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2639 switch (type) {
2640 case kNativeObjectRelocationTypeArtField:
2641 case kNativeObjectRelocationTypeArtFieldArray:
2642 return kBinArtField;
2643 case kNativeObjectRelocationTypeArtMethodClean:
2644 case kNativeObjectRelocationTypeArtMethodArrayClean:
2645 return kBinArtMethodClean;
2646 case kNativeObjectRelocationTypeArtMethodDirty:
2647 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2648 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002649 case kNativeObjectRelocationTypeDexCacheArray:
2650 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002651 case kNativeObjectRelocationTypeRuntimeMethod:
2652 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002653 case kNativeObjectRelocationTypeIMTable:
2654 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002655 case kNativeObjectRelocationTypeIMTConflictTable:
2656 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002657 }
2658 UNREACHABLE();
2659}
2660
Vladimir Marko944da602016-02-19 12:27:55 +00002661size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002662 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002663 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002664 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002665 auto it = oat_index_map_.find(obj);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002666 DCHECK(it != oat_index_map_.end()) << obj;
Mathieu Chartier496577f2016-09-20 15:33:31 -07002667 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002668}
2669
Vladimir Marko944da602016-02-19 12:27:55 +00002670size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002671 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002672 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002673 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002674 auto it = dex_file_oat_index_map_.find(dex_file);
2675 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2676 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002677}
2678
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002679size_t ImageWriter::GetOatIndexForDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
2680 return (dex_cache == nullptr)
2681 ? GetDefaultOatIndex()
2682 : GetOatIndexForDexFile(dex_cache->GetDexFile());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002683}
2684
Vladimir Marko944da602016-02-19 12:27:55 +00002685void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2686 size_t oat_loaded_size,
2687 size_t oat_data_offset,
2688 size_t oat_data_size) {
2689 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2690 for (const ImageInfo& info : image_infos_) {
2691 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2692 }
2693 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002694
Vladimir Marko944da602016-02-19 12:27:55 +00002695 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2696 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2697 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2698 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2699 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002700
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002701 if (compile_app_image_) {
2702 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2703 return;
2704 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002705
2706 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002707 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002708 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002709 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002710 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2711 }
2712}
2713
Vladimir Marko944da602016-02-19 12:27:55 +00002714void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2715 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2716 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2717
2718 if (oat_index == GetDefaultOatIndex()) {
2719 // Primary oat file, read the trampolines.
2720 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2721 oat_header.GetInterpreterToInterpreterBridgeOffset();
2722 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2723 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2724 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2725 oat_header.GetJniDlsymLookupOffset();
2726 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2727 oat_header.GetQuickGenericJniTrampolineOffset();
2728 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2729 oat_header.GetQuickImtConflictTrampolineOffset();
2730 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2731 oat_header.GetQuickResolutionTrampolineOffset();
2732 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2733 oat_header.GetQuickToInterpreterBridgeOffset();
2734 }
2735}
2736
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002737ImageWriter::ImageWriter(
2738 const CompilerDriver& compiler_driver,
2739 uintptr_t image_begin,
2740 bool compile_pic,
2741 bool compile_app_image,
2742 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002743 const std::vector<const char*>& oat_filenames,
2744 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002745 : compiler_driver_(compiler_driver),
2746 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2747 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002748 compile_pic_(compile_pic),
2749 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002750 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002751 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002752 dirty_methods_(0u),
2753 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002754 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002755 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002756 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002757 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002758 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002759 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2760 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002761}
2762
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002763ImageWriter::ImageInfo::ImageInfo()
2764 : intern_table_(new InternTable),
2765 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002766
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002767void ImageWriter::CopyReference(mirror::HeapReference<mirror::Object>* dest,
2768 ObjPtr<mirror::Object> src) {
2769 dest->Assign(GetImageAddress(src.Ptr()));
2770}
2771
2772void ImageWriter::CopyReference(mirror::CompressedReference<mirror::Object>* dest,
2773 ObjPtr<mirror::Object> src) {
2774 dest->Assign(GetImageAddress(src.Ptr()));
2775}
2776
2777void ImageWriter::CopyAndFixupPointer(void** target, void* value) {
2778 void* new_value = value;
2779 if (value != nullptr && !IsInBootImage(value)) {
2780 auto it = native_object_relocations_.find(value);
2781 CHECK(it != native_object_relocations_.end()) << value;
2782 const NativeObjectRelocation& relocation = it->second;
2783 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2784 new_value = reinterpret_cast<void*>(image_info.image_begin_ + relocation.offset);
2785 }
2786 if (target_ptr_size_ == PointerSize::k32) {
2787 *reinterpret_cast<uint32_t*>(target) = PointerToLowMemUInt32(new_value);
2788 } else {
2789 *reinterpret_cast<uint64_t*>(target) = reinterpret_cast<uintptr_t>(new_value);
2790 }
2791}
2792
2793
Brian Carlstrom7940e442013-07-12 13:46:57 -07002794} // namespace art