blob: ad881b72f0e796f2b0329e07125533e99a026bbb [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"
35#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070036#include "elf_file.h"
37#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "elf_writer.h"
39#include "gc/accounting/card_table-inl.h"
40#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070041#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier36a270a2016-07-28 18:08:51 -070042#include "gc/collector/concurrent_copying.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070043#include "gc/heap.h"
44#include "gc/space/large_object_space.h"
45#include "gc/space/space-inl.h"
46#include "globals.h"
47#include "image.h"
48#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070049#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070050#include "lock_word.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "mirror/array-inl.h"
52#include "mirror/class-inl.h"
53#include "mirror/class_loader.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070054#include "mirror/dex_cache.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "mirror/dex_cache-inl.h"
Neil Fuller0e844392016-09-08 13:43:31 +010056#include "mirror/executable.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070057#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "mirror/object-inl.h"
59#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070060#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "oat.h"
62#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070063#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "runtime.h"
65#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070066#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000067#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070069using ::art::mirror::Class;
70using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070071using ::art::mirror::Object;
72using ::art::mirror::ObjectArray;
73using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070074
75namespace art {
76
Igor Murashkinf5b4c502014-11-14 15:01:59 -080077// Separate objects into multiple bins to optimize dirty memory use.
78static constexpr bool kBinObjects = true;
79
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080080// Return true if an object is already in an image space.
81bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080082 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080083 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080084 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080085 return false;
86 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080087 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
88 const uint8_t* image_begin = boot_image_space->Begin();
89 // Real image end including ArtMethods and ArtField sections.
90 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
91 if (image_begin <= obj && obj < image_end) {
92 return true;
93 }
94 }
95 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080096}
97
98bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080099 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800100 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800101 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800102 return false;
103 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800104 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
105 const ImageHeader& image_header = boot_image_space->GetImageHeader();
106 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
107 return true;
108 }
109 }
110 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800111}
112
Andreas Gampedd9d0552015-03-09 12:57:41 -0700113static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700114 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700115 Class* klass = obj->GetClass();
116 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
117}
118
119static void CheckNoDexObjects() {
120 ScopedObjectAccess soa(Thread::Current());
121 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
122}
123
Vladimir Markof4da6752014-08-01 19:04:18 +0100124bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800125 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800126 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100127 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700128 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100129 PruneNonImageClasses(); // Remove junk
Mathieu Chartier901e0702016-02-19 13:42:48 -0800130 if (!compile_app_image_) {
131 // Avoid for app image since this may increase RAM and image size.
132 ComputeLazyFieldsForImageClasses(); // Add useful information
133 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100134 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100135 heap->CollectGarbage(false); // Remove garbage.
136
Andreas Gampedd9d0552015-03-09 12:57:41 -0700137 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
138 // dex files.
139 //
140 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
141 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
142 // true.
143 if (kIsDebugBuild) {
144 CheckNoDexObjects();
145 }
146
Vladimir Markof4da6752014-08-01 19:04:18 +0100147 if (kIsDebugBuild) {
148 ScopedObjectAccess soa(Thread::Current());
149 CheckNonImageClassesRemoved();
150 }
151
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700152 {
153 ScopedObjectAccess soa(Thread::Current());
154 CalculateNewObjectOffsets();
155 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100156
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700157 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
158 // bin size sums being calculated.
159 if (!AllocMemory()) {
160 return false;
161 }
162
Vladimir Markof4da6752014-08-01 19:04:18 +0100163 return true;
164}
165
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700166bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800167 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000168 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800169 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
170 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800171 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800172 if (image_fd != kInvalidFd) {
173 CHECK_EQ(image_filenames.size(), 1u);
174 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800175 CHECK(!oat_filenames.empty());
176 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700177
Vladimir Marko944da602016-02-19 12:27:55 +0000178 {
179 ScopedObjectAccess soa(Thread::Current());
180 for (size_t i = 0; i < oat_filenames.size(); ++i) {
181 CreateHeader(i);
182 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800183 }
184 }
Alex Light53cb16b2014-06-12 11:26:29 -0700185
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700186 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700187 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800188 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700189 Runtime::Current()->GetHeap()->DisableObjectValidation();
190 CopyAndFixupObjects();
191 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700192
Jeff Haodcdc85b2015-12-04 14:06:18 -0800193 for (size_t i = 0; i < image_filenames.size(); ++i) {
194 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000195 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800196 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800197 if (image_fd != kInvalidFd) {
198 if (strlen(image_filename) == 0u) {
199 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800200 // Empty the file in case it already exists.
201 if (image_file != nullptr) {
202 TEMP_FAILURE_RETRY(image_file->SetLength(0));
203 TEMP_FAILURE_RETRY(image_file->Flush());
204 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800205 } else {
206 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
207 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800208 } else {
209 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800210 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800211
Jeff Haodcdc85b2015-12-04 14:06:18 -0800212 if (image_file == nullptr) {
213 LOG(ERROR) << "Failed to open image file " << image_filename;
214 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800215 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800216
217 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800218 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
219 image_file->Erase();
220 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800221 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800222
Jeff Haodcdc85b2015-12-04 14:06:18 -0800223 std::unique_ptr<char[]> compressed_data;
224 // Image data size excludes the bitmap and the header.
225 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
226 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
227 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
228 size_t data_size;
229 const char* image_data_to_write;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800230 const uint64_t compress_start_time = NanoTime();
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000231
Jeff Haodcdc85b2015-12-04 14:06:18 -0800232 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
233 switch (image_storage_mode_) {
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700234 case ImageHeader::kStorageModeLZ4HC: // Fall-through.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800235 case ImageHeader::kStorageModeLZ4: {
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800236 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800237 compressed_data.reset(new char[compressed_max_size]);
238 data_size = LZ4_compress(
239 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
240 &compressed_data[0],
241 image_data_size);
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800242
243 break;
244 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700245 /*
246 * Disabled due to image_test64 flakyness. Both use same decompression. b/27560444
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800247 case ImageHeader::kStorageModeLZ4HC: {
248 // Bound is same as non HC.
249 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
250 compressed_data.reset(new char[compressed_max_size]);
251 data_size = LZ4_compressHC(
252 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
253 &compressed_data[0],
254 image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800255 break;
256 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700257 */
Jeff Haodcdc85b2015-12-04 14:06:18 -0800258 case ImageHeader::kStorageModeUncompressed: {
259 data_size = image_data_size;
260 image_data_to_write = image_data;
261 break;
262 }
263 default: {
264 LOG(FATAL) << "Unsupported";
265 UNREACHABLE();
266 }
267 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800268
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800269 if (compressed_data != nullptr) {
270 image_data_to_write = &compressed_data[0];
271 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
272 << PrettyDuration(NanoTime() - compress_start_time);
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700273 if (kIsDebugBuild) {
274 std::unique_ptr<uint8_t[]> temp(new uint8_t[image_data_size]);
275 const size_t decompressed_size = LZ4_decompress_safe(
276 reinterpret_cast<char*>(&compressed_data[0]),
277 reinterpret_cast<char*>(&temp[0]),
278 data_size,
279 image_data_size);
280 CHECK_EQ(decompressed_size, image_data_size);
281 CHECK_EQ(memcmp(image_data, &temp[0], image_data_size), 0) << image_storage_mode_;
282 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800283 }
284
Jeff Haodcdc85b2015-12-04 14:06:18 -0800285 // Write out the image + fields + methods.
286 const bool is_compressed = compressed_data != nullptr;
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800287 if (!image_file->PwriteFully(image_data_to_write, data_size, sizeof(ImageHeader))) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800288 PLOG(ERROR) << "Failed to write image file data " << image_filename;
289 image_file->Erase();
290 return false;
291 }
292
293 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
294 // convenience.
295 const ImageSection& bitmap_section = image_header->GetImageSection(
296 ImageHeader::kSectionImageBitmap);
297 // Align up since data size may be unaligned if the image is compressed.
298 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
299 if (!is_compressed) {
300 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
301 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800302 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
303 bitmap_section.Size(),
304 bitmap_position_in_file)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800305 PLOG(ERROR) << "Failed to write image file " << image_filename;
306 image_file->Erase();
307 return false;
308 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800309
310 int err = image_file->Flush();
311 if (err < 0) {
312 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
313 image_file->Erase();
314 return false;
315 }
316
317 // Write header last in case the compiler gets killed in the middle of image writing.
318 // We do not want to have a corrupted image with a valid header.
319 // The header is uncompressed since it contains whether the image is compressed or not.
320 image_header->data_size_ = data_size;
321 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
322 sizeof(ImageHeader),
323 0)) {
324 PLOG(ERROR) << "Failed to write image file header " << image_filename;
325 image_file->Erase();
326 return false;
327 }
328
Jeff Haodcdc85b2015-12-04 14:06:18 -0800329 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
330 static_cast<size_t>(image_file->GetLength()));
331 if (image_file->FlushCloseOrErase() != 0) {
332 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
333 return false;
334 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800335 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700336 return true;
337}
338
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700339void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700340 DCHECK(object != nullptr);
341 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800342
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800343 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700344 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700345 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700346 DCHECK(IsImageOffsetAssigned(object));
347}
348
Mathieu Chartiere401d142015-04-22 13:56:20 -0700349void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
350 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
351 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
352 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
353}
354
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800355void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700356 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800357 DCHECK_NE(image_objects_offset_begin_, 0u);
358
Vladimir Marko944da602016-02-19 12:27:55 +0000359 size_t oat_index = GetOatIndex(object);
360 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800361 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100362 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800363 DCHECK_ALIGNED(new_offset, kObjectAlignment);
364
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700365 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800366 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700367}
368
Ian Rogersef7d42f2014-01-06 12:55:46 -0800369bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800370 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700371 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700372 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700373}
374
Ian Rogersef7d42f2014-01-06 12:55:46 -0800375size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700376 DCHECK(object != nullptr);
377 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700378 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700379 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000380 size_t oat_index = GetOatIndex(object);
381 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800382 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700383 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700384}
385
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800386void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
387 DCHECK(object != nullptr);
388 DCHECK(!IsImageOffsetAssigned(object));
389 DCHECK(!IsImageBinSlotAssigned(object));
390
391 // Before we stomp over the lock word, save the hash code for later.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800392 LockWord lw(object->GetLockWord(false));
393 switch (lw.GetState()) {
394 case LockWord::kFatLocked: {
395 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
396 break;
397 }
398 case LockWord::kThinLocked: {
399 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
400 break;
401 }
402 case LockWord::kUnlocked:
403 // No hash, don't need to save it.
404 break;
405 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700406 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
407 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800408 break;
409 default:
410 LOG(FATAL) << "Unreachable.";
411 UNREACHABLE();
412 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700413 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700414 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800415 DCHECK(IsImageBinSlotAssigned(object));
416}
417
Vladimir Marko20f85592015-03-19 10:07:02 +0000418void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000419 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000420 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
421 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800422 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000423 auto it = dex_file_oat_index_map_.find(dex_file);
424 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800425 ImageInfo& image_info = GetImageInfo(it->second);
426 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
427 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
428 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
429 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000430
Vladimir Marko20f85592015-03-19 10:07:02 +0000431 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700432 Thread* const self = Thread::Current();
433 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800434 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700435 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800436 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800437 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700438 continue;
439 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000440 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartier0b490842016-05-25 15:05:59 -0700441 CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
442 << "Dex cache should have been pruned " << dex_file->GetLocation()
443 << "; possibly in class path";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700444 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000445 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000446 size_t oat_index = GetOatIndexForDexCache(dex_cache);
447 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800448 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100449 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800450 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
451 start + layout.TypesOffset(),
452 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100453 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800454 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
455 start + layout.MethodsOffset(),
456 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100457 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800458 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
459 start + layout.FieldsOffset(),
460 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100461 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800462 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000463 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000464}
465
Jeff Haodcdc85b2015-12-04 14:06:18 -0800466void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100467 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800468 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000469 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800470 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000471 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100472 }
473}
474
Mathieu Chartiere401d142015-04-22 13:56:20 -0700475void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
476 DCHECK(arr != nullptr);
477 if (kIsDebugBuild) {
478 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800479 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700480 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800481 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800482 CHECK(klass == nullptr || KeepClass(klass))
483 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700484 }
485 }
486 }
487 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
488 // ArtMethods.
489 pointer_arrays_.emplace(arr, kBinArtMethodClean);
490}
491
Mathieu Chartier496577f2016-09-20 15:33:31 -0700492void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800493 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800494 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800495
496 // The magic happens here. We segregate objects into different bins based
497 // on how likely they are to get dirty at runtime.
498 //
499 // Likely-to-dirty objects get packed together into the same bin so that
500 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
501 // maximized.
502 //
503 // This means more pages will stay either clean or shared dirty (with zygote) and
504 // the app will use less of its own (private) memory.
505 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000506 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800507
508 if (kBinObjects) {
509 //
510 // Changing the bin of an object is purely a memory-use tuning.
511 // It has no change on runtime correctness.
512 //
513 // Memory analysis has determined that the following types of objects get dirtied
514 // the most:
515 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000516 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
517 // a fixed layout which helps improve generated code (using PC-relative addressing),
518 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
519 // Since these arrays are huge, most pages do not overlap other objects and it's not
520 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100521 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800522 // * Class'es which are verified [their clinit runs only at runtime]
523 // - classes in general [because their static fields get overwritten]
524 // - initialized classes with all-final statics are unlikely to be ever dirty,
525 // so bin them separately
526 // * Art Methods that are:
527 // - native [their native entry point is not looked up until runtime]
528 // - have declaring classes that aren't initialized
529 // [their interpreter/quick entry points are trampolines until the class
530 // becomes initialized]
531 //
532 // We also assume the following objects get dirtied either never or extremely rarely:
533 // * Strings (they are immutable)
534 // * Art methods that aren't native and have initialized declared classes
535 //
536 // We assume that "regular" bin objects are highly unlikely to become dirtied,
537 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
538 //
539 if (object->IsClass()) {
540 bin = kBinClassVerified;
541 mirror::Class* klass = object->AsClass();
542
Mathieu Chartiere401d142015-04-22 13:56:20 -0700543 // Add non-embedded vtable to the pointer array table if there is one.
544 auto* vtable = klass->GetVTable();
545 if (vtable != nullptr) {
546 AddMethodPointerArray(vtable);
547 }
548 auto* iftable = klass->GetIfTable();
549 if (iftable != nullptr) {
550 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
551 if (iftable->GetMethodArrayCount(i) > 0) {
552 AddMethodPointerArray(iftable->GetMethodArray(i));
553 }
554 }
555 }
556
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800557 if (klass->GetStatus() == Class::kStatusInitialized) {
558 bin = kBinClassInitialized;
559
560 // If the class's static fields are all final, put it into a separate bin
561 // since it's very likely it will stay clean.
562 uint32_t num_static_fields = klass->NumStaticFields();
563 if (num_static_fields == 0) {
564 bin = kBinClassInitializedFinalStatics;
565 } else {
566 // Maybe all the statics are final?
567 bool all_final = true;
568 for (uint32_t i = 0; i < num_static_fields; ++i) {
569 ArtField* field = klass->GetStaticField(i);
570 if (!field->IsFinal()) {
571 all_final = false;
572 break;
573 }
574 }
575
576 if (all_final) {
577 bin = kBinClassInitializedFinalStatics;
578 }
579 }
580 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800581 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
582 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700583 } else if (object->GetClass<kVerifyNone>() ==
584 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
585 // Instance of java lang object, probably a lock object. This means it will be dirty when we
586 // synchronize on it.
587 bin = kBinMiscDirty;
588 } else if (object->IsDexCache()) {
589 // Dex file field becomes dirty when the image is loaded.
590 bin = kBinMiscDirty;
591 }
592 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800593 }
594
Mathieu Chartier496577f2016-09-20 15:33:31 -0700595 // Assign the oat index too.
596 DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
597 oat_index_map_.emplace(object, oat_index);
598
Vladimir Marko944da602016-02-19 12:27:55 +0000599 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800600
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800601 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800602 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
603 // Move the current bin size up to accommodate the object we just assigned a bin slot.
604 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800605
606 BinSlot new_bin_slot(bin, current_offset);
607 SetImageBinSlot(object, new_bin_slot);
608
Jeff Haodcdc85b2015-12-04 14:06:18 -0800609 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800610
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800611 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800612 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800613}
614
Mathieu Chartiere401d142015-04-22 13:56:20 -0700615bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
616 if (m->IsNative()) {
617 return true;
618 }
619 mirror::Class* declaring_class = m->GetDeclaringClass();
620 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
621 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
622}
623
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800624bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
625 DCHECK(object != nullptr);
626
627 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
628 // If it's in some other state, then we haven't yet assigned an image bin slot.
629 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
630 return false;
631 } else if (kIsDebugBuild) {
632 LockWord lock_word = object->GetLockWord(false);
633 size_t offset = lock_word.ForwardingAddress();
634 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000635 size_t oat_index = GetOatIndex(object);
636 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800637 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800638 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800639 }
640 return true;
641}
642
643ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
644 DCHECK(object != nullptr);
645 DCHECK(IsImageBinSlotAssigned(object));
646
647 LockWord lock_word = object->GetLockWord(false);
648 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
649 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
650
651 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000652 size_t oat_index = GetOatIndex(object);
653 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800654 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800655
656 return bin_slot;
657}
658
Brian Carlstrom7940e442013-07-12 13:46:57 -0700659bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000660 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800661 ImageSection unused_sections[ImageHeader::kSectionCount];
662 const size_t length = RoundUp(
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700663 image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800664
Jeff Haodcdc85b2015-12-04 14:06:18 -0800665 std::string error_msg;
666 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
667 nullptr,
668 length,
669 PROT_READ | PROT_WRITE,
670 false,
671 false,
672 &error_msg));
673 if (UNLIKELY(image_info.image_.get() == nullptr)) {
674 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
675 return false;
676 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700677
Jeff Haodcdc85b2015-12-04 14:06:18 -0800678 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
679 CHECK_LE(image_info.image_end_, length);
680 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
681 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
682 if (image_info.image_bitmap_.get() == nullptr) {
683 LOG(ERROR) << "Failed to allocate memory for image bitmap";
684 return false;
685 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700686 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700687 return true;
688}
689
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700690class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
691 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700692 bool operator()(Class* c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700693 StackHandleScope<1> hs(Thread::Current());
694 mirror::Class::ComputeName(hs.NewHandle(c));
695 return true;
696 }
697};
698
Brian Carlstrom7940e442013-07-12 13:46:57 -0700699void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700700 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700701 ComputeLazyFieldsForClassesVisitor visitor;
702 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700703}
704
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700705static bool IsBootClassLoaderClass(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800706 return klass->GetClassLoader() == nullptr;
707}
708
709bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
710 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
711}
712
Mathieu Chartier901e0702016-02-19 13:42:48 -0800713bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800714 bool early_exit = false;
715 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800716 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800717}
718
Mathieu Chartier901e0702016-02-19 13:42:48 -0800719bool ImageWriter::PruneAppImageClassInternal(
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800720 mirror::Class* klass,
721 bool* early_exit,
722 std::unordered_set<mirror::Class*>* visited) {
723 DCHECK(early_exit != nullptr);
724 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800725 DCHECK(compile_app_image_);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800726 if (klass == nullptr || IsInBootImage(klass)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700727 return false;
728 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800729 auto found = prune_class_memo_.find(klass);
730 if (found != prune_class_memo_.end()) {
731 // Already computed, return the found value.
732 return found->second;
733 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800734 // Circular dependencies, return false but do not store the result in the memoization table.
735 if (visited->find(klass) != visited->end()) {
736 *early_exit = true;
737 return false;
738 }
739 visited->emplace(klass);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800740 bool result = IsBootClassLoaderClass(klass);
741 std::string temp;
742 // Prune if not an image class, this handles any broken sets of image classes such as having a
743 // class in the set but not it's superclass.
744 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800745 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800746 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
747 // app image.
748 if (klass->GetStatus() == mirror::Class::kStatusError) {
749 result = true;
750 } else {
751 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
752 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800753 if (!result) {
754 // Check interfaces since these wont be visited through VisitReferences.)
755 mirror::IfTable* if_table = klass->GetIfTable();
756 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800757 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
758 &my_early_exit,
759 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800760 }
761 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800762 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800763 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
764 &my_early_exit,
765 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800766 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800767 // Check static fields and their classes.
768 size_t num_static_fields = klass->NumReferenceStaticFields();
769 if (num_static_fields != 0 && klass->IsResolved()) {
770 // Presumably GC can happen when we are cross compiling, it should not cause performance
771 // problems to do pointer size logic.
772 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
773 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
774 for (size_t i = 0u; i < num_static_fields; ++i) {
775 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
776 if (ref != nullptr) {
777 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800778 result = result || PruneAppImageClassInternal(ref->AsClass(),
779 &my_early_exit,
780 visited);
781 } else {
782 result = result || PruneAppImageClassInternal(ref->GetClass(),
783 &my_early_exit,
784 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800785 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800786 }
787 field_offset = MemberOffset(field_offset.Uint32Value() +
788 sizeof(mirror::HeapReference<mirror::Object>));
789 }
790 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800791 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
792 &my_early_exit,
793 visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800794 // Erase the element we stored earlier since we are exiting the function.
795 auto it = visited->find(klass);
796 DCHECK(it != visited->end());
797 visited->erase(it);
798 // Only store result if it is true or none of the calls early exited due to circular
799 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
800 // a child call and we can remember the result.
801 if (result == true || !my_early_exit || visited->empty()) {
802 prune_class_memo_[klass] = result;
803 }
804 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800805 return result;
806}
807
808bool ImageWriter::KeepClass(Class* klass) {
809 if (klass == nullptr) {
810 return false;
811 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800812 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
813 // Already in boot image, return true.
814 return true;
815 }
816 std::string temp;
817 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
818 return false;
819 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800820 if (compile_app_image_) {
821 // For app images, we need to prune boot loader classes that are not in the boot image since
822 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800823 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800824 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800825 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800826 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700827}
828
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700829class NonImageClassesVisitor : public ClassVisitor {
830 public:
831 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
832
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700833 bool operator()(Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800834 if (!image_writer_->KeepClass(klass)) {
835 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700836 }
837 return true;
838 }
839
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800840 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700841 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700842};
843
844void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700845 Runtime* runtime = Runtime::Current();
846 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700847 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700848
Mathieu Chartier696632e2016-06-03 17:47:32 -0700849 // Clear class table strong roots so that dex caches can get pruned. We require pruning the class
850 // path dex caches.
851 class_linker->ClearClassTableStrongRoots();
852
Brian Carlstrom7940e442013-07-12 13:46:57 -0700853 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700854 NonImageClassesVisitor visitor(this);
855 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700856
857 // Remove the undesired classes from the class roots.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800858 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800859 for (mirror::Class* klass : visitor.classes_to_prune_) {
860 std::string temp;
861 const char* name = klass->GetDescriptor(&temp);
862 VLOG(compiler) << "Pruning class " << name;
863 if (!compile_app_image_) {
864 DCHECK(IsBootClassLoaderClass(klass));
865 }
866 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800867 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700868 }
869
870 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100871 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700872
Mathieu Chartier268764d2016-09-13 12:09:38 -0700873 ScopedAssertNoThreadSuspension sa(__FUNCTION__);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700874 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
875 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800876 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800877 if (self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700878 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700879 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800880 mirror::DexCache* dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700881 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
882 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800883 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700884 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700885 }
886 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100887 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
888 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
889 ArtMethod* method =
890 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800891 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
892 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800893 // 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 -0800894 // declaring class which is an image class. Set it to the resolution method to be safe and
895 // prevent dangling pointers.
Alex Light36121492016-02-22 13:43:29 -0800896 if (method->IsCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800897 mirror::DexCache::SetElementPtrSize(resolved_methods,
898 i,
899 resolution_method,
900 target_ptr_size_);
901 } else {
902 // Check that the class is still in the classes table.
903 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
904 << PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700905 }
906 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800907 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700908 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800909 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800910 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700911 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700912 }
913 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700914 // Clean the dex field. It might have been populated during the initialization phase, but
915 // contains data only valid during a real run.
916 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700917 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700918
919 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
920 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800921
922 // Clear to save RAM.
923 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700924}
925
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800926void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700927 if (compiler_driver_.GetImageClasses() != nullptr) {
928 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700929 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700930 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700931}
932
933void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
934 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800935 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700936 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800937 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700938 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700939 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800940 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
941 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700942 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700943 }
944}
945
946void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700947 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700948 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700949 for (const std::string& image_class : *image_classes) {
950 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700951 }
952}
953
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800954mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
955 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +0000956 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800957 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
958 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
959 << string->ToModifiedUtf8();
960 if (found != nullptr) {
961 return found;
962 }
963 }
964 if (compile_app_image_) {
965 Runtime* const runtime = Runtime::Current();
966 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
967 // If we found it in the runtime intern table it could either be in the boot image or interned
968 // during app image compilation. If it was in the boot image return that, otherwise return null
969 // since it belongs to another image space.
970 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
971 return found;
972 }
973 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
974 << string->ToModifiedUtf8();
975 }
976 return nullptr;
977}
978
Brian Carlstrom7940e442013-07-12 13:46:57 -0700979
Vladimir Marko944da602016-02-19 12:27:55 +0000980ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700981 Runtime* runtime = Runtime::Current();
982 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700983 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700984 StackHandleScope<3> hs(self);
985 Handle<Class> object_array_class(hs.NewHandle(
986 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700987
Jeff Haodcdc85b2015-12-04 14:06:18 -0800988 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +0000989 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800990 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +0000991 size_t image_oat_index = pair.second;
992 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800993 image_dex_files.insert(image_dex_file);
994 }
995 }
996
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700997 // build an Object[] of all the DexCaches used in the source_space_.
998 // Since we can't hold the dex lock when allocating the dex_caches
999 // ObjectArray, we lock the dex lock twice, first to get the number
1000 // of dex caches first and then lock it again to copy the dex
1001 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001002 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001003 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001004 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001005 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001006 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1007 mirror::DexCache* dex_cache =
1008 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001009 if (dex_cache == nullptr) {
1010 continue;
1011 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001012 const DexFile* dex_file = dex_cache->GetDexFile();
1013 if (!IsInBootImage(dex_cache)) {
1014 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1015 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001016 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001017 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001018 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001019 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001020 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1021 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001022 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001023 size_t non_image_dex_caches = 0;
1024 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001025 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1026 mirror::DexCache* dex_cache =
1027 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001028 if (dex_cache == nullptr) {
1029 continue;
1030 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001031 const DexFile* dex_file = dex_cache->GetDexFile();
1032 if (!IsInBootImage(dex_cache)) {
1033 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1034 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001035 }
1036 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1037 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001038 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001039 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1040 mirror::DexCache* dex_cache =
1041 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001042 if (dex_cache == nullptr) {
1043 continue;
1044 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001045 const DexFile* dex_file = dex_cache->GetDexFile();
1046 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001047 dex_caches->Set<false>(i, dex_cache);
1048 ++i;
1049 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001050 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001051 }
1052
1053 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001054 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001055 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001056 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001057 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001058 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001059 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001060 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001061 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001062}
1063
Mathieu Chartier496577f2016-09-20 15:33:31 -07001064mirror::Object* ImageWriter::TryAssignBinSlot(WorkStack& work_stack,
1065 mirror::Object* obj,
1066 size_t oat_index) {
1067 if (obj == nullptr || IsInBootImage(obj)) {
1068 // Object is null or already in the image, there is no work to do.
1069 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001070 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001071 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001072 // We want to intern all strings but also assign offsets for the source string. Since the
1073 // pruning phase has already happened, if we intern a string to one in the image we still
1074 // end up copying an unreachable string.
1075 if (obj->IsString()) {
1076 // Need to check if the string is already interned in another image info so that we don't have
1077 // the intern tables of two different images contain the same string.
1078 mirror::String* interned = FindInternedString(obj->AsString());
1079 if (interned == nullptr) {
1080 // Not in another image space, insert to our table.
1081 interned = GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString());
1082 DCHECK_EQ(interned, obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001083 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001084 } else if (obj->IsDexCache()) {
1085 oat_index = GetOatIndexForDexCache(obj->AsDexCache());
1086 } else if (obj->IsClass()) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001087 // Visit and assign offsets for fields and field arrays.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001088 mirror::Class* as_klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001089 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001090 DCHECK_NE(as_klass->GetStatus(), mirror::Class::kStatusError);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001091 if (compile_app_image_) {
1092 // Extra sanity, no boot loader classes should be left!
1093 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1094 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001095 LengthPrefixedArray<ArtField>* fields[] = {
1096 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1097 };
Mathieu Chartier496577f2016-09-20 15:33:31 -07001098 // Overwrite the oat index value since the class' dex cache is more accurate of where it
1099 // belongs.
1100 oat_index = GetOatIndexForDexCache(dex_cache);
Vladimir Marko944da602016-02-19 12:27:55 +00001101 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001102 {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001103 // Note: This table is only accessed from the image writer, avoid locking to prevent lock
1104 // order violations from root visiting.
1105 image_info.class_table_->InsertWithoutLocks(as_klass);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001106 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001107 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1108 // Total array length including header.
1109 if (cur_fields != nullptr) {
1110 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1111 // Forward the entire array at once.
1112 auto it = native_object_relocations_.find(cur_fields);
1113 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1114 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001115 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001116 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001117 native_object_relocations_.emplace(
1118 cur_fields,
1119 NativeObjectRelocation {
1120 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1121 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001122 offset += header_size;
1123 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001124 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001125 // Need to forward arrays separate of fields.
1126 ArtField* field = &cur_fields->At(i);
1127 auto it2 = native_object_relocations_.find(field);
1128 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1129 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001130 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001131 native_object_relocations_.emplace(
1132 field,
1133 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001134 offset += sizeof(ArtField);
1135 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001136 }
1137 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001138 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001139 size_t num_methods = as_klass->NumMethods();
1140 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001141 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001142 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1143 if (WillMethodBeDirty(&m)) {
1144 any_dirty = true;
1145 break;
1146 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001147 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001148 NativeObjectRelocationType type = any_dirty
1149 ? kNativeObjectRelocationTypeArtMethodDirty
1150 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001151 Bin bin_type = BinTypeForNativeRelocationType(type);
1152 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001153 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1154 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001155 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1156 method_size,
1157 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001158 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001159 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001160 CHECK(it == native_object_relocations_.end())
1161 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001162 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001163 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001164 native_object_relocations_.emplace(array,
1165 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001166 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001167 offset,
1168 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1169 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001170 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001171 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001172 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001173 }
Alex Lighte64300b2015-12-15 15:02:47 -08001174 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001175 }
1176 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1177 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001178 if (as_klass->ShouldHaveImt()) {
1179 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1180 for (size_t i = 0; i < ImTable::kSize; ++i) {
1181 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001182 DCHECK(imt_method != nullptr);
1183 if (imt_method->IsRuntimeMethod() &&
1184 !IsInBootImage(imt_method) &&
1185 !NativeRelocationAssigned(imt_method)) {
1186 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001187 }
1188 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001189 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001190
1191 if (as_klass->ShouldHaveImt()) {
1192 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1193 TryAssignImTableOffset(imt, oat_index);
1194 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001195 } else if (obj->IsClassLoader()) {
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001196 // Register the class loader if it has a class table.
1197 // The fake boot class loader should not get registered and we should end up with only one
1198 // class loader.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001199 mirror::ClassLoader* class_loader = obj->AsClassLoader();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001200 if (class_loader->GetClassTable() != nullptr) {
1201 class_loaders_.insert(class_loader);
1202 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001203 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001204 AssignImageBinSlot(obj, oat_index);
1205 work_stack.emplace(obj, oat_index);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001206 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001207 if (obj->IsString()) {
1208 // Always return the interned string if there exists one.
1209 mirror::String* interned = FindInternedString(obj->AsString());
1210 if (interned != nullptr) {
1211 return interned;
1212 }
1213 }
1214 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001215}
1216
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001217bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1218 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1219}
1220
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001221void ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
1222 // No offset, or already assigned.
1223 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
1224 return;
1225 }
1226 // If the method is a conflict method we also want to assign the conflict table offset.
1227 ImageInfo& image_info = GetImageInfo(oat_index);
1228 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1229 native_object_relocations_.emplace(
1230 imt,
1231 NativeObjectRelocation {
1232 oat_index,
1233 image_info.bin_slot_sizes_[kBinImTable],
1234 kNativeObjectRelocationTypeIMTable});
1235 image_info.bin_slot_sizes_[kBinImTable] += size;
1236}
1237
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001238void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1239 // No offset, or already assigned.
1240 if (table == nullptr || NativeRelocationAssigned(table)) {
1241 return;
1242 }
1243 CHECK(!IsInBootImage(table));
1244 // If the method is a conflict method we also want to assign the conflict table offset.
1245 ImageInfo& image_info = GetImageInfo(oat_index);
1246 const size_t size = table->ComputeSize(target_ptr_size_);
1247 native_object_relocations_.emplace(
1248 table,
1249 NativeObjectRelocation {
1250 oat_index,
1251 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1252 kNativeObjectRelocationTypeIMTConflictTable});
1253 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1254}
1255
Jeff Haodcdc85b2015-12-04 14:06:18 -08001256void ImageWriter::AssignMethodOffset(ArtMethod* method,
1257 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001258 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001259 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001260 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001261 << PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001262 if (method->IsRuntimeMethod()) {
1263 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1264 }
Vladimir Marko944da602016-02-19 12:27:55 +00001265 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001266 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001267 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001268 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001269}
1270
Mathieu Chartier496577f2016-09-20 15:33:31 -07001271void ImageWriter::EnsureBinSlotAssignedCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001272 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1273 DCHECK(writer != nullptr);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001274 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) {
1275 CHECK(writer->IsImageBinSlotAssigned(obj)) << PrettyTypeOf(obj) << " " << obj;
1276 }
1277}
1278
1279void ImageWriter::DeflateMonitorCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED) {
1280 Monitor::Deflate(Thread::Current(), obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001281}
1282
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001283void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1284 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1285 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001286 if (!writer->IsInBootImage(obj)) {
1287 writer->UnbinObjectsIntoOffset(obj);
1288 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001289}
1290
1291void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001292 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001293 CHECK(obj != nullptr);
1294
1295 // We know the bin slot, and the total bin sizes for all objects by now,
1296 // so calculate the object's final image offset.
1297
1298 DCHECK(IsImageBinSlotAssigned(obj));
1299 BinSlot bin_slot = GetImageBinSlot(obj);
1300 // Change the lockword from a bin slot into an offset
1301 AssignImageOffset(obj, bin_slot);
1302}
1303
Mathieu Chartier496577f2016-09-20 15:33:31 -07001304class ImageWriter::VisitReferencesVisitor {
1305 public:
1306 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index)
1307 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {}
1308
1309 // Fix up separately since we also need to fix up method entrypoints.
1310 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1311 REQUIRES_SHARED(Locks::mutator_lock_) {
1312 if (!root->IsNull()) {
1313 VisitRoot(root);
1314 }
1315 }
1316
1317 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1318 REQUIRES_SHARED(Locks::mutator_lock_) {
1319 root->Assign(VisitReference(root->AsMirrorPtr()));
1320 }
1321
1322 ALWAYS_INLINE void operator() (mirror::Object* obj,
1323 MemberOffset offset,
1324 bool is_static ATTRIBUTE_UNUSED) const
1325 REQUIRES_SHARED(Locks::mutator_lock_) {
1326 mirror::Object* ref =
1327 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1328 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1329 }
1330
1331 ALWAYS_INLINE void operator() (mirror::Class* klass ATTRIBUTE_UNUSED,
1332 mirror::Reference* ref) const
1333 REQUIRES_SHARED(Locks::mutator_lock_) {
1334 ref->SetReferent</*kTransactionActive*/false>(
1335 VisitReference(ref->GetReferent<kWithoutReadBarrier>()));
1336 }
1337
1338 private:
1339 mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1340 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_);
1341 }
1342
1343 ImageWriter* const image_writer_;
1344 WorkStack* const work_stack_;
1345 const size_t oat_index_;
1346};
1347
1348class ImageWriter::GetRootsVisitor : public RootVisitor {
1349 public:
1350 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {}
1351
1352 void VisitRoots(mirror::Object*** roots,
1353 size_t count,
1354 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1355 REQUIRES_SHARED(Locks::mutator_lock_) {
1356 for (size_t i = 0; i < count; ++i) {
1357 roots_->push_back(*roots[i]);
1358 }
1359 }
1360
1361 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1362 size_t count,
1363 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1364 REQUIRES_SHARED(Locks::mutator_lock_) {
1365 for (size_t i = 0; i < count; ++i) {
1366 roots_->push_back(roots[i]->AsMirrorPtr());
1367 }
1368 }
1369
1370 private:
1371 std::vector<mirror::Object*>* const roots_;
1372};
1373
1374void ImageWriter::ProcessWorkStack(WorkStack* work_stack) {
1375 while (!work_stack->empty()) {
1376 std::pair<mirror::Object*, size_t> pair(work_stack->top());
1377 work_stack->pop();
1378 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second);
1379 // Walk references and assign bin slots for them.
1380 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1381 visitor,
1382 visitor);
1383 }
1384}
1385
Vladimir Markof4da6752014-08-01 19:04:18 +01001386void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001387 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001388 StackHandleScopeCollection handles(self);
1389 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001390 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1391 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001392 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001393
Mathieu Chartier496577f2016-09-20 15:33:31 -07001394 Runtime* const runtime = Runtime::Current();
1395 gc::Heap* const heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001396
Mathieu Chartier31e89252013-08-28 11:29:12 -07001397 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001398 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001399 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001400
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001401 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001402 // Write the image runtime methods.
1403 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1404 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1405 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001406 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
1407 runtime->GetCalleeSaveMethod(Runtime::kSaveAllCalleeSaves);
1408 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
1409 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsOnly);
1410 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
1411 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001412 image_methods_[ImageHeader::kSaveEverythingMethod] =
1413 runtime->GetCalleeSaveMethod(Runtime::kSaveEverything);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001414 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001415 for (auto* m : image_methods_) {
1416 CHECK(m != nullptr);
1417 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001418 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1419 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001420 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001421 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001422 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001423
Mathieu Chartier496577f2016-09-20 15:33:31 -07001424 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
1425 // this lock while holding other locks may cause lock order violations.
1426 heap->VisitObjects(DeflateMonitorCallback, this);
1427
1428 // Work list of <object, oat_index> for objects. Everything on the stack must already be
1429 // assigned a bin slot.
1430 WorkStack work_stack;
1431
1432 // Special case interned strings to put them in the image they are likely to be resolved from.
1433 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
1434 auto it = dex_file_oat_index_map_.find(dex_file);
1435 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1436 const size_t oat_index = it->second;
1437 InternTable* const intern_table = runtime->GetInternTable();
1438 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
1439 uint32_t utf16_length;
1440 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(i, &utf16_length);
1441 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data);
1442 TryAssignBinSlot(work_stack, string, oat_index);
1443 }
1444 }
1445
1446 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor
1447 // visits roots while holding various locks.
1448 {
1449 std::vector<mirror::Object*> roots;
1450 GetRootsVisitor root_visitor(&roots);
1451 runtime->VisitRoots(&root_visitor);
1452 for (mirror::Object* obj : roots) {
1453 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex());
1454 }
1455 }
1456 ProcessWorkStack(&work_stack);
1457
1458 // For app images, there may be objects that are only held live by the by the boot image. One
1459 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback
1460 // does not fail any checks. TODO: We should probably avoid copying these objects.
1461 if (compile_app_image_) {
1462 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) {
1463 DCHECK(space->IsImageSpace());
1464 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1465 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1466 reinterpret_cast<uintptr_t>(space->Limit()),
1467 [this, &work_stack](mirror::Object* obj)
1468 REQUIRES_SHARED(Locks::mutator_lock_) {
1469 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex());
1470 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot).
1471 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1472 visitor,
1473 visitor);
1474 });
1475 }
1476 // Process the work stack in case anything was added by TryAssignBinSlot.
1477 ProcessWorkStack(&work_stack);
1478 }
1479
1480 // Verify that all objects have assigned image bin slots.
1481 heap->VisitObjects(EnsureBinSlotAssignedCallback, this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001482
Vladimir Marko05792b92015-08-03 11:56:49 +01001483 // Calculate size of the dex cache arrays slot and prepare offsets.
1484 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001485
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001486 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001487 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001488 // Calculate how big the intern table will be after being serialized.
1489 InternTable* const intern_table = image_info.intern_table_.get();
1490 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1491 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001492 // Calculate the size of the class table.
1493 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1494 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001495 }
1496
Vladimir Markocf36d492015-08-12 19:27:26 +01001497 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001498 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001499 size_t bin_offset = image_objects_offset_begin_;
1500 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001501 switch (i) {
1502 case kBinArtMethodClean:
1503 case kBinArtMethodDirty: {
1504 bin_offset = RoundUp(bin_offset, method_alignment);
1505 break;
1506 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001507 case kBinDexCacheArray:
1508 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment());
1509 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001510 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001511 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001512 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001513 break;
1514 }
1515 default: {
1516 // Normal alignment.
1517 }
1518 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001519 image_info.bin_slot_offsets_[i] = bin_offset;
1520 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001521 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001522 // NOTE: There may be additional padding between the bin slots and the intern table.
1523 DCHECK_EQ(image_info.image_end_,
1524 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001525 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001526
Jeff Haodcdc85b2015-12-04 14:06:18 -08001527 // Calculate image offsets.
1528 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001529 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001530 image_info.image_begin_ = global_image_begin_ + image_offset;
1531 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001532 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001533 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001534 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001535 image_offset += image_info.image_size_;
1536 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001537
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001538 // Transform each object's bin slot into an offset which will be used to do the final copy.
1539 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001540
Jeff Haodcdc85b2015-12-04 14:06:18 -08001541 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001542
Jeff Haodcdc85b2015-12-04 14:06:18 -08001543 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001544 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001545 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1546 i++;
1547 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001548
Mathieu Chartiere401d142015-04-22 13:56:20 -07001549 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001550 for (auto& pair : native_object_relocations_) {
1551 NativeObjectRelocation& relocation = pair.second;
1552 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001553 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001554 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001555 }
1556
Jeff Haodcdc85b2015-12-04 14:06:18 -08001557 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001558}
1559
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001560size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001561 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001562
1563 // Do not round up any sections here that are represented by the bins since it will break
1564 // offsets.
1565
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001566 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001567 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001568 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001569
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001570 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001571 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1572 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001573 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001574
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001575 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001576 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1577 *methods_section = ImageSection(
1578 bin_slot_offsets_[kBinArtMethodClean],
1579 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1580
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001581 // IMT section.
1582 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1583 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1584
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001585 // Conflict tables section.
1586 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1587 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1588 bin_slot_sizes_[kBinIMTConflictTable]);
1589
1590 // Runtime methods section.
1591 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1592 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1593 bin_slot_sizes_[kBinRuntimeMethod]);
1594
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001595 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001596 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1597 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1598 bin_slot_sizes_[kBinDexCacheArray]);
1599
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001600 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001601 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001602 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001603 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001604 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1605 cur_pos = interned_strings_section->End();
1606 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1607 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1608 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001609 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001610 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001611 cur_pos = class_table_section->End();
1612 // Image end goes right before the start of the image bitmap.
1613 return cur_pos;
1614}
1615
Vladimir Marko944da602016-02-19 12:27:55 +00001616void ImageWriter::CreateHeader(size_t oat_index) {
1617 ImageInfo& image_info = GetImageInfo(oat_index);
1618 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1619 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1620 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001621
1622 // Create the image sections.
1623 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001624 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001625
Mathieu Chartiere401d142015-04-22 13:56:20 -07001626 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001627 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001628 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001629 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001630 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001631 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001632 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001633 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001634 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1635 ++idx;
1636 }
1637 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001638 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1639 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1640 << " Image offset=" << image_info.image_offset_ << std::dec;
1641 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1642 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1643 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1644 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001645 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001646 // Store boot image info for app image so that we can relocate.
1647 uint32_t boot_image_begin = 0;
1648 uint32_t boot_image_end = 0;
1649 uint32_t boot_oat_begin = 0;
1650 uint32_t boot_oat_end = 0;
1651 gc::Heap* const heap = Runtime::Current()->GetHeap();
1652 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001653
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001654 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1655 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001656 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1657 image_end,
1658 sections,
1659 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001660 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001661 PointerToLowMemUInt32(oat_file_begin),
1662 PointerToLowMemUInt32(image_info.oat_data_begin_),
1663 PointerToLowMemUInt32(oat_data_end),
1664 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001665 boot_image_begin,
1666 boot_image_end - boot_image_begin,
1667 boot_oat_begin,
1668 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001669 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001670 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001671 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001672 image_storage_mode_,
1673 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001674}
1675
1676ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001677 auto it = native_object_relocations_.find(method);
1678 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001679 size_t oat_index = GetOatIndex(method->GetDexCache());
1680 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001681 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1682 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001683}
1684
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001685class FixupRootVisitor : public RootVisitor {
1686 public:
1687 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1688 }
1689
1690 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001691 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001692 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001693 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001694 }
1695 }
1696
1697 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1698 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001699 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001700 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001701 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001702 }
1703 }
1704
1705 private:
1706 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001707};
1708
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001709void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
1710 for (size_t i = 0; i < ImTable::kSize; ++i) {
1711 ArtMethod* method = orig->Get(i, target_ptr_size_);
1712 copy->Set(i, NativeLocationInImage(method), target_ptr_size_);
1713 }
1714}
1715
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001716void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
1717 const size_t count = orig->NumEntries(target_ptr_size_);
1718 for (size_t i = 0; i < count; ++i) {
1719 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
1720 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
1721 copy->SetInterfaceMethod(i, target_ptr_size_, NativeLocationInImage(interface_method));
1722 copy->SetImplementationMethod(i,
1723 target_ptr_size_,
1724 NativeLocationInImage(implementation_method));
1725 }
1726}
1727
Vladimir Marko944da602016-02-19 12:27:55 +00001728void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001729 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001730 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001731 for (auto& pair : native_object_relocations_) {
1732 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001733 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001734 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001735 continue;
1736 }
1737 auto* dest = image_info.image_->Begin() + relocation.offset;
1738 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001739 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001740 switch (relocation.type) {
1741 case kNativeObjectRelocationTypeArtField: {
1742 memcpy(dest, pair.first, sizeof(ArtField));
1743 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1744 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1745 break;
1746 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001747 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001748 case kNativeObjectRelocationTypeArtMethodClean:
1749 case kNativeObjectRelocationTypeArtMethodDirty: {
1750 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001751 reinterpret_cast<ArtMethod*>(dest),
1752 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001753 break;
1754 }
1755 // For arrays, copy just the header since the elements will get copied by their corresponding
1756 // relocations.
1757 case kNativeObjectRelocationTypeArtFieldArray: {
1758 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1759 break;
1760 }
1761 case kNativeObjectRelocationTypeArtMethodArrayClean:
1762 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00001763 size_t size = ArtMethod::Size(target_ptr_size_);
1764 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1765 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1766 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1767 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001768 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00001769 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001770 case kNativeObjectRelocationTypeDexCacheArray:
1771 // Nothing to copy here, everything is done in FixupDexCache().
1772 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001773 case kNativeObjectRelocationTypeIMTable: {
1774 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
1775 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
1776 CopyAndFixupImTable(orig_imt, dest_imt);
1777 break;
1778 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001779 case kNativeObjectRelocationTypeIMTConflictTable: {
1780 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
1781 CopyAndFixupImtConflictTable(
1782 orig_table,
1783 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
1784 break;
1785 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001786 }
1787 }
1788 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001789 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001790 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001791 ArtMethod* method = image_methods_[i];
1792 CHECK(method != nullptr);
1793 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001794 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001795 }
1796 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001797 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001798 FixupRootVisitor root_visitor(this);
1799
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001800 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001801 if (image_info.intern_table_bytes_ > 0) {
1802 const ImageSection& intern_table_section = image_header->GetImageSection(
1803 ImageHeader::kSectionInternedStrings);
1804 InternTable* const intern_table = image_info.intern_table_.get();
1805 uint8_t* const intern_table_memory_ptr =
1806 image_info.image_->Begin() + intern_table_section.Offset();
1807 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1808 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1809 // Fixup the pointers in the newly written intern table to contain image addresses.
1810 InternTable temp_intern_table;
1811 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1812 // the VisitRoots() will update the memory directly rather than the copies.
1813 // This also relies on visit roots not doing any verification which could fail after we update
1814 // the roots to be the image addresses.
1815 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1816 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1817 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1818 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001819 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1820 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001821 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001822 const ImageSection& class_table_section = image_header->GetImageSection(
1823 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001824 uint8_t* const class_table_memory_ptr =
1825 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001826 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001827
1828 ClassTable* table = image_info.class_table_.get();
1829 CHECK(table != nullptr);
1830 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1831 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1832 // Fixup the pointers in the newly written class table to contain image addresses. See
1833 // above comment for intern tables.
1834 ClassTable temp_class_table;
1835 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1836 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1837 table->NumZygoteClasses());
1838 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1839 RootInfo(kRootUnknown));
1840 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001841 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001842}
1843
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001844void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001845 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001846 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1847 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001848 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001849 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001850 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1851 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001852 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001853 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001854}
1855
Mathieu Chartier590fee92013-09-13 13:46:47 -07001856void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001857 DCHECK(obj != nullptr);
1858 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001859 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1860}
1861
Mathieu Chartiere401d142015-04-22 13:56:20 -07001862void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1863 mirror::Class* klass, Bin array_type) {
1864 CHECK(klass->IsArrayClass());
1865 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1866 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001867 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001868 dst->SetClass(GetImageAddress(arr->GetClass()));
1869 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001870 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001871 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1872 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001873 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001874 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001875 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001876 auto* method = reinterpret_cast<ArtMethod*>(elem);
1877 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1878 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1879 << PrettyClass(method->GetDeclaringClass());
1880 } else {
1881 CHECK_EQ(array_type, kBinArtField);
1882 auto* field = reinterpret_cast<ArtField*>(elem);
1883 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1884 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1885 << PrettyClass(field->GetDeclaringClass());
1886 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001887 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001888 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001889 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001890 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001891 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001892 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001893 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001894 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001895}
1896
1897void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001898 if (IsInBootImage(obj)) {
1899 return;
1900 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001901 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001902 size_t oat_index = GetOatIndex(obj);
1903 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001904 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1905 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001906 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001907
Jeff Haodcdc85b2015-12-04 14:06:18 -08001908 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001909
1910 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001911 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001912 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001913
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001914 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1915 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001916 const auto it = saved_hashcode_map_.find(obj);
1917 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1918 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001919 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
1920 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
1921 // safe since we mark all of the objects that may reference non immune objects as gray.
1922 CHECK(dst->AtomicSetMarkBit(0, 1));
1923 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001924 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001925}
1926
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001927// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001928class FixupVisitor {
1929 public:
1930 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1931 }
1932
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001933 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1934 // with other logic.
1935 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1936 const {}
1937 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1938
1939
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001940 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001941 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001942 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001943 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1944 // image.
1945 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001946 offset,
1947 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001948 }
1949
1950 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001951 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001952 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001953 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001954 mirror::Reference::ReferentOffset(),
1955 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001956 }
1957
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001958 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001959 ImageWriter* const image_writer_;
1960 mirror::Object* const copy_;
1961};
1962
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001963class FixupClassVisitor FINAL : public FixupVisitor {
1964 public:
1965 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1966 }
1967
Mathieu Chartierc7853442015-03-27 14:35:38 -07001968 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001969 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001970 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001971 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001972 }
1973
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001974 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1975 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001976 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001977 LOG(FATAL) << "Reference not expected here.";
1978 }
1979};
1980
Vladimir Marko05792b92015-08-03 11:56:49 +01001981uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1982 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001983 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001984 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001985 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1986 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001987 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001988 return relocation.offset;
1989}
1990
1991template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001992std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001993 std::ostringstream oss;
1994 oss << ptr;
1995 return oss.str();
1996}
1997
1998template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001999std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002000 return PrettyMethod(method);
2001}
2002
2003template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002004T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002005 if (obj == nullptr || IsInBootImage(obj)) {
2006 return obj;
2007 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002008 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002009 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
2010 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002011 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00002012 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002013 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002014 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002015}
2016
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002017template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08002018T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
2019 if (obj == nullptr || IsInBootImage(obj)) {
2020 return obj;
2021 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002022 size_t oat_index = GetOatIndexForDexCache(dex_cache);
2023 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002024 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
2025 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002026}
2027
2028class NativeLocationVisitor {
2029 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002030 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002031
2032 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002033 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002034 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002035 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002036
2037 private:
2038 ImageWriter* const image_writer_;
2039};
2040
2041void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002042 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002043 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002044 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002045
2046 // Remove the clinitThreadId. This is required for image determinism.
2047 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002048}
2049
Ian Rogersef7d42f2014-01-06 12:55:46 -08002050void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002051 DCHECK(orig != nullptr);
2052 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002053 if (kUseBakerOrBrooksReadBarrier) {
2054 orig->AssertReadBarrierPointer();
2055 if (kUseBrooksReadBarrier) {
2056 // Note the address 'copy' isn't the same as the image address of 'orig'.
2057 copy->SetReadBarrierPointer(GetImageAddress(orig));
2058 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
2059 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002060 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002061 auto* klass = orig->GetClass();
2062 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002063 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07002064 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
2065 if (it != pointer_arrays_.end()) {
2066 // Should only need to fixup every pointer array exactly once.
2067 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
2068 pointer_arrays_.erase(it);
2069 return;
2070 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002071 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002072 if (orig->IsClass()) {
2073 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002074 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002075 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
2076 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01002077 auto* dest = down_cast<mirror::Executable*>(copy);
2078 auto* src = down_cast<mirror::Executable*>(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002079 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05002080 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01002081 } else if (!klass->IsArrayClass()) {
2082 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2083 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
2084 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002085 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002086 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002087 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2088 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002089 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002090 // Also set allocator to null to be safe. The allocator is created when we create the class
2091 // table. We also never expect to unload things in the image since they are held live as
2092 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002093 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002094 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002095 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002096 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002097 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002098 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002099}
2100
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002101
2102class ImageAddressVisitor {
2103 public:
2104 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
2105
2106 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002107 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002108 return image_writer_->GetImageAddress(ptr);
2109 }
2110
2111 private:
2112 ImageWriter* const image_writer_;
2113};
2114
2115
Vladimir Marko05792b92015-08-03 11:56:49 +01002116void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2117 mirror::DexCache* copy_dex_cache) {
2118 // Though the DexCache array fields are usually treated as native pointers, we set the full
2119 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2120 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2121 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002122 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002123 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002124 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002125 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002126 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002127 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
2128 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002129 }
2130 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
2131 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002132 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002133 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002134 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002135 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
2136 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002137 }
2138 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
2139 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002140 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002141 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002142 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002143 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002144 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
2145 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002146 // NativeLocationInImage also handles runtime methods since these have relocation info.
2147 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002148 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
2149 }
2150 }
2151 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
2152 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002153 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002154 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002155 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002156 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002157 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
2158 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002159 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002160 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
2161 }
2162 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002163
2164 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2165 // compiler pointers in here will make the output non-deterministic.
2166 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002167}
2168
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002169const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2170 DCHECK_LT(type, kOatAddressCount);
2171 // If we are compiling an app image, we need to use the stubs of the boot image.
2172 if (compile_app_image_) {
2173 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002174 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002175 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2176 DCHECK(!image_spaces.empty());
2177 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002178 CHECK(oat_file != nullptr);
2179 const OatHeader& header = oat_file->GetOatHeader();
2180 switch (type) {
2181 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2182 case kOatAddressQuickGenericJNITrampoline:
2183 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2184 case kOatAddressInterpreterToInterpreterBridge:
2185 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2186 case kOatAddressInterpreterToCompiledCodeBridge:
2187 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2188 case kOatAddressJNIDlsymLookup:
2189 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2190 case kOatAddressQuickIMTConflictTrampoline:
2191 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2192 case kOatAddressQuickResolutionTrampoline:
2193 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2194 case kOatAddressQuickToInterpreterBridge:
2195 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2196 default:
2197 UNREACHABLE();
2198 }
2199 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002200 const ImageInfo& primary_image_info = GetImageInfo(0);
2201 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002202}
2203
Jeff Haodcdc85b2015-12-04 14:06:18 -08002204const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2205 const ImageInfo& image_info,
2206 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002207 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
Nicolas Geoffray796d6302016-03-13 22:22:31 +00002208 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002209 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07002210 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002211 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002212
2213 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2214 // trampoline.
2215
2216 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002217 const void* quick_oat_entry_point =
2218 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2219 const uint8_t* quick_code;
2220
2221 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2222 DCHECK(method->IsCopied());
2223 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2224 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2225 } else {
2226 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2227 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2228 }
2229
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002230 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002231 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2232 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002233 // We have code for a non-static or initialized method, just use the code.
2234 } else if (quick_code == nullptr && method->IsNative() &&
2235 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2236 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002237 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002238 } else if (quick_code == nullptr && !method->IsNative()) {
2239 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002240 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002241 *quick_is_interpreted = true;
2242 } else {
2243 CHECK(!method->GetDeclaringClass()->IsInitialized());
2244 // We have code for a static method, but need to go through the resolution stub for class
2245 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002246 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2247 }
2248 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002249 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002250 }
2251 return quick_code;
2252}
2253
Jeff Haodcdc85b2015-12-04 14:06:18 -08002254void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2255 ArtMethod* copy,
2256 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002257 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002258
2259 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002260 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002261 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002262 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002263 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002264
Ian Rogers848871b2013-08-05 10:56:33 -07002265 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2266 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002267
Ian Rogers848871b2013-08-05 10:56:33 -07002268 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002269 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002270 if (orig->IsRuntimeMethod()) {
2271 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2272 if (orig_table != nullptr) {
2273 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2274 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2275 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2276 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2277 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2278 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2279 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2280 } else {
2281 bool found_one = false;
2282 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2283 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2284 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2285 found_one = true;
2286 break;
2287 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002288 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002289 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2290 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002291 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002292 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002293 // We assume all methods have code. If they don't currently then we set them to the use the
2294 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2295 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002296 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002297 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002298 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002299 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002300 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002301 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002302 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002303
Sebastien Hertze1d07812014-05-21 15:44:09 +02002304 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002305 if (orig->IsNative()) {
2306 // The native method's pointer is set to a stub to lookup via dlsym.
2307 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002308 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002309 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002310 }
2311 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002312 }
2313}
2314
Jeff Haodcdc85b2015-12-04 14:06:18 -08002315size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002316 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002317 return std::accumulate(&image_info.bin_slot_sizes_[0],
2318 &image_info.bin_slot_sizes_[up_to],
2319 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002320}
2321
2322ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2323 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002324 static_assert(kBinBits == 3, "wrong number of bin bits");
2325 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002326 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2327
2328 DCHECK_LT(GetBin(), kBinSize);
2329 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2330}
2331
2332ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2333 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2334 DCHECK_EQ(index, GetIndex());
2335}
2336
2337ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2338 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2339}
2340
2341uint32_t ImageWriter::BinSlot::GetIndex() const {
2342 return lockword_ & ~kBinMask;
2343}
2344
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002345ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2346 switch (type) {
2347 case kNativeObjectRelocationTypeArtField:
2348 case kNativeObjectRelocationTypeArtFieldArray:
2349 return kBinArtField;
2350 case kNativeObjectRelocationTypeArtMethodClean:
2351 case kNativeObjectRelocationTypeArtMethodArrayClean:
2352 return kBinArtMethodClean;
2353 case kNativeObjectRelocationTypeArtMethodDirty:
2354 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2355 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002356 case kNativeObjectRelocationTypeDexCacheArray:
2357 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002358 case kNativeObjectRelocationTypeRuntimeMethod:
2359 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002360 case kNativeObjectRelocationTypeIMTable:
2361 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002362 case kNativeObjectRelocationTypeIMTConflictTable:
2363 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002364 }
2365 UNREACHABLE();
2366}
2367
Vladimir Marko944da602016-02-19 12:27:55 +00002368size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002369 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002370 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002371 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002372 auto it = oat_index_map_.find(obj);
2373 DCHECK(it != oat_index_map_.end());
2374 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002375}
2376
Vladimir Marko944da602016-02-19 12:27:55 +00002377size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002378 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002379 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002380 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002381 auto it = dex_file_oat_index_map_.find(dex_file);
2382 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2383 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002384}
2385
Vladimir Marko944da602016-02-19 12:27:55 +00002386size_t ImageWriter::GetOatIndexForDexCache(mirror::DexCache* dex_cache) const {
2387 if (dex_cache == nullptr) {
2388 return GetDefaultOatIndex();
2389 } else {
2390 return GetOatIndexForDexFile(dex_cache->GetDexFile());
2391 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002392}
2393
Vladimir Marko944da602016-02-19 12:27:55 +00002394void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2395 size_t oat_loaded_size,
2396 size_t oat_data_offset,
2397 size_t oat_data_size) {
2398 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2399 for (const ImageInfo& info : image_infos_) {
2400 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2401 }
2402 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002403
Vladimir Marko944da602016-02-19 12:27:55 +00002404 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2405 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2406 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2407 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2408 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002409
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002410 if (compile_app_image_) {
2411 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2412 return;
2413 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002414
2415 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002416 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002417 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002418 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002419 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2420 }
2421}
2422
Vladimir Marko944da602016-02-19 12:27:55 +00002423void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2424 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2425 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2426
2427 if (oat_index == GetDefaultOatIndex()) {
2428 // Primary oat file, read the trampolines.
2429 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2430 oat_header.GetInterpreterToInterpreterBridgeOffset();
2431 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2432 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2433 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2434 oat_header.GetJniDlsymLookupOffset();
2435 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2436 oat_header.GetQuickGenericJniTrampolineOffset();
2437 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2438 oat_header.GetQuickImtConflictTrampolineOffset();
2439 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2440 oat_header.GetQuickResolutionTrampolineOffset();
2441 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2442 oat_header.GetQuickToInterpreterBridgeOffset();
2443 }
2444}
2445
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002446ImageWriter::ImageWriter(
2447 const CompilerDriver& compiler_driver,
2448 uintptr_t image_begin,
2449 bool compile_pic,
2450 bool compile_app_image,
2451 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002452 const std::vector<const char*>& oat_filenames,
2453 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002454 : compiler_driver_(compiler_driver),
2455 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2456 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002457 compile_pic_(compile_pic),
2458 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002459 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002460 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002461 dirty_methods_(0u),
2462 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002463 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002464 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002465 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002466 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002467 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002468 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2469 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002470}
2471
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002472ImageWriter::ImageInfo::ImageInfo()
2473 : intern_table_(new InternTable),
2474 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002475
Brian Carlstrom7940e442013-07-12 13:46:57 -07002476} // namespace art