blob: a70669749671c8201103ba9af98f8ead2a0300d0 [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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070030#include "base/logging.h"
31#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010032#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070033#include "compiled_method.h"
34#include "dex_file-inl.h"
Andreas Gampea5b09a62016-11-17 15:21:22 -080035#include "dex_file_types.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070036#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070037#include "elf_file.h"
38#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070039#include "elf_writer.h"
40#include "gc/accounting/card_table-inl.h"
41#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070042#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier36a270a2016-07-28 18:08:51 -070043#include "gc/collector/concurrent_copying.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070044#include "gc/heap.h"
45#include "gc/space/large_object_space.h"
46#include "gc/space/space-inl.h"
47#include "globals.h"
48#include "image.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070049#include "imt_conflict_table.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070051#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070052#include "lock_word.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070053#include "mirror/array-inl.h"
54#include "mirror/class-inl.h"
Alex Lightd6251582016-10-31 11:12:30 -070055#include "mirror/class_ext.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "mirror/class_loader.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070057#include "mirror/dex_cache.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "mirror/dex_cache-inl.h"
Neil Fuller0e844392016-09-08 13:43:31 +010059#include "mirror/executable.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070060#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "mirror/object-inl.h"
62#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070063#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "oat.h"
65#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070066#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070068#include "scoped_thread_state_change-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070069#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000070#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070071
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070072using ::art::mirror::Class;
73using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070074using ::art::mirror::Object;
75using ::art::mirror::ObjectArray;
76using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070077
78namespace art {
79
Igor Murashkinf5b4c502014-11-14 15:01:59 -080080// Separate objects into multiple bins to optimize dirty memory use.
81static constexpr bool kBinObjects = true;
82
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080083// Return true if an object is already in an image space.
84bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080085 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080086 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080087 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080088 return false;
89 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080090 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
91 const uint8_t* image_begin = boot_image_space->Begin();
92 // Real image end including ArtMethods and ArtField sections.
93 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
94 if (image_begin <= obj && obj < image_end) {
95 return true;
96 }
97 }
98 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080099}
100
101bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800102 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800103 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800104 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800105 return false;
106 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800107 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
108 const ImageHeader& image_header = boot_image_space->GetImageHeader();
109 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
110 return true;
111 }
112 }
113 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800114}
115
Andreas Gampedd9d0552015-03-09 12:57:41 -0700116static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700117 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700118 Class* klass = obj->GetClass();
David Sehr709b0702016-10-13 09:12:37 -0700119 CHECK_NE(Class::PrettyClass(klass), "com.android.dex.Dex");
Andreas Gampedd9d0552015-03-09 12:57:41 -0700120}
121
122static void CheckNoDexObjects() {
123 ScopedObjectAccess soa(Thread::Current());
124 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
125}
126
Vladimir Markof4da6752014-08-01 19:04:18 +0100127bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800128 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800129 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100130 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700131 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100132 PruneNonImageClasses(); // Remove junk
Mathieu Chartier901e0702016-02-19 13:42:48 -0800133 if (!compile_app_image_) {
134 // Avoid for app image since this may increase RAM and image size.
135 ComputeLazyFieldsForImageClasses(); // Add useful information
136 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100137 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100138 heap->CollectGarbage(false); // Remove garbage.
139
Andreas Gampedd9d0552015-03-09 12:57:41 -0700140 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
141 // dex files.
142 //
143 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
144 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
145 // true.
146 if (kIsDebugBuild) {
147 CheckNoDexObjects();
148 }
149
Vladimir Markof4da6752014-08-01 19:04:18 +0100150 if (kIsDebugBuild) {
151 ScopedObjectAccess soa(Thread::Current());
152 CheckNonImageClassesRemoved();
153 }
154
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700155 {
156 ScopedObjectAccess soa(Thread::Current());
157 CalculateNewObjectOffsets();
158 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100159
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700160 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
161 // bin size sums being calculated.
162 if (!AllocMemory()) {
163 return false;
164 }
165
Vladimir Markof4da6752014-08-01 19:04:18 +0100166 return true;
167}
168
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700169bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800170 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000171 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800172 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
173 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800174 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800175 if (image_fd != kInvalidFd) {
176 CHECK_EQ(image_filenames.size(), 1u);
177 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800178 CHECK(!oat_filenames.empty());
179 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700180
Vladimir Marko944da602016-02-19 12:27:55 +0000181 {
182 ScopedObjectAccess soa(Thread::Current());
183 for (size_t i = 0; i < oat_filenames.size(); ++i) {
184 CreateHeader(i);
185 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800186 }
187 }
Alex Light53cb16b2014-06-12 11:26:29 -0700188
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700189 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700190 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800191 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700192 Runtime::Current()->GetHeap()->DisableObjectValidation();
193 CopyAndFixupObjects();
194 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700195
Jeff Haodcdc85b2015-12-04 14:06:18 -0800196 for (size_t i = 0; i < image_filenames.size(); ++i) {
197 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000198 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800199 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800200 if (image_fd != kInvalidFd) {
201 if (strlen(image_filename) == 0u) {
202 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800203 // Empty the file in case it already exists.
204 if (image_file != nullptr) {
205 TEMP_FAILURE_RETRY(image_file->SetLength(0));
206 TEMP_FAILURE_RETRY(image_file->Flush());
207 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800208 } else {
209 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
210 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800211 } else {
212 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800213 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800214
Jeff Haodcdc85b2015-12-04 14:06:18 -0800215 if (image_file == nullptr) {
216 LOG(ERROR) << "Failed to open image file " << image_filename;
217 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800218 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800219
220 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800221 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
222 image_file->Erase();
223 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800224 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800225
Jeff Haodcdc85b2015-12-04 14:06:18 -0800226 std::unique_ptr<char[]> compressed_data;
227 // Image data size excludes the bitmap and the header.
228 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
229 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
230 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
231 size_t data_size;
232 const char* image_data_to_write;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800233 const uint64_t compress_start_time = NanoTime();
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000234
Jeff Haodcdc85b2015-12-04 14:06:18 -0800235 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
236 switch (image_storage_mode_) {
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700237 case ImageHeader::kStorageModeLZ4HC: // Fall-through.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800238 case ImageHeader::kStorageModeLZ4: {
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800239 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800240 compressed_data.reset(new char[compressed_max_size]);
241 data_size = LZ4_compress(
242 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
243 &compressed_data[0],
244 image_data_size);
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800245
246 break;
247 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700248 /*
249 * Disabled due to image_test64 flakyness. Both use same decompression. b/27560444
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800250 case ImageHeader::kStorageModeLZ4HC: {
251 // Bound is same as non HC.
252 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
253 compressed_data.reset(new char[compressed_max_size]);
254 data_size = LZ4_compressHC(
255 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
256 &compressed_data[0],
257 image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800258 break;
259 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700260 */
Jeff Haodcdc85b2015-12-04 14:06:18 -0800261 case ImageHeader::kStorageModeUncompressed: {
262 data_size = image_data_size;
263 image_data_to_write = image_data;
264 break;
265 }
266 default: {
267 LOG(FATAL) << "Unsupported";
268 UNREACHABLE();
269 }
270 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800271
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800272 if (compressed_data != nullptr) {
273 image_data_to_write = &compressed_data[0];
274 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
275 << PrettyDuration(NanoTime() - compress_start_time);
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700276 if (kIsDebugBuild) {
277 std::unique_ptr<uint8_t[]> temp(new uint8_t[image_data_size]);
278 const size_t decompressed_size = LZ4_decompress_safe(
279 reinterpret_cast<char*>(&compressed_data[0]),
280 reinterpret_cast<char*>(&temp[0]),
281 data_size,
282 image_data_size);
283 CHECK_EQ(decompressed_size, image_data_size);
284 CHECK_EQ(memcmp(image_data, &temp[0], image_data_size), 0) << image_storage_mode_;
285 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800286 }
287
Jeff Haodcdc85b2015-12-04 14:06:18 -0800288 // Write out the image + fields + methods.
289 const bool is_compressed = compressed_data != nullptr;
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800290 if (!image_file->PwriteFully(image_data_to_write, data_size, sizeof(ImageHeader))) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800291 PLOG(ERROR) << "Failed to write image file data " << image_filename;
292 image_file->Erase();
293 return false;
294 }
295
296 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
297 // convenience.
298 const ImageSection& bitmap_section = image_header->GetImageSection(
299 ImageHeader::kSectionImageBitmap);
300 // Align up since data size may be unaligned if the image is compressed.
301 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
302 if (!is_compressed) {
303 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
304 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800305 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
306 bitmap_section.Size(),
307 bitmap_position_in_file)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800308 PLOG(ERROR) << "Failed to write image file " << image_filename;
309 image_file->Erase();
310 return false;
311 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800312
313 int err = image_file->Flush();
314 if (err < 0) {
315 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
316 image_file->Erase();
317 return false;
318 }
319
320 // Write header last in case the compiler gets killed in the middle of image writing.
321 // We do not want to have a corrupted image with a valid header.
322 // The header is uncompressed since it contains whether the image is compressed or not.
323 image_header->data_size_ = data_size;
324 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
325 sizeof(ImageHeader),
326 0)) {
327 PLOG(ERROR) << "Failed to write image file header " << image_filename;
328 image_file->Erase();
329 return false;
330 }
331
Jeff Haodcdc85b2015-12-04 14:06:18 -0800332 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
333 static_cast<size_t>(image_file->GetLength()));
334 if (image_file->FlushCloseOrErase() != 0) {
335 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
336 return false;
337 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800338 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700339 return true;
340}
341
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700342void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700343 DCHECK(object != nullptr);
344 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800345
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800346 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700347 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700348 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700349 DCHECK(IsImageOffsetAssigned(object));
350}
351
Mathieu Chartiere401d142015-04-22 13:56:20 -0700352void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
353 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
354 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
355 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
356}
357
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800358void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700359 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800360 DCHECK_NE(image_objects_offset_begin_, 0u);
361
Vladimir Marko944da602016-02-19 12:27:55 +0000362 size_t oat_index = GetOatIndex(object);
363 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800364 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100365 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800366 DCHECK_ALIGNED(new_offset, kObjectAlignment);
367
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700368 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800369 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700370}
371
Ian Rogersef7d42f2014-01-06 12:55:46 -0800372bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800373 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700374 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700375 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700376}
377
Ian Rogersef7d42f2014-01-06 12:55:46 -0800378size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700379 DCHECK(object != nullptr);
380 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700381 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700382 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000383 size_t oat_index = GetOatIndex(object);
384 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800385 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700386 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700387}
388
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800389void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
390 DCHECK(object != nullptr);
391 DCHECK(!IsImageOffsetAssigned(object));
392 DCHECK(!IsImageBinSlotAssigned(object));
393
394 // Before we stomp over the lock word, save the hash code for later.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800395 LockWord lw(object->GetLockWord(false));
396 switch (lw.GetState()) {
397 case LockWord::kFatLocked: {
398 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
399 break;
400 }
401 case LockWord::kThinLocked: {
402 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
403 break;
404 }
405 case LockWord::kUnlocked:
406 // No hash, don't need to save it.
407 break;
408 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700409 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
410 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800411 break;
412 default:
413 LOG(FATAL) << "Unreachable.";
414 UNREACHABLE();
415 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700416 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700417 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800418 DCHECK(IsImageBinSlotAssigned(object));
419}
420
Vladimir Marko20f85592015-03-19 10:07:02 +0000421void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000422 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000423 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
424 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800425 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000426 auto it = dex_file_oat_index_map_.find(dex_file);
427 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800428 ImageInfo& image_info = GetImageInfo(it->second);
429 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
430 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
431 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
432 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000433
Vladimir Marko20f85592015-03-19 10:07:02 +0000434 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700435 Thread* const self = Thread::Current();
436 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800437 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700438 ObjPtr<mirror::DexCache> dex_cache =
439 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
440 if (dex_cache == nullptr || IsInBootImage(dex_cache.Ptr())) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700441 continue;
442 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000443 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartier0b490842016-05-25 15:05:59 -0700444 CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
445 << "Dex cache should have been pruned " << dex_file->GetLocation()
446 << "; possibly in class path";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700447 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000448 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000449 size_t oat_index = GetOatIndexForDexCache(dex_cache);
450 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800451 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100452 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800453 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
454 start + layout.TypesOffset(),
455 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100456 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800457 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
458 start + layout.MethodsOffset(),
459 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100460 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800461 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
462 start + layout.FieldsOffset(),
463 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100464 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800465 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Narayan Kamath7fe56582016-10-14 18:49:12 +0100466
467 if (dex_cache->GetResolvedMethodTypes() != nullptr) {
468 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethodTypes(),
469 start + layout.MethodTypesOffset(),
470 dex_cache);
471 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000472 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000473}
474
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700475void ImageWriter::AddDexCacheArrayRelocation(void* array,
476 size_t offset,
477 ObjPtr<mirror::DexCache> dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100478 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800479 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000480 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800481 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000482 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100483 }
484}
485
Mathieu Chartiere401d142015-04-22 13:56:20 -0700486void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
487 DCHECK(arr != nullptr);
488 if (kIsDebugBuild) {
489 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800490 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700491 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800492 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800493 CHECK(klass == nullptr || KeepClass(klass))
David Sehr709b0702016-10-13 09:12:37 -0700494 << Class::PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700495 }
496 }
497 }
498 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
499 // ArtMethods.
500 pointer_arrays_.emplace(arr, kBinArtMethodClean);
501}
502
Mathieu Chartier496577f2016-09-20 15:33:31 -0700503void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800504 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800505 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800506
507 // The magic happens here. We segregate objects into different bins based
508 // on how likely they are to get dirty at runtime.
509 //
510 // Likely-to-dirty objects get packed together into the same bin so that
511 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
512 // maximized.
513 //
514 // This means more pages will stay either clean or shared dirty (with zygote) and
515 // the app will use less of its own (private) memory.
516 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000517 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800518
519 if (kBinObjects) {
520 //
521 // Changing the bin of an object is purely a memory-use tuning.
522 // It has no change on runtime correctness.
523 //
524 // Memory analysis has determined that the following types of objects get dirtied
525 // the most:
526 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000527 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
528 // a fixed layout which helps improve generated code (using PC-relative addressing),
529 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
530 // Since these arrays are huge, most pages do not overlap other objects and it's not
531 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100532 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800533 // * Class'es which are verified [their clinit runs only at runtime]
534 // - classes in general [because their static fields get overwritten]
535 // - initialized classes with all-final statics are unlikely to be ever dirty,
536 // so bin them separately
537 // * Art Methods that are:
538 // - native [their native entry point is not looked up until runtime]
539 // - have declaring classes that aren't initialized
540 // [their interpreter/quick entry points are trampolines until the class
541 // becomes initialized]
542 //
543 // We also assume the following objects get dirtied either never or extremely rarely:
544 // * Strings (they are immutable)
545 // * Art methods that aren't native and have initialized declared classes
546 //
547 // We assume that "regular" bin objects are highly unlikely to become dirtied,
548 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
549 //
550 if (object->IsClass()) {
551 bin = kBinClassVerified;
552 mirror::Class* klass = object->AsClass();
553
Mathieu Chartiere401d142015-04-22 13:56:20 -0700554 // Add non-embedded vtable to the pointer array table if there is one.
555 auto* vtable = klass->GetVTable();
556 if (vtable != nullptr) {
557 AddMethodPointerArray(vtable);
558 }
559 auto* iftable = klass->GetIfTable();
560 if (iftable != nullptr) {
561 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
562 if (iftable->GetMethodArrayCount(i) > 0) {
563 AddMethodPointerArray(iftable->GetMethodArray(i));
564 }
565 }
566 }
567
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800568 if (klass->GetStatus() == Class::kStatusInitialized) {
569 bin = kBinClassInitialized;
570
571 // If the class's static fields are all final, put it into a separate bin
572 // since it's very likely it will stay clean.
573 uint32_t num_static_fields = klass->NumStaticFields();
574 if (num_static_fields == 0) {
575 bin = kBinClassInitializedFinalStatics;
576 } else {
577 // Maybe all the statics are final?
578 bool all_final = true;
579 for (uint32_t i = 0; i < num_static_fields; ++i) {
580 ArtField* field = klass->GetStaticField(i);
581 if (!field->IsFinal()) {
582 all_final = false;
583 break;
584 }
585 }
586
587 if (all_final) {
588 bin = kBinClassInitializedFinalStatics;
589 }
590 }
591 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800592 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
593 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700594 } else if (object->GetClass<kVerifyNone>() ==
595 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
596 // Instance of java lang object, probably a lock object. This means it will be dirty when we
597 // synchronize on it.
598 bin = kBinMiscDirty;
599 } else if (object->IsDexCache()) {
600 // Dex file field becomes dirty when the image is loaded.
601 bin = kBinMiscDirty;
602 }
603 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800604 }
605
Mathieu Chartier496577f2016-09-20 15:33:31 -0700606 // Assign the oat index too.
607 DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
608 oat_index_map_.emplace(object, oat_index);
609
Vladimir Marko944da602016-02-19 12:27:55 +0000610 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800611
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800612 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800613 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
614 // Move the current bin size up to accommodate the object we just assigned a bin slot.
615 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800616
617 BinSlot new_bin_slot(bin, current_offset);
618 SetImageBinSlot(object, new_bin_slot);
619
Jeff Haodcdc85b2015-12-04 14:06:18 -0800620 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800621
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800622 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800623 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800624}
625
Mathieu Chartiere401d142015-04-22 13:56:20 -0700626bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
627 if (m->IsNative()) {
628 return true;
629 }
630 mirror::Class* declaring_class = m->GetDeclaringClass();
631 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
632 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
633}
634
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800635bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
636 DCHECK(object != nullptr);
637
638 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
639 // If it's in some other state, then we haven't yet assigned an image bin slot.
640 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
641 return false;
642 } else if (kIsDebugBuild) {
643 LockWord lock_word = object->GetLockWord(false);
644 size_t offset = lock_word.ForwardingAddress();
645 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000646 size_t oat_index = GetOatIndex(object);
647 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800648 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800649 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800650 }
651 return true;
652}
653
654ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
655 DCHECK(object != nullptr);
656 DCHECK(IsImageBinSlotAssigned(object));
657
658 LockWord lock_word = object->GetLockWord(false);
659 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
660 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
661
662 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000663 size_t oat_index = GetOatIndex(object);
664 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800665 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800666
667 return bin_slot;
668}
669
Brian Carlstrom7940e442013-07-12 13:46:57 -0700670bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000671 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800672 ImageSection unused_sections[ImageHeader::kSectionCount];
673 const size_t length = RoundUp(
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700674 image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800675
Jeff Haodcdc85b2015-12-04 14:06:18 -0800676 std::string error_msg;
677 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
678 nullptr,
679 length,
680 PROT_READ | PROT_WRITE,
681 false,
682 false,
683 &error_msg));
684 if (UNLIKELY(image_info.image_.get() == nullptr)) {
685 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
686 return false;
687 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700688
Jeff Haodcdc85b2015-12-04 14:06:18 -0800689 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
690 CHECK_LE(image_info.image_end_, length);
691 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
692 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
693 if (image_info.image_bitmap_.get() == nullptr) {
694 LOG(ERROR) << "Failed to allocate memory for image bitmap";
695 return false;
696 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700697 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700698 return true;
699}
700
Vladimir Markoad06b982016-11-17 16:38:59 +0000701class ImageWriter::ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700702 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700703 bool operator()(ObjPtr<Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700704 StackHandleScope<1> hs(Thread::Current());
705 mirror::Class::ComputeName(hs.NewHandle(c));
706 return true;
707 }
708};
709
Brian Carlstrom7940e442013-07-12 13:46:57 -0700710void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700711 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700712 ComputeLazyFieldsForClassesVisitor visitor;
713 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700714}
715
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700716static bool IsBootClassLoaderClass(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800717 return klass->GetClassLoader() == nullptr;
718}
719
720bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
721 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
722}
723
Mathieu Chartier901e0702016-02-19 13:42:48 -0800724bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800725 bool early_exit = false;
726 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800727 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800728}
729
Mathieu Chartier901e0702016-02-19 13:42:48 -0800730bool ImageWriter::PruneAppImageClassInternal(
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800731 mirror::Class* klass,
732 bool* early_exit,
733 std::unordered_set<mirror::Class*>* visited) {
734 DCHECK(early_exit != nullptr);
735 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800736 DCHECK(compile_app_image_);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800737 if (klass == nullptr || IsInBootImage(klass)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700738 return false;
739 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800740 auto found = prune_class_memo_.find(klass);
741 if (found != prune_class_memo_.end()) {
742 // Already computed, return the found value.
743 return found->second;
744 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800745 // Circular dependencies, return false but do not store the result in the memoization table.
746 if (visited->find(klass) != visited->end()) {
747 *early_exit = true;
748 return false;
749 }
750 visited->emplace(klass);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800751 bool result = IsBootClassLoaderClass(klass);
752 std::string temp;
753 // Prune if not an image class, this handles any broken sets of image classes such as having a
754 // class in the set but not it's superclass.
755 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800756 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800757 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
758 // app image.
759 if (klass->GetStatus() == mirror::Class::kStatusError) {
760 result = true;
761 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700762 ObjPtr<mirror::ClassExt> ext(klass->GetExtData());
763 CHECK(ext.IsNull() || ext->GetVerifyError() == nullptr) << klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800764 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800765 if (!result) {
766 // Check interfaces since these wont be visited through VisitReferences.)
767 mirror::IfTable* if_table = klass->GetIfTable();
768 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800769 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
770 &my_early_exit,
771 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800772 }
773 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800774 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800775 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
776 &my_early_exit,
777 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800778 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800779 // Check static fields and their classes.
780 size_t num_static_fields = klass->NumReferenceStaticFields();
781 if (num_static_fields != 0 && klass->IsResolved()) {
782 // Presumably GC can happen when we are cross compiling, it should not cause performance
783 // problems to do pointer size logic.
784 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
785 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
786 for (size_t i = 0u; i < num_static_fields; ++i) {
787 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
788 if (ref != nullptr) {
789 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800790 result = result || PruneAppImageClassInternal(ref->AsClass(),
791 &my_early_exit,
792 visited);
793 } else {
794 result = result || PruneAppImageClassInternal(ref->GetClass(),
795 &my_early_exit,
796 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800797 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800798 }
799 field_offset = MemberOffset(field_offset.Uint32Value() +
800 sizeof(mirror::HeapReference<mirror::Object>));
801 }
802 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800803 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
804 &my_early_exit,
805 visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800806 // Erase the element we stored earlier since we are exiting the function.
807 auto it = visited->find(klass);
808 DCHECK(it != visited->end());
809 visited->erase(it);
810 // Only store result if it is true or none of the calls early exited due to circular
811 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
812 // a child call and we can remember the result.
813 if (result == true || !my_early_exit || visited->empty()) {
814 prune_class_memo_[klass] = result;
815 }
816 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800817 return result;
818}
819
820bool ImageWriter::KeepClass(Class* klass) {
821 if (klass == nullptr) {
822 return false;
823 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800824 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
825 // Already in boot image, return true.
826 return true;
827 }
828 std::string temp;
829 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
830 return false;
831 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800832 if (compile_app_image_) {
833 // For app images, we need to prune boot loader classes that are not in the boot image since
834 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800835 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800836 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800837 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800838 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700839}
840
Vladimir Markoad06b982016-11-17 16:38:59 +0000841class ImageWriter::NonImageClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700842 public:
843 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
844
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700845 bool operator()(ObjPtr<Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
846 if (!image_writer_->KeepClass(klass.Ptr())) {
847 classes_to_prune_.insert(klass.Ptr());
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700848 }
849 return true;
850 }
851
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800852 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700853 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700854};
855
856void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700857 Runtime* runtime = Runtime::Current();
858 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700859 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700860
Mathieu Chartier696632e2016-06-03 17:47:32 -0700861 // Clear class table strong roots so that dex caches can get pruned. We require pruning the class
862 // path dex caches.
863 class_linker->ClearClassTableStrongRoots();
864
Brian Carlstrom7940e442013-07-12 13:46:57 -0700865 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700866 NonImageClassesVisitor visitor(this);
867 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700868
869 // Remove the undesired classes from the class roots.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800870 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800871 for (mirror::Class* klass : visitor.classes_to_prune_) {
872 std::string temp;
873 const char* name = klass->GetDescriptor(&temp);
874 VLOG(compiler) << "Pruning class " << name;
875 if (!compile_app_image_) {
876 DCHECK(IsBootClassLoaderClass(klass));
877 }
878 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800879 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700880 }
881
882 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100883 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700884
Mathieu Chartier268764d2016-09-13 12:09:38 -0700885 ScopedAssertNoThreadSuspension sa(__FUNCTION__);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700886 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
887 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800888 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800889 if (self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700890 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700891 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700892 ObjPtr<mirror::DexCache> dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700893 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800894 Class* klass = dex_cache->GetResolvedType(dex::TypeIndex(i));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800895 if (klass != nullptr && !KeepClass(klass)) {
Andreas Gampea5b09a62016-11-17 15:21:22 -0800896 dex_cache->SetResolvedType(dex::TypeIndex(i), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700897 }
898 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100899 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
900 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
901 ArtMethod* method =
902 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800903 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
904 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800905 // Copied methods may be held live by a class which was not an image class but have a
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800906 // declaring class which is an image class. Set it to the resolution method to be safe and
907 // prevent dangling pointers.
Alex Light36121492016-02-22 13:43:29 -0800908 if (method->IsCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800909 mirror::DexCache::SetElementPtrSize(resolved_methods,
910 i,
911 resolution_method,
912 target_ptr_size_);
913 } else {
914 // Check that the class is still in the classes table.
915 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
David Sehr709b0702016-10-13 09:12:37 -0700916 << Class::PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700917 }
918 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800919 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700920 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800921 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700922 if (field != nullptr && !KeepClass(field->GetDeclaringClass().Ptr())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700923 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700924 }
925 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700926 // Clean the dex field. It might have been populated during the initialization phase, but
927 // contains data only valid during a real run.
928 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700929 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700930
931 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
932 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800933
934 // Clear to save RAM.
935 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700936}
937
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800938void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700939 if (compiler_driver_.GetImageClasses() != nullptr) {
940 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700941 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700942 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700943}
944
945void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
946 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800947 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700948 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800949 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700950 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700951 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800952 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
David Sehr709b0702016-10-13 09:12:37 -0700953 << " " << klass->PrettyDescriptor();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700954 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700955 }
956}
957
958void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700959 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700960 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700961 for (const std::string& image_class : *image_classes) {
962 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700963 }
964}
965
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800966mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
967 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +0000968 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartier9e868092016-10-31 14:58:04 -0700969 ObjPtr<mirror::String> const found = image_info.intern_table_->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800970 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
971 << string->ToModifiedUtf8();
972 if (found != nullptr) {
Mathieu Chartier9e868092016-10-31 14:58:04 -0700973 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800974 }
975 }
976 if (compile_app_image_) {
977 Runtime* const runtime = Runtime::Current();
Mathieu Chartier9e868092016-10-31 14:58:04 -0700978 ObjPtr<mirror::String> found = runtime->GetInternTable()->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800979 // If we found it in the runtime intern table it could either be in the boot image or interned
980 // during app image compilation. If it was in the boot image return that, otherwise return null
981 // since it belongs to another image space.
Mathieu Chartier9e868092016-10-31 14:58:04 -0700982 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found.Ptr())) {
983 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800984 }
985 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
986 << string->ToModifiedUtf8();
987 }
988 return nullptr;
989}
990
Brian Carlstrom7940e442013-07-12 13:46:57 -0700991
Vladimir Marko944da602016-02-19 12:27:55 +0000992ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700993 Runtime* runtime = Runtime::Current();
994 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700995 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700996 StackHandleScope<3> hs(self);
997 Handle<Class> object_array_class(hs.NewHandle(
998 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700999
Jeff Haodcdc85b2015-12-04 14:06:18 -08001000 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +00001001 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001002 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +00001003 size_t image_oat_index = pair.second;
1004 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001005 image_dex_files.insert(image_dex_file);
1006 }
1007 }
1008
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001009 // build an Object[] of all the DexCaches used in the source_space_.
1010 // Since we can't hold the dex lock when allocating the dex_caches
1011 // ObjectArray, we lock the dex lock twice, first to get the number
1012 // of dex caches first and then lock it again to copy the dex
1013 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001014 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001015 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001016 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001017 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001018 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001019 ObjPtr<mirror::DexCache> dex_cache =
1020 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001021 if (dex_cache == nullptr) {
1022 continue;
1023 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001024 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001025 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001026 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1027 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001028 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001029 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001030 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001031 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001032 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1033 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001034 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001035 size_t non_image_dex_caches = 0;
1036 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001037 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001038 ObjPtr<mirror::DexCache> dex_cache =
1039 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001040 if (dex_cache == nullptr) {
1041 continue;
1042 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001043 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001044 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001045 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1046 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001047 }
1048 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1049 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001050 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001051 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001052 ObjPtr<mirror::DexCache> dex_cache =
1053 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001054 if (dex_cache == nullptr) {
1055 continue;
1056 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001057 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001058 if (!IsInBootImage(dex_cache.Ptr()) &&
1059 image_dex_files.find(dex_file) != image_dex_files.end()) {
1060 dex_caches->Set<false>(i, dex_cache.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001061 ++i;
1062 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001063 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001064 }
1065
1066 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001067 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001068 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001069 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001070 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001071 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001072 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001073 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001074 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001075}
1076
Mathieu Chartier496577f2016-09-20 15:33:31 -07001077mirror::Object* ImageWriter::TryAssignBinSlot(WorkStack& work_stack,
1078 mirror::Object* obj,
1079 size_t oat_index) {
1080 if (obj == nullptr || IsInBootImage(obj)) {
1081 // Object is null or already in the image, there is no work to do.
1082 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001083 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001084 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001085 // We want to intern all strings but also assign offsets for the source string. Since the
1086 // pruning phase has already happened, if we intern a string to one in the image we still
1087 // end up copying an unreachable string.
1088 if (obj->IsString()) {
1089 // Need to check if the string is already interned in another image info so that we don't have
1090 // the intern tables of two different images contain the same string.
1091 mirror::String* interned = FindInternedString(obj->AsString());
1092 if (interned == nullptr) {
1093 // Not in another image space, insert to our table.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001094 interned =
1095 GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString()).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001096 DCHECK_EQ(interned, obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001097 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001098 } else if (obj->IsDexCache()) {
1099 oat_index = GetOatIndexForDexCache(obj->AsDexCache());
1100 } else if (obj->IsClass()) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001101 // Visit and assign offsets for fields and field arrays.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001102 mirror::Class* as_klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001103 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001104 DCHECK_NE(as_klass->GetStatus(), mirror::Class::kStatusError);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001105 if (compile_app_image_) {
1106 // Extra sanity, no boot loader classes should be left!
David Sehr709b0702016-10-13 09:12:37 -07001107 CHECK(!IsBootClassLoaderClass(as_klass)) << as_klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001108 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001109 LengthPrefixedArray<ArtField>* fields[] = {
1110 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1111 };
Mathieu Chartier496577f2016-09-20 15:33:31 -07001112 // Overwrite the oat index value since the class' dex cache is more accurate of where it
1113 // belongs.
1114 oat_index = GetOatIndexForDexCache(dex_cache);
Vladimir Marko944da602016-02-19 12:27:55 +00001115 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001116 {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001117 // Note: This table is only accessed from the image writer, avoid locking to prevent lock
1118 // order violations from root visiting.
1119 image_info.class_table_->InsertWithoutLocks(as_klass);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001120 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001121 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1122 // Total array length including header.
1123 if (cur_fields != nullptr) {
1124 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1125 // Forward the entire array at once.
1126 auto it = native_object_relocations_.find(cur_fields);
1127 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1128 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001129 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001130 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001131 native_object_relocations_.emplace(
1132 cur_fields,
1133 NativeObjectRelocation {
1134 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1135 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001136 offset += header_size;
1137 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001138 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001139 // Need to forward arrays separate of fields.
1140 ArtField* field = &cur_fields->At(i);
1141 auto it2 = native_object_relocations_.find(field);
1142 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
David Sehr709b0702016-10-13 09:12:37 -07001143 << " already assigned " << field->PrettyField() << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001144 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001145 native_object_relocations_.emplace(
1146 field,
1147 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001148 offset += sizeof(ArtField);
1149 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001150 }
1151 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001152 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001153 size_t num_methods = as_klass->NumMethods();
1154 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001155 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001156 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1157 if (WillMethodBeDirty(&m)) {
1158 any_dirty = true;
1159 break;
1160 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001161 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001162 NativeObjectRelocationType type = any_dirty
1163 ? kNativeObjectRelocationTypeArtMethodDirty
1164 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001165 Bin bin_type = BinTypeForNativeRelocationType(type);
1166 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001167 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1168 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001169 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1170 method_size,
1171 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001172 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001173 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001174 CHECK(it == native_object_relocations_.end())
1175 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001176 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001177 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001178 native_object_relocations_.emplace(array,
1179 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001180 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001181 offset,
1182 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1183 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001184 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001185 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001186 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001187 }
Alex Lighte64300b2015-12-15 15:02:47 -08001188 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001189 }
1190 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1191 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001192 if (as_klass->ShouldHaveImt()) {
1193 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1194 for (size_t i = 0; i < ImTable::kSize; ++i) {
1195 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001196 DCHECK(imt_method != nullptr);
1197 if (imt_method->IsRuntimeMethod() &&
1198 !IsInBootImage(imt_method) &&
1199 !NativeRelocationAssigned(imt_method)) {
1200 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001201 }
1202 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001203 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001204
1205 if (as_klass->ShouldHaveImt()) {
1206 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1207 TryAssignImTableOffset(imt, oat_index);
1208 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001209 } else if (obj->IsClassLoader()) {
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001210 // Register the class loader if it has a class table.
1211 // The fake boot class loader should not get registered and we should end up with only one
1212 // class loader.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001213 mirror::ClassLoader* class_loader = obj->AsClassLoader();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001214 if (class_loader->GetClassTable() != nullptr) {
1215 class_loaders_.insert(class_loader);
1216 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001217 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001218 AssignImageBinSlot(obj, oat_index);
1219 work_stack.emplace(obj, oat_index);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001220 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001221 if (obj->IsString()) {
1222 // Always return the interned string if there exists one.
1223 mirror::String* interned = FindInternedString(obj->AsString());
1224 if (interned != nullptr) {
1225 return interned;
1226 }
1227 }
1228 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001229}
1230
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001231bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1232 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1233}
1234
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001235void ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
1236 // No offset, or already assigned.
1237 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
1238 return;
1239 }
1240 // If the method is a conflict method we also want to assign the conflict table offset.
1241 ImageInfo& image_info = GetImageInfo(oat_index);
1242 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1243 native_object_relocations_.emplace(
1244 imt,
1245 NativeObjectRelocation {
1246 oat_index,
1247 image_info.bin_slot_sizes_[kBinImTable],
1248 kNativeObjectRelocationTypeIMTable});
1249 image_info.bin_slot_sizes_[kBinImTable] += size;
1250}
1251
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001252void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1253 // No offset, or already assigned.
1254 if (table == nullptr || NativeRelocationAssigned(table)) {
1255 return;
1256 }
1257 CHECK(!IsInBootImage(table));
1258 // If the method is a conflict method we also want to assign the conflict table offset.
1259 ImageInfo& image_info = GetImageInfo(oat_index);
1260 const size_t size = table->ComputeSize(target_ptr_size_);
1261 native_object_relocations_.emplace(
1262 table,
1263 NativeObjectRelocation {
1264 oat_index,
1265 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1266 kNativeObjectRelocationTypeIMTConflictTable});
1267 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1268}
1269
Jeff Haodcdc85b2015-12-04 14:06:18 -08001270void ImageWriter::AssignMethodOffset(ArtMethod* method,
1271 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001272 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001273 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001274 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
David Sehr709b0702016-10-13 09:12:37 -07001275 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001276 if (method->IsRuntimeMethod()) {
1277 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1278 }
Vladimir Marko944da602016-02-19 12:27:55 +00001279 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001280 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001281 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001282 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001283}
1284
Mathieu Chartier496577f2016-09-20 15:33:31 -07001285void ImageWriter::EnsureBinSlotAssignedCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001286 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1287 DCHECK(writer != nullptr);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001288 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) {
David Sehr709b0702016-10-13 09:12:37 -07001289 CHECK(writer->IsImageBinSlotAssigned(obj)) << mirror::Object::PrettyTypeOf(obj) << " " << obj;
Mathieu Chartier496577f2016-09-20 15:33:31 -07001290 }
1291}
1292
1293void ImageWriter::DeflateMonitorCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED) {
1294 Monitor::Deflate(Thread::Current(), obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001295}
1296
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001297void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1298 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1299 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001300 if (!writer->IsInBootImage(obj)) {
1301 writer->UnbinObjectsIntoOffset(obj);
1302 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001303}
1304
1305void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001306 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001307 CHECK(obj != nullptr);
1308
1309 // We know the bin slot, and the total bin sizes for all objects by now,
1310 // so calculate the object's final image offset.
1311
1312 DCHECK(IsImageBinSlotAssigned(obj));
1313 BinSlot bin_slot = GetImageBinSlot(obj);
1314 // Change the lockword from a bin slot into an offset
1315 AssignImageOffset(obj, bin_slot);
1316}
1317
Mathieu Chartier496577f2016-09-20 15:33:31 -07001318class ImageWriter::VisitReferencesVisitor {
1319 public:
1320 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index)
1321 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {}
1322
1323 // Fix up separately since we also need to fix up method entrypoints.
1324 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1325 REQUIRES_SHARED(Locks::mutator_lock_) {
1326 if (!root->IsNull()) {
1327 VisitRoot(root);
1328 }
1329 }
1330
1331 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1332 REQUIRES_SHARED(Locks::mutator_lock_) {
1333 root->Assign(VisitReference(root->AsMirrorPtr()));
1334 }
1335
Mathieu Chartier31e88222016-10-14 18:43:19 -07001336 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
Mathieu Chartier496577f2016-09-20 15:33:31 -07001337 MemberOffset offset,
1338 bool is_static ATTRIBUTE_UNUSED) const
1339 REQUIRES_SHARED(Locks::mutator_lock_) {
1340 mirror::Object* ref =
1341 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1342 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1343 }
1344
Mathieu Chartier31e88222016-10-14 18:43:19 -07001345 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1346 ObjPtr<mirror::Reference> ref) const
Mathieu Chartier496577f2016-09-20 15:33:31 -07001347 REQUIRES_SHARED(Locks::mutator_lock_) {
1348 ref->SetReferent</*kTransactionActive*/false>(
1349 VisitReference(ref->GetReferent<kWithoutReadBarrier>()));
1350 }
1351
1352 private:
1353 mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1354 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_);
1355 }
1356
1357 ImageWriter* const image_writer_;
1358 WorkStack* const work_stack_;
1359 const size_t oat_index_;
1360};
1361
1362class ImageWriter::GetRootsVisitor : public RootVisitor {
1363 public:
1364 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {}
1365
1366 void VisitRoots(mirror::Object*** roots,
1367 size_t count,
1368 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1369 REQUIRES_SHARED(Locks::mutator_lock_) {
1370 for (size_t i = 0; i < count; ++i) {
1371 roots_->push_back(*roots[i]);
1372 }
1373 }
1374
1375 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1376 size_t count,
1377 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1378 REQUIRES_SHARED(Locks::mutator_lock_) {
1379 for (size_t i = 0; i < count; ++i) {
1380 roots_->push_back(roots[i]->AsMirrorPtr());
1381 }
1382 }
1383
1384 private:
1385 std::vector<mirror::Object*>* const roots_;
1386};
1387
1388void ImageWriter::ProcessWorkStack(WorkStack* work_stack) {
1389 while (!work_stack->empty()) {
1390 std::pair<mirror::Object*, size_t> pair(work_stack->top());
1391 work_stack->pop();
1392 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second);
1393 // Walk references and assign bin slots for them.
1394 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1395 visitor,
1396 visitor);
1397 }
1398}
1399
Vladimir Markof4da6752014-08-01 19:04:18 +01001400void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001401 Thread* const self = Thread::Current();
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07001402 VariableSizedHandleScope handles(self);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001403 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001404 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1405 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001406 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001407
Mathieu Chartier496577f2016-09-20 15:33:31 -07001408 Runtime* const runtime = Runtime::Current();
1409 gc::Heap* const heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001410
Mathieu Chartier31e89252013-08-28 11:29:12 -07001411 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001412 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001413 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001414
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001415 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001416 // Write the image runtime methods.
1417 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1418 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1419 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001420 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
1421 runtime->GetCalleeSaveMethod(Runtime::kSaveAllCalleeSaves);
1422 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
1423 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsOnly);
1424 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
1425 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001426 image_methods_[ImageHeader::kSaveEverythingMethod] =
1427 runtime->GetCalleeSaveMethod(Runtime::kSaveEverything);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001428 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001429 for (auto* m : image_methods_) {
1430 CHECK(m != nullptr);
1431 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001432 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1433 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001434 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001435 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001436 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001437
Mathieu Chartier496577f2016-09-20 15:33:31 -07001438 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
1439 // this lock while holding other locks may cause lock order violations.
1440 heap->VisitObjects(DeflateMonitorCallback, this);
1441
1442 // Work list of <object, oat_index> for objects. Everything on the stack must already be
1443 // assigned a bin slot.
1444 WorkStack work_stack;
1445
1446 // Special case interned strings to put them in the image they are likely to be resolved from.
1447 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
1448 auto it = dex_file_oat_index_map_.find(dex_file);
1449 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1450 const size_t oat_index = it->second;
1451 InternTable* const intern_table = runtime->GetInternTable();
1452 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
1453 uint32_t utf16_length;
1454 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(i, &utf16_length);
Mathieu Chartier9e868092016-10-31 14:58:04 -07001455 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001456 TryAssignBinSlot(work_stack, string, oat_index);
1457 }
1458 }
1459
1460 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor
1461 // visits roots while holding various locks.
1462 {
1463 std::vector<mirror::Object*> roots;
1464 GetRootsVisitor root_visitor(&roots);
1465 runtime->VisitRoots(&root_visitor);
1466 for (mirror::Object* obj : roots) {
1467 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex());
1468 }
1469 }
1470 ProcessWorkStack(&work_stack);
1471
1472 // For app images, there may be objects that are only held live by the by the boot image. One
1473 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback
1474 // does not fail any checks. TODO: We should probably avoid copying these objects.
1475 if (compile_app_image_) {
1476 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) {
1477 DCHECK(space->IsImageSpace());
1478 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1479 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1480 reinterpret_cast<uintptr_t>(space->Limit()),
1481 [this, &work_stack](mirror::Object* obj)
1482 REQUIRES_SHARED(Locks::mutator_lock_) {
1483 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex());
1484 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot).
1485 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1486 visitor,
1487 visitor);
1488 });
1489 }
1490 // Process the work stack in case anything was added by TryAssignBinSlot.
1491 ProcessWorkStack(&work_stack);
1492 }
1493
1494 // Verify that all objects have assigned image bin slots.
1495 heap->VisitObjects(EnsureBinSlotAssignedCallback, this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001496
Vladimir Marko05792b92015-08-03 11:56:49 +01001497 // Calculate size of the dex cache arrays slot and prepare offsets.
1498 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001499
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001500 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001501 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001502 // Calculate how big the intern table will be after being serialized.
1503 InternTable* const intern_table = image_info.intern_table_.get();
1504 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
Vladimir Marko1a1de672016-10-13 12:53:15 +01001505 if (intern_table->StrongSize() != 0u) {
1506 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1507 }
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001508 // Calculate the size of the class table.
1509 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko1a1de672016-10-13 12:53:15 +01001510 DCHECK_EQ(image_info.class_table_->NumZygoteClasses(), 0u);
1511 if (image_info.class_table_->NumNonZygoteClasses() != 0u) {
1512 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
1513 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001514 }
1515
Vladimir Markocf36d492015-08-12 19:27:26 +01001516 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001517 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001518 size_t bin_offset = image_objects_offset_begin_;
1519 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001520 switch (i) {
1521 case kBinArtMethodClean:
1522 case kBinArtMethodDirty: {
1523 bin_offset = RoundUp(bin_offset, method_alignment);
1524 break;
1525 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001526 case kBinDexCacheArray:
1527 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment());
1528 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001529 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001530 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001531 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001532 break;
1533 }
1534 default: {
1535 // Normal alignment.
1536 }
1537 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001538 image_info.bin_slot_offsets_[i] = bin_offset;
1539 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001540 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001541 // NOTE: There may be additional padding between the bin slots and the intern table.
1542 DCHECK_EQ(image_info.image_end_,
1543 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001544 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001545
Jeff Haodcdc85b2015-12-04 14:06:18 -08001546 // Calculate image offsets.
1547 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001548 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001549 image_info.image_begin_ = global_image_begin_ + image_offset;
1550 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001551 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001552 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001553 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001554 image_offset += image_info.image_size_;
1555 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001556
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001557 // Transform each object's bin slot into an offset which will be used to do the final copy.
1558 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001559
Jeff Haodcdc85b2015-12-04 14:06:18 -08001560 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001561
Jeff Haodcdc85b2015-12-04 14:06:18 -08001562 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001563 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001564 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1565 i++;
1566 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001567
Mathieu Chartiere401d142015-04-22 13:56:20 -07001568 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001569 for (auto& pair : native_object_relocations_) {
1570 NativeObjectRelocation& relocation = pair.second;
1571 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001572 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001573 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001574 }
1575
Jeff Haodcdc85b2015-12-04 14:06:18 -08001576 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001577}
1578
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001579size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001580 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001581
1582 // Do not round up any sections here that are represented by the bins since it will break
1583 // offsets.
1584
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001585 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001586 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001587 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001588
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001589 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001590 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1591 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001592 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001593
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001594 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001595 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1596 *methods_section = ImageSection(
1597 bin_slot_offsets_[kBinArtMethodClean],
1598 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1599
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001600 // IMT section.
1601 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1602 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1603
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001604 // Conflict tables section.
1605 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1606 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1607 bin_slot_sizes_[kBinIMTConflictTable]);
1608
1609 // Runtime methods section.
1610 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1611 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1612 bin_slot_sizes_[kBinRuntimeMethod]);
1613
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001614 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001615 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1616 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1617 bin_slot_sizes_[kBinDexCacheArray]);
1618
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001619 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001620 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001621 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001622 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001623 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1624 cur_pos = interned_strings_section->End();
1625 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1626 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1627 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001628 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001629 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001630 cur_pos = class_table_section->End();
1631 // Image end goes right before the start of the image bitmap.
1632 return cur_pos;
1633}
1634
Vladimir Marko944da602016-02-19 12:27:55 +00001635void ImageWriter::CreateHeader(size_t oat_index) {
1636 ImageInfo& image_info = GetImageInfo(oat_index);
1637 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1638 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1639 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001640
1641 // Create the image sections.
1642 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001643 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001644
Mathieu Chartiere401d142015-04-22 13:56:20 -07001645 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001646 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001647 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001648 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001649 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001650 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001651 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001652 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001653 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1654 ++idx;
1655 }
1656 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001657 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1658 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1659 << " Image offset=" << image_info.image_offset_ << std::dec;
1660 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1661 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1662 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1663 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001664 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001665 // Store boot image info for app image so that we can relocate.
1666 uint32_t boot_image_begin = 0;
1667 uint32_t boot_image_end = 0;
1668 uint32_t boot_oat_begin = 0;
1669 uint32_t boot_oat_end = 0;
1670 gc::Heap* const heap = Runtime::Current()->GetHeap();
1671 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001672
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001673 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1674 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001675 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1676 image_end,
1677 sections,
1678 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001679 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001680 PointerToLowMemUInt32(oat_file_begin),
1681 PointerToLowMemUInt32(image_info.oat_data_begin_),
1682 PointerToLowMemUInt32(oat_data_end),
1683 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001684 boot_image_begin,
1685 boot_image_end - boot_image_begin,
1686 boot_oat_begin,
1687 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001688 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001689 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001690 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001691 image_storage_mode_,
1692 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001693}
1694
1695ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001696 auto it = native_object_relocations_.find(method);
David Sehr709b0702016-10-13 09:12:37 -07001697 CHECK(it != native_object_relocations_.end()) << ArtMethod::PrettyMethod(method) << " @ "
1698 << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001699 size_t oat_index = GetOatIndex(method->GetDexCache());
1700 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001701 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1702 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001703}
1704
Vladimir Markoad06b982016-11-17 16:38:59 +00001705class ImageWriter::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001706 public:
1707 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1708 }
1709
1710 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001711 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001712 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001713 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001714 }
1715 }
1716
1717 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1718 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001719 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001720 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001721 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001722 }
1723 }
1724
1725 private:
1726 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001727};
1728
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001729void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
1730 for (size_t i = 0; i < ImTable::kSize; ++i) {
1731 ArtMethod* method = orig->Get(i, target_ptr_size_);
1732 copy->Set(i, NativeLocationInImage(method), target_ptr_size_);
1733 }
1734}
1735
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001736void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
1737 const size_t count = orig->NumEntries(target_ptr_size_);
1738 for (size_t i = 0; i < count; ++i) {
1739 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
1740 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
1741 copy->SetInterfaceMethod(i, target_ptr_size_, NativeLocationInImage(interface_method));
1742 copy->SetImplementationMethod(i,
1743 target_ptr_size_,
1744 NativeLocationInImage(implementation_method));
1745 }
1746}
1747
Vladimir Marko944da602016-02-19 12:27:55 +00001748void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001749 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001750 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001751 for (auto& pair : native_object_relocations_) {
1752 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001753 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001754 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001755 continue;
1756 }
1757 auto* dest = image_info.image_->Begin() + relocation.offset;
1758 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001759 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001760 switch (relocation.type) {
1761 case kNativeObjectRelocationTypeArtField: {
1762 memcpy(dest, pair.first, sizeof(ArtField));
1763 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001764 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass().Ptr()));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001765 break;
1766 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001767 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001768 case kNativeObjectRelocationTypeArtMethodClean:
1769 case kNativeObjectRelocationTypeArtMethodDirty: {
1770 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001771 reinterpret_cast<ArtMethod*>(dest),
1772 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001773 break;
1774 }
1775 // For arrays, copy just the header since the elements will get copied by their corresponding
1776 // relocations.
1777 case kNativeObjectRelocationTypeArtFieldArray: {
1778 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1779 break;
1780 }
1781 case kNativeObjectRelocationTypeArtMethodArrayClean:
1782 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00001783 size_t size = ArtMethod::Size(target_ptr_size_);
1784 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1785 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1786 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1787 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001788 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00001789 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001790 case kNativeObjectRelocationTypeDexCacheArray:
1791 // Nothing to copy here, everything is done in FixupDexCache().
1792 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001793 case kNativeObjectRelocationTypeIMTable: {
1794 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
1795 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
1796 CopyAndFixupImTable(orig_imt, dest_imt);
1797 break;
1798 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001799 case kNativeObjectRelocationTypeIMTConflictTable: {
1800 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
1801 CopyAndFixupImtConflictTable(
1802 orig_table,
1803 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
1804 break;
1805 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001806 }
1807 }
1808 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001809 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001810 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001811 ArtMethod* method = image_methods_[i];
1812 CHECK(method != nullptr);
1813 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001814 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001815 }
1816 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001817 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001818 FixupRootVisitor root_visitor(this);
1819
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001820 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001821 if (image_info.intern_table_bytes_ > 0) {
1822 const ImageSection& intern_table_section = image_header->GetImageSection(
1823 ImageHeader::kSectionInternedStrings);
1824 InternTable* const intern_table = image_info.intern_table_.get();
1825 uint8_t* const intern_table_memory_ptr =
1826 image_info.image_->Begin() + intern_table_section.Offset();
1827 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1828 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1829 // Fixup the pointers in the newly written intern table to contain image addresses.
1830 InternTable temp_intern_table;
1831 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1832 // the VisitRoots() will update the memory directly rather than the copies.
1833 // This also relies on visit roots not doing any verification which could fail after we update
1834 // the roots to be the image addresses.
1835 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1836 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1837 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1838 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001839 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1840 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001841 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001842 const ImageSection& class_table_section = image_header->GetImageSection(
1843 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001844 uint8_t* const class_table_memory_ptr =
1845 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001846 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001847
1848 ClassTable* table = image_info.class_table_.get();
1849 CHECK(table != nullptr);
1850 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1851 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1852 // Fixup the pointers in the newly written class table to contain image addresses. See
1853 // above comment for intern tables.
1854 ClassTable temp_class_table;
1855 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1856 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1857 table->NumZygoteClasses());
1858 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1859 RootInfo(kRootUnknown));
1860 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001861 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001862}
1863
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001864void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001865 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001866 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1867 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001868 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001869 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001870 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1871 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001872 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001873 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001874}
1875
Mathieu Chartier590fee92013-09-13 13:46:47 -07001876void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001877 DCHECK(obj != nullptr);
1878 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001879 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1880}
1881
Mathieu Chartiere401d142015-04-22 13:56:20 -07001882void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1883 mirror::Class* klass, Bin array_type) {
1884 CHECK(klass->IsArrayClass());
David Sehr709b0702016-10-13 09:12:37 -07001885 CHECK(arr->IsIntArray() || arr->IsLongArray()) << klass->PrettyClass() << " " << arr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001886 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001887 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001888 dst->SetClass(GetImageAddress(arr->GetClass()));
1889 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001890 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001891 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1892 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001893 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001894 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001895 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001896 auto* method = reinterpret_cast<ArtMethod*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07001897 LOG(FATAL) << "No relocation entry for ArtMethod " << method->PrettyMethod() << " @ "
1898 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1899 << Class::PrettyClass(method->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001900 } else {
1901 CHECK_EQ(array_type, kBinArtField);
1902 auto* field = reinterpret_cast<ArtField*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07001903 LOG(FATAL) << "No relocation entry for ArtField " << field->PrettyField() << " @ "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001904 << field << " idx=" << i << "/" << num_elements << " with declaring class "
David Sehr709b0702016-10-13 09:12:37 -07001905 << Class::PrettyClass(field->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001906 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001907 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001908 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001909 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001910 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001911 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001912 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001913 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001914 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001915}
1916
1917void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001918 if (IsInBootImage(obj)) {
1919 return;
1920 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001921 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001922 size_t oat_index = GetOatIndex(obj);
1923 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001924 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1925 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001926 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001927
Jeff Haodcdc85b2015-12-04 14:06:18 -08001928 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001929
1930 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001931 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001932 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001933
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001934 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1935 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001936 const auto it = saved_hashcode_map_.find(obj);
1937 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1938 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001939 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
1940 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
1941 // safe since we mark all of the objects that may reference non immune objects as gray.
1942 CHECK(dst->AtomicSetMarkBit(0, 1));
1943 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001944 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001945}
1946
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001947// Rewrite all the references in the copied object to point to their image address equivalent
Vladimir Markoad06b982016-11-17 16:38:59 +00001948class ImageWriter::FixupVisitor {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001949 public:
1950 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1951 }
1952
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001953 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1954 // with other logic.
1955 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1956 const {}
1957 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1958
1959
Mathieu Chartier31e88222016-10-14 18:43:19 -07001960 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001961 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07001962 ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001963 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1964 // image.
1965 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001966 offset,
Mathieu Chartier31e88222016-10-14 18:43:19 -07001967 image_writer_->GetImageAddress(ref.Ptr()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001968 }
1969
1970 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001971 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1972 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001973 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001974 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001975 mirror::Reference::ReferentOffset(),
1976 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001977 }
1978
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001979 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001980 ImageWriter* const image_writer_;
1981 mirror::Object* const copy_;
1982};
1983
Vladimir Markoad06b982016-11-17 16:38:59 +00001984class ImageWriter::FixupClassVisitor FINAL : public FixupVisitor {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001985 public:
1986 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1987 }
1988
Mathieu Chartier31e88222016-10-14 18:43:19 -07001989 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001990 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001991 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001992 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001993 }
1994
Mathieu Chartier31e88222016-10-14 18:43:19 -07001995 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1996 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001997 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001998 LOG(FATAL) << "Reference not expected here.";
1999 }
2000};
2001
Vladimir Marko05792b92015-08-03 11:56:49 +01002002uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
2003 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002004 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002005 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002006 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
2007 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002008 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01002009 return relocation.offset;
2010}
2011
2012template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002013std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002014 std::ostringstream oss;
2015 oss << ptr;
2016 return oss.str();
2017}
2018
2019template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002020std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07002021 return ArtMethod::PrettyMethod(method);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002022}
2023
2024template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002025T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002026 if (obj == nullptr || IsInBootImage(obj)) {
2027 return obj;
2028 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002029 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002030 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
2031 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002032 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00002033 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002034 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002035 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002036}
2037
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002038template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08002039T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
2040 if (obj == nullptr || IsInBootImage(obj)) {
2041 return obj;
2042 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002043 size_t oat_index = GetOatIndexForDexCache(dex_cache);
2044 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002045 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
2046 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002047}
2048
Vladimir Markoad06b982016-11-17 16:38:59 +00002049class ImageWriter::NativeLocationVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002050 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002051 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002052
2053 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002054 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002055 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002056 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002057
2058 private:
2059 ImageWriter* const image_writer_;
2060};
2061
2062void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002063 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002064 FixupClassVisitor visitor(this, copy);
Mathieu Chartier31e88222016-10-14 18:43:19 -07002065 ObjPtr<mirror::Object>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002066
2067 // Remove the clinitThreadId. This is required for image determinism.
2068 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002069}
2070
Ian Rogersef7d42f2014-01-06 12:55:46 -08002071void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002072 DCHECK(orig != nullptr);
2073 DCHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002074 if (kUseBakerReadBarrier) {
2075 orig->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002076 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002077 auto* klass = orig->GetClass();
2078 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002079 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07002080 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
2081 if (it != pointer_arrays_.end()) {
2082 // Should only need to fixup every pointer array exactly once.
2083 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
2084 pointer_arrays_.erase(it);
2085 return;
2086 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002087 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002088 if (orig->IsClass()) {
2089 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002090 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002091 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
2092 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01002093 auto* dest = down_cast<mirror::Executable*>(copy);
2094 auto* src = down_cast<mirror::Executable*>(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002095 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05002096 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01002097 } else if (!klass->IsArrayClass()) {
2098 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2099 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
2100 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002101 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002102 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002103 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2104 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002105 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002106 // Also set allocator to null to be safe. The allocator is created when we create the class
2107 // table. We also never expect to unload things in the image since they are held live as
2108 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002109 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002110 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002111 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002112 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002113 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002114 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002115}
2116
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002117
2118class ImageAddressVisitor {
2119 public:
2120 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
2121
2122 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002123 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002124 return image_writer_->GetImageAddress(ptr);
2125 }
2126
2127 private:
2128 ImageWriter* const image_writer_;
2129};
2130
2131
Vladimir Marko05792b92015-08-03 11:56:49 +01002132void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2133 mirror::DexCache* copy_dex_cache) {
2134 // Though the DexCache array fields are usually treated as native pointers, we set the full
2135 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2136 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2137 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002138 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002139 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002140 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002141 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002142 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002143 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
2144 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002145 }
2146 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
2147 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002148 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002149 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002150 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002151 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
2152 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002153 }
2154 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
2155 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002156 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002157 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002158 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002159 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002160 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
2161 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002162 // NativeLocationInImage also handles runtime methods since these have relocation info.
2163 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002164 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
2165 }
2166 }
2167 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
2168 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002169 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002170 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002171 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002172 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002173 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
2174 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002175 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002176 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
2177 }
2178 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01002179 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
2180 if (orig_method_types != nullptr) {
2181 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodTypesOffset(),
2182 NativeLocationInImage(orig_method_types),
2183 PointerSize::k64);
2184 orig_dex_cache->FixupResolvedMethodTypes(NativeCopyLocation(orig_method_types, orig_dex_cache),
2185 ImageAddressVisitor(this));
2186 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002187
2188 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2189 // compiler pointers in here will make the output non-deterministic.
2190 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002191}
2192
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002193const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2194 DCHECK_LT(type, kOatAddressCount);
2195 // If we are compiling an app image, we need to use the stubs of the boot image.
2196 if (compile_app_image_) {
2197 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002198 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002199 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2200 DCHECK(!image_spaces.empty());
2201 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002202 CHECK(oat_file != nullptr);
2203 const OatHeader& header = oat_file->GetOatHeader();
2204 switch (type) {
2205 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2206 case kOatAddressQuickGenericJNITrampoline:
2207 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2208 case kOatAddressInterpreterToInterpreterBridge:
2209 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2210 case kOatAddressInterpreterToCompiledCodeBridge:
2211 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2212 case kOatAddressJNIDlsymLookup:
2213 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2214 case kOatAddressQuickIMTConflictTrampoline:
2215 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2216 case kOatAddressQuickResolutionTrampoline:
2217 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2218 case kOatAddressQuickToInterpreterBridge:
2219 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2220 default:
2221 UNREACHABLE();
2222 }
2223 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002224 const ImageInfo& primary_image_info = GetImageInfo(0);
2225 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002226}
2227
Jeff Haodcdc85b2015-12-04 14:06:18 -08002228const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2229 const ImageInfo& image_info,
2230 bool* quick_is_interpreted) {
David Sehr709b0702016-10-13 09:12:37 -07002231 DCHECK(!method->IsResolutionMethod()) << method->PrettyMethod();
2232 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << method->PrettyMethod();
2233 DCHECK(!method->IsImtUnimplementedMethod()) << method->PrettyMethod();
2234 DCHECK(method->IsInvokable()) << method->PrettyMethod();
2235 DCHECK(!IsInBootImage(method)) << method->PrettyMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002236
2237 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2238 // trampoline.
2239
2240 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002241 const void* quick_oat_entry_point =
2242 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2243 const uint8_t* quick_code;
2244
2245 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2246 DCHECK(method->IsCopied());
2247 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2248 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2249 } else {
2250 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2251 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2252 }
2253
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002254 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002255 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2256 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002257 // We have code for a non-static or initialized method, just use the code.
2258 } else if (quick_code == nullptr && method->IsNative() &&
2259 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2260 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002261 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002262 } else if (quick_code == nullptr && !method->IsNative()) {
2263 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002264 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002265 *quick_is_interpreted = true;
2266 } else {
2267 CHECK(!method->GetDeclaringClass()->IsInitialized());
2268 // We have code for a static method, but need to go through the resolution stub for class
2269 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002270 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2271 }
2272 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002273 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002274 }
2275 return quick_code;
2276}
2277
Jeff Haodcdc85b2015-12-04 14:06:18 -08002278void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2279 ArtMethod* copy,
2280 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002281 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002282
2283 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002284 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002285 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002286 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002287 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002288
Ian Rogers848871b2013-08-05 10:56:33 -07002289 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2290 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002291
Ian Rogers848871b2013-08-05 10:56:33 -07002292 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002293 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002294 if (orig->IsRuntimeMethod()) {
2295 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2296 if (orig_table != nullptr) {
2297 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2298 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2299 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2300 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2301 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2302 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2303 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2304 } else {
2305 bool found_one = false;
2306 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2307 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2308 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2309 found_one = true;
2310 break;
2311 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002312 }
David Sehr709b0702016-10-13 09:12:37 -07002313 CHECK(found_one) << "Expected to find callee save method but got " << orig->PrettyMethod();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002314 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002315 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002316 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002317 // We assume all methods have code. If they don't currently then we set them to the use the
2318 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2319 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002320 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002321 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002322 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002323 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002324 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002325 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002326 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002327
Sebastien Hertze1d07812014-05-21 15:44:09 +02002328 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002329 if (orig->IsNative()) {
2330 // The native method's pointer is set to a stub to lookup via dlsym.
2331 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002332 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002333 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002334 }
2335 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002336 }
2337}
2338
Jeff Haodcdc85b2015-12-04 14:06:18 -08002339size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002340 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002341 return std::accumulate(&image_info.bin_slot_sizes_[0],
2342 &image_info.bin_slot_sizes_[up_to],
2343 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002344}
2345
2346ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2347 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002348 static_assert(kBinBits == 3, "wrong number of bin bits");
2349 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002350 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2351
2352 DCHECK_LT(GetBin(), kBinSize);
2353 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2354}
2355
2356ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2357 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2358 DCHECK_EQ(index, GetIndex());
2359}
2360
2361ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2362 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2363}
2364
2365uint32_t ImageWriter::BinSlot::GetIndex() const {
2366 return lockword_ & ~kBinMask;
2367}
2368
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002369ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2370 switch (type) {
2371 case kNativeObjectRelocationTypeArtField:
2372 case kNativeObjectRelocationTypeArtFieldArray:
2373 return kBinArtField;
2374 case kNativeObjectRelocationTypeArtMethodClean:
2375 case kNativeObjectRelocationTypeArtMethodArrayClean:
2376 return kBinArtMethodClean;
2377 case kNativeObjectRelocationTypeArtMethodDirty:
2378 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2379 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002380 case kNativeObjectRelocationTypeDexCacheArray:
2381 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002382 case kNativeObjectRelocationTypeRuntimeMethod:
2383 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002384 case kNativeObjectRelocationTypeIMTable:
2385 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002386 case kNativeObjectRelocationTypeIMTConflictTable:
2387 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002388 }
2389 UNREACHABLE();
2390}
2391
Vladimir Marko944da602016-02-19 12:27:55 +00002392size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002393 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002394 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002395 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002396 auto it = oat_index_map_.find(obj);
2397 DCHECK(it != oat_index_map_.end());
2398 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002399}
2400
Vladimir Marko944da602016-02-19 12:27:55 +00002401size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002402 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002403 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002404 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002405 auto it = dex_file_oat_index_map_.find(dex_file);
2406 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2407 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002408}
2409
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002410size_t ImageWriter::GetOatIndexForDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
2411 return (dex_cache == nullptr)
2412 ? GetDefaultOatIndex()
2413 : GetOatIndexForDexFile(dex_cache->GetDexFile());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002414}
2415
Vladimir Marko944da602016-02-19 12:27:55 +00002416void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2417 size_t oat_loaded_size,
2418 size_t oat_data_offset,
2419 size_t oat_data_size) {
2420 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2421 for (const ImageInfo& info : image_infos_) {
2422 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2423 }
2424 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002425
Vladimir Marko944da602016-02-19 12:27:55 +00002426 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2427 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2428 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2429 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2430 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002431
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002432 if (compile_app_image_) {
2433 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2434 return;
2435 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002436
2437 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002438 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002439 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002440 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002441 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2442 }
2443}
2444
Vladimir Marko944da602016-02-19 12:27:55 +00002445void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2446 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2447 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2448
2449 if (oat_index == GetDefaultOatIndex()) {
2450 // Primary oat file, read the trampolines.
2451 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2452 oat_header.GetInterpreterToInterpreterBridgeOffset();
2453 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2454 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2455 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2456 oat_header.GetJniDlsymLookupOffset();
2457 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2458 oat_header.GetQuickGenericJniTrampolineOffset();
2459 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2460 oat_header.GetQuickImtConflictTrampolineOffset();
2461 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2462 oat_header.GetQuickResolutionTrampolineOffset();
2463 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2464 oat_header.GetQuickToInterpreterBridgeOffset();
2465 }
2466}
2467
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002468ImageWriter::ImageWriter(
2469 const CompilerDriver& compiler_driver,
2470 uintptr_t image_begin,
2471 bool compile_pic,
2472 bool compile_app_image,
2473 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002474 const std::vector<const char*>& oat_filenames,
2475 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002476 : compiler_driver_(compiler_driver),
2477 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2478 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002479 compile_pic_(compile_pic),
2480 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002481 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002482 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002483 dirty_methods_(0u),
2484 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002485 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002486 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002487 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002488 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002489 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002490 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2491 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002492}
2493
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002494ImageWriter::ImageInfo::ImageInfo()
2495 : intern_table_(new InternTable),
2496 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002497
Brian Carlstrom7940e442013-07-12 13:46:57 -07002498} // namespace art