blob: 3e6658ee400cdfa6a097d16a663139f0f350bea9 [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"
Mathieu Chartiere401d142015-04-22 13:56:20 -070051#include "mirror/abstract_method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070052#include "mirror/array-inl.h"
53#include "mirror/class-inl.h"
54#include "mirror/class_loader.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070055#include "mirror/dex_cache.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "mirror/dex_cache-inl.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.
392 Monitor::Deflate(Thread::Current(), object);;
393 LockWord lw(object->GetLockWord(false));
394 switch (lw.GetState()) {
395 case LockWord::kFatLocked: {
396 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
397 break;
398 }
399 case LockWord::kThinLocked: {
400 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
401 break;
402 }
403 case LockWord::kUnlocked:
404 // No hash, don't need to save it.
405 break;
406 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700407 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
408 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800409 break;
410 default:
411 LOG(FATAL) << "Unreachable.";
412 UNREACHABLE();
413 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700414 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700415 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800416 DCHECK(IsImageBinSlotAssigned(object));
417}
418
Vladimir Marko20f85592015-03-19 10:07:02 +0000419void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000420 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000421 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
422 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800423 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000424 auto it = dex_file_oat_index_map_.find(dex_file);
425 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800426 ImageInfo& image_info = GetImageInfo(it->second);
427 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
428 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
429 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
430 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000431
Vladimir Marko20f85592015-03-19 10:07:02 +0000432 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700433 Thread* const self = Thread::Current();
434 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800435 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700436 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800437 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800438 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700439 continue;
440 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000441 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartier0b490842016-05-25 15:05:59 -0700442 CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
443 << "Dex cache should have been pruned " << dex_file->GetLocation()
444 << "; possibly in class path";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700445 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000446 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000447 size_t oat_index = GetOatIndexForDexCache(dex_cache);
448 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800449 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100450 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800451 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
452 start + layout.TypesOffset(),
453 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100454 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800455 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
456 start + layout.MethodsOffset(),
457 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100458 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800459 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
460 start + layout.FieldsOffset(),
461 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100462 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800463 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000464 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000465}
466
Jeff Haodcdc85b2015-12-04 14:06:18 -0800467void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100468 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800469 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000470 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800471 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000472 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100473 }
474}
475
Mathieu Chartiere401d142015-04-22 13:56:20 -0700476void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
477 DCHECK(arr != nullptr);
478 if (kIsDebugBuild) {
479 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800480 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700481 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800482 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800483 CHECK(klass == nullptr || KeepClass(klass))
484 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700485 }
486 }
487 }
488 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
489 // ArtMethods.
490 pointer_arrays_.emplace(arr, kBinArtMethodClean);
491}
492
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800493void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
494 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800495 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800496
497 // The magic happens here. We segregate objects into different bins based
498 // on how likely they are to get dirty at runtime.
499 //
500 // Likely-to-dirty objects get packed together into the same bin so that
501 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
502 // maximized.
503 //
504 // This means more pages will stay either clean or shared dirty (with zygote) and
505 // the app will use less of its own (private) memory.
506 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000507 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800508
509 if (kBinObjects) {
510 //
511 // Changing the bin of an object is purely a memory-use tuning.
512 // It has no change on runtime correctness.
513 //
514 // Memory analysis has determined that the following types of objects get dirtied
515 // the most:
516 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000517 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
518 // a fixed layout which helps improve generated code (using PC-relative addressing),
519 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
520 // Since these arrays are huge, most pages do not overlap other objects and it's not
521 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100522 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800523 // * Class'es which are verified [their clinit runs only at runtime]
524 // - classes in general [because their static fields get overwritten]
525 // - initialized classes with all-final statics are unlikely to be ever dirty,
526 // so bin them separately
527 // * Art Methods that are:
528 // - native [their native entry point is not looked up until runtime]
529 // - have declaring classes that aren't initialized
530 // [their interpreter/quick entry points are trampolines until the class
531 // becomes initialized]
532 //
533 // We also assume the following objects get dirtied either never or extremely rarely:
534 // * Strings (they are immutable)
535 // * Art methods that aren't native and have initialized declared classes
536 //
537 // We assume that "regular" bin objects are highly unlikely to become dirtied,
538 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
539 //
540 if (object->IsClass()) {
541 bin = kBinClassVerified;
542 mirror::Class* klass = object->AsClass();
543
Mathieu Chartiere401d142015-04-22 13:56:20 -0700544 // Add non-embedded vtable to the pointer array table if there is one.
545 auto* vtable = klass->GetVTable();
546 if (vtable != nullptr) {
547 AddMethodPointerArray(vtable);
548 }
549 auto* iftable = klass->GetIfTable();
550 if (iftable != nullptr) {
551 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
552 if (iftable->GetMethodArrayCount(i) > 0) {
553 AddMethodPointerArray(iftable->GetMethodArray(i));
554 }
555 }
556 }
557
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800558 if (klass->GetStatus() == Class::kStatusInitialized) {
559 bin = kBinClassInitialized;
560
561 // If the class's static fields are all final, put it into a separate bin
562 // since it's very likely it will stay clean.
563 uint32_t num_static_fields = klass->NumStaticFields();
564 if (num_static_fields == 0) {
565 bin = kBinClassInitializedFinalStatics;
566 } else {
567 // Maybe all the statics are final?
568 bool all_final = true;
569 for (uint32_t i = 0; i < num_static_fields; ++i) {
570 ArtField* field = klass->GetStaticField(i);
571 if (!field->IsFinal()) {
572 all_final = false;
573 break;
574 }
575 }
576
577 if (all_final) {
578 bin = kBinClassInitializedFinalStatics;
579 }
580 }
581 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800582 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
583 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700584 } else if (object->GetClass<kVerifyNone>() ==
585 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
586 // Instance of java lang object, probably a lock object. This means it will be dirty when we
587 // synchronize on it.
588 bin = kBinMiscDirty;
589 } else if (object->IsDexCache()) {
590 // Dex file field becomes dirty when the image is loaded.
591 bin = kBinMiscDirty;
592 }
593 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800594 }
595
Vladimir Marko944da602016-02-19 12:27:55 +0000596 size_t oat_index = GetOatIndex(object);
597 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800598
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800599 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800600 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
601 // Move the current bin size up to accommodate the object we just assigned a bin slot.
602 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800603
604 BinSlot new_bin_slot(bin, current_offset);
605 SetImageBinSlot(object, new_bin_slot);
606
Jeff Haodcdc85b2015-12-04 14:06:18 -0800607 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800608
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800609 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800610 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800611}
612
Mathieu Chartiere401d142015-04-22 13:56:20 -0700613bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
614 if (m->IsNative()) {
615 return true;
616 }
617 mirror::Class* declaring_class = m->GetDeclaringClass();
618 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
619 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
620}
621
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800622bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
623 DCHECK(object != nullptr);
624
625 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
626 // If it's in some other state, then we haven't yet assigned an image bin slot.
627 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
628 return false;
629 } else if (kIsDebugBuild) {
630 LockWord lock_word = object->GetLockWord(false);
631 size_t offset = lock_word.ForwardingAddress();
632 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000633 size_t oat_index = GetOatIndex(object);
634 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800635 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800636 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800637 }
638 return true;
639}
640
641ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
642 DCHECK(object != nullptr);
643 DCHECK(IsImageBinSlotAssigned(object));
644
645 LockWord lock_word = object->GetLockWord(false);
646 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
647 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
648
649 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000650 size_t oat_index = GetOatIndex(object);
651 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800652 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800653
654 return bin_slot;
655}
656
Brian Carlstrom7940e442013-07-12 13:46:57 -0700657bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000658 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800659 ImageSection unused_sections[ImageHeader::kSectionCount];
660 const size_t length = RoundUp(
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700661 image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800662
Jeff Haodcdc85b2015-12-04 14:06:18 -0800663 std::string error_msg;
664 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
665 nullptr,
666 length,
667 PROT_READ | PROT_WRITE,
668 false,
669 false,
670 &error_msg));
671 if (UNLIKELY(image_info.image_.get() == nullptr)) {
672 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
673 return false;
674 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700675
Jeff Haodcdc85b2015-12-04 14:06:18 -0800676 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
677 CHECK_LE(image_info.image_end_, length);
678 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
679 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
680 if (image_info.image_bitmap_.get() == nullptr) {
681 LOG(ERROR) << "Failed to allocate memory for image bitmap";
682 return false;
683 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700684 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700685 return true;
686}
687
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700688class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
689 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700690 bool operator()(Class* c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700691 StackHandleScope<1> hs(Thread::Current());
692 mirror::Class::ComputeName(hs.NewHandle(c));
693 return true;
694 }
695};
696
Brian Carlstrom7940e442013-07-12 13:46:57 -0700697void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700698 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700699 ComputeLazyFieldsForClassesVisitor visitor;
700 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700701}
702
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700703static bool IsBootClassLoaderClass(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800704 return klass->GetClassLoader() == nullptr;
705}
706
707bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
708 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
709}
710
Mathieu Chartier901e0702016-02-19 13:42:48 -0800711bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800712 bool early_exit = false;
713 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800714 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800715}
716
Mathieu Chartier901e0702016-02-19 13:42:48 -0800717bool ImageWriter::PruneAppImageClassInternal(
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800718 mirror::Class* klass,
719 bool* early_exit,
720 std::unordered_set<mirror::Class*>* visited) {
721 DCHECK(early_exit != nullptr);
722 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800723 DCHECK(compile_app_image_);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800724 if (klass == nullptr || IsInBootImage(klass)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700725 return false;
726 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800727 auto found = prune_class_memo_.find(klass);
728 if (found != prune_class_memo_.end()) {
729 // Already computed, return the found value.
730 return found->second;
731 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800732 // Circular dependencies, return false but do not store the result in the memoization table.
733 if (visited->find(klass) != visited->end()) {
734 *early_exit = true;
735 return false;
736 }
737 visited->emplace(klass);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800738 bool result = IsBootClassLoaderClass(klass);
739 std::string temp;
740 // Prune if not an image class, this handles any broken sets of image classes such as having a
741 // class in the set but not it's superclass.
742 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800743 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800744 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
745 // app image.
746 if (klass->GetStatus() == mirror::Class::kStatusError) {
747 result = true;
748 } else {
749 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
750 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800751 if (!result) {
752 // Check interfaces since these wont be visited through VisitReferences.)
753 mirror::IfTable* if_table = klass->GetIfTable();
754 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800755 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
756 &my_early_exit,
757 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800758 }
759 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800760 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800761 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
762 &my_early_exit,
763 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800764 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800765 // Check static fields and their classes.
766 size_t num_static_fields = klass->NumReferenceStaticFields();
767 if (num_static_fields != 0 && klass->IsResolved()) {
768 // Presumably GC can happen when we are cross compiling, it should not cause performance
769 // problems to do pointer size logic.
770 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
771 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
772 for (size_t i = 0u; i < num_static_fields; ++i) {
773 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
774 if (ref != nullptr) {
775 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800776 result = result || PruneAppImageClassInternal(ref->AsClass(),
777 &my_early_exit,
778 visited);
779 } else {
780 result = result || PruneAppImageClassInternal(ref->GetClass(),
781 &my_early_exit,
782 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800783 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800784 }
785 field_offset = MemberOffset(field_offset.Uint32Value() +
786 sizeof(mirror::HeapReference<mirror::Object>));
787 }
788 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800789 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
790 &my_early_exit,
791 visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800792 // Erase the element we stored earlier since we are exiting the function.
793 auto it = visited->find(klass);
794 DCHECK(it != visited->end());
795 visited->erase(it);
796 // Only store result if it is true or none of the calls early exited due to circular
797 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
798 // a child call and we can remember the result.
799 if (result == true || !my_early_exit || visited->empty()) {
800 prune_class_memo_[klass] = result;
801 }
802 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800803 return result;
804}
805
806bool ImageWriter::KeepClass(Class* klass) {
807 if (klass == nullptr) {
808 return false;
809 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800810 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
811 // Already in boot image, return true.
812 return true;
813 }
814 std::string temp;
815 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
816 return false;
817 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800818 if (compile_app_image_) {
819 // For app images, we need to prune boot loader classes that are not in the boot image since
820 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800821 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800822 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800823 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800824 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700825}
826
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700827class NonImageClassesVisitor : public ClassVisitor {
828 public:
829 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
830
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700831 bool operator()(Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800832 if (!image_writer_->KeepClass(klass)) {
833 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700834 }
835 return true;
836 }
837
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800838 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700839 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700840};
841
842void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700843 Runtime* runtime = Runtime::Current();
844 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700845 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700846
Mathieu Chartier696632e2016-06-03 17:47:32 -0700847 // Clear class table strong roots so that dex caches can get pruned. We require pruning the class
848 // path dex caches.
849 class_linker->ClearClassTableStrongRoots();
850
Brian Carlstrom7940e442013-07-12 13:46:57 -0700851 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700852 NonImageClassesVisitor visitor(this);
853 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700854
855 // Remove the undesired classes from the class roots.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800856 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800857 for (mirror::Class* klass : visitor.classes_to_prune_) {
858 std::string temp;
859 const char* name = klass->GetDescriptor(&temp);
860 VLOG(compiler) << "Pruning class " << name;
861 if (!compile_app_image_) {
862 DCHECK(IsBootClassLoaderClass(klass));
863 }
864 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800865 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700866 }
867
868 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100869 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700870
Mathieu Chartier268764d2016-09-13 12:09:38 -0700871 ScopedAssertNoThreadSuspension sa(__FUNCTION__);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700872 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
873 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800874 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800875 if (self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700876 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700877 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800878 mirror::DexCache* dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700879 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
880 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800881 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700882 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700883 }
884 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100885 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
886 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
887 ArtMethod* method =
888 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800889 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
890 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800891 // 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 -0800892 // declaring class which is an image class. Set it to the resolution method to be safe and
893 // prevent dangling pointers.
Alex Light36121492016-02-22 13:43:29 -0800894 if (method->IsCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800895 mirror::DexCache::SetElementPtrSize(resolved_methods,
896 i,
897 resolution_method,
898 target_ptr_size_);
899 } else {
900 // Check that the class is still in the classes table.
901 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
902 << PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700903 }
904 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800905 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700906 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800907 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800908 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700909 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700910 }
911 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700912 // Clean the dex field. It might have been populated during the initialization phase, but
913 // contains data only valid during a real run.
914 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700915 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700916
917 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
918 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800919
920 // Clear to save RAM.
921 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700922}
923
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800924void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700925 if (compiler_driver_.GetImageClasses() != nullptr) {
926 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700927 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700928 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700929}
930
931void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
932 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800933 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700934 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800935 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700936 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700937 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800938 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
939 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700940 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700941 }
942}
943
944void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700945 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700946 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700947 for (const std::string& image_class : *image_classes) {
948 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700949 }
950}
951
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800952mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
953 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +0000954 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800955 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
956 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
957 << string->ToModifiedUtf8();
958 if (found != nullptr) {
959 return found;
960 }
961 }
962 if (compile_app_image_) {
963 Runtime* const runtime = Runtime::Current();
964 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
965 // If we found it in the runtime intern table it could either be in the boot image or interned
966 // during app image compilation. If it was in the boot image return that, otherwise return null
967 // since it belongs to another image space.
968 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
969 return found;
970 }
971 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
972 << string->ToModifiedUtf8();
973 }
974 return nullptr;
975}
976
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800977void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700978 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700979 // if it is a string, we want to intern it if its not interned.
980 if (obj->GetClass()->IsStringClass()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000981 size_t oat_index = GetOatIndex(obj);
982 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800983
Brian Carlstrom7940e442013-07-12 13:46:57 -0700984 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800985 if (IsImageBinSlotAssigned(obj)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800986 DCHECK_EQ(obj, FindInternedString(obj->AsString()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700987 return;
988 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800989 // Need to check if the string is already interned in another image info so that we don't have
990 // the intern tables of two different images contain the same string.
991 mirror::String* interned = FindInternedString(obj->AsString());
992 if (interned == nullptr) {
993 // Not in another image space, insert to our table.
994 interned = image_info.intern_table_->InternStrongImageString(obj->AsString());
995 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700996 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800997 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700998 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800999 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001000 }
1001 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001002 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001003 return;
1004 }
1005 // else (obj == interned), nothing to do but fall through to the normal case
1006 }
1007
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001008 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001009}
1010
Vladimir Marko944da602016-02-19 12:27:55 +00001011ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001012 Runtime* runtime = Runtime::Current();
1013 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001014 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001015 StackHandleScope<3> hs(self);
1016 Handle<Class> object_array_class(hs.NewHandle(
1017 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001018
Jeff Haodcdc85b2015-12-04 14:06:18 -08001019 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +00001020 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001021 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +00001022 size_t image_oat_index = pair.second;
1023 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001024 image_dex_files.insert(image_dex_file);
1025 }
1026 }
1027
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001028 // build an Object[] of all the DexCaches used in the source_space_.
1029 // Since we can't hold the dex lock when allocating the dex_caches
1030 // ObjectArray, we lock the dex lock twice, first to get the number
1031 // of dex caches first and then lock it again to copy the dex
1032 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001033 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001034 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001035 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001036 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001037 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1038 mirror::DexCache* dex_cache =
1039 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001040 if (dex_cache == nullptr) {
1041 continue;
1042 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001043 const DexFile* dex_file = dex_cache->GetDexFile();
1044 if (!IsInBootImage(dex_cache)) {
1045 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1046 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001047 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001048 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001049 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001050 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001051 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1052 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001053 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001054 size_t non_image_dex_caches = 0;
1055 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001056 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1057 mirror::DexCache* dex_cache =
1058 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001059 if (dex_cache == nullptr) {
1060 continue;
1061 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001062 const DexFile* dex_file = dex_cache->GetDexFile();
1063 if (!IsInBootImage(dex_cache)) {
1064 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1065 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001066 }
1067 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1068 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001069 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001070 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1071 mirror::DexCache* dex_cache =
1072 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001073 if (dex_cache == nullptr) {
1074 continue;
1075 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001076 const DexFile* dex_file = dex_cache->GetDexFile();
1077 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001078 dex_caches->Set<false>(i, dex_cache);
1079 ++i;
1080 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001081 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001082 }
1083
1084 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001085 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001086 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001087 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001088 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001089 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001090 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001091 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001092 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001093}
1094
Mathieu Chartier590fee92013-09-13 13:46:47 -07001095// Walk instance fields of the given Class. Separate function to allow recursion on the super
1096// class.
1097void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1098 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001099 StackHandleScope<1> hs(Thread::Current());
1100 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1101 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001102 if (super != nullptr) {
1103 WalkInstanceFields(obj, super);
1104 }
1105 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001106 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +00001107 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001108 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001109 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001110 if (value != nullptr) {
1111 WalkFieldsInOrder(value);
1112 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001113 field_offset = MemberOffset(field_offset.Uint32Value() +
1114 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001115 }
1116}
1117
1118// For an unvisited object, visit it then all its children found via fields.
1119void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001120 if (IsInBootImage(obj)) {
1121 // Object is in the image, don't need to fix it up.
1122 return;
1123 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001124 // Use our own visitor routine (instead of GC visitor) to get better locality between
1125 // an object and its fields
1126 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001127 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001128 StackHandleScope<2> hs(Thread::Current());
1129 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1130 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001131 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001132 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001133 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001134 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001135 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001136 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001137 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001138 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001139 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001140 if (value != nullptr) {
1141 WalkFieldsInOrder(value);
1142 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001143 field_offset = MemberOffset(field_offset.Uint32Value() +
1144 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001145 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001146 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001147 auto* as_klass = h_obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001148 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001149 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1150 if (compile_app_image_) {
1151 // Extra sanity, no boot loader classes should be left!
1152 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1153 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001154 LengthPrefixedArray<ArtField>* fields[] = {
1155 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1156 };
Vladimir Marko944da602016-02-19 12:27:55 +00001157 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1158 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001159 {
1160 // Note: This table is only accessed from the image writer, so the lock is technically
1161 // unnecessary.
1162 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1163 // Insert in the class table for this iamge.
1164 image_info.class_table_->Insert(as_klass);
1165 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001166 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1167 // Total array length including header.
1168 if (cur_fields != nullptr) {
1169 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1170 // Forward the entire array at once.
1171 auto it = native_object_relocations_.find(cur_fields);
1172 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1173 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001174 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001175 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001176 native_object_relocations_.emplace(
1177 cur_fields,
1178 NativeObjectRelocation {
1179 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1180 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001181 offset += header_size;
1182 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001183 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001184 // Need to forward arrays separate of fields.
1185 ArtField* field = &cur_fields->At(i);
1186 auto it2 = native_object_relocations_.find(field);
1187 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1188 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001189 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001190 native_object_relocations_.emplace(
1191 field,
1192 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001193 offset += sizeof(ArtField);
1194 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001195 }
1196 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001197 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001198 size_t num_methods = as_klass->NumMethods();
1199 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001200 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001201 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1202 if (WillMethodBeDirty(&m)) {
1203 any_dirty = true;
1204 break;
1205 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001206 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001207 NativeObjectRelocationType type = any_dirty
1208 ? kNativeObjectRelocationTypeArtMethodDirty
1209 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001210 Bin bin_type = BinTypeForNativeRelocationType(type);
1211 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001212 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1213 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001214 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1215 method_size,
1216 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001217 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001218 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001219 CHECK(it == native_object_relocations_.end())
1220 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001221 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001222 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001223 native_object_relocations_.emplace(array,
1224 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001225 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001226 offset,
1227 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1228 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001229 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001230 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001231 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001232 }
Alex Lighte64300b2015-12-15 15:02:47 -08001233 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001234 }
1235 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1236 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001237 if (as_klass->ShouldHaveImt()) {
1238 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1239 for (size_t i = 0; i < ImTable::kSize; ++i) {
1240 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001241 DCHECK(imt_method != nullptr);
1242 if (imt_method->IsRuntimeMethod() &&
1243 !IsInBootImage(imt_method) &&
1244 !NativeRelocationAssigned(imt_method)) {
1245 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001246 }
1247 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001248 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001249
1250 if (as_klass->ShouldHaveImt()) {
1251 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1252 TryAssignImTableOffset(imt, oat_index);
1253 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001254 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001255 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001256 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001257 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001258 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001259 mirror::Object* value = obj_array->Get(i);
1260 if (value != nullptr) {
1261 WalkFieldsInOrder(value);
1262 }
1263 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001264 } else if (h_obj->IsClassLoader()) {
1265 // Register the class loader if it has a class table.
1266 // The fake boot class loader should not get registered and we should end up with only one
1267 // class loader.
1268 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1269 if (class_loader->GetClassTable() != nullptr) {
1270 class_loaders_.insert(class_loader);
1271 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001272 }
1273 }
1274}
1275
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001276bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1277 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1278}
1279
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001280void ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
1281 // No offset, or already assigned.
1282 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
1283 return;
1284 }
1285 // If the method is a conflict method we also want to assign the conflict table offset.
1286 ImageInfo& image_info = GetImageInfo(oat_index);
1287 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1288 native_object_relocations_.emplace(
1289 imt,
1290 NativeObjectRelocation {
1291 oat_index,
1292 image_info.bin_slot_sizes_[kBinImTable],
1293 kNativeObjectRelocationTypeIMTable});
1294 image_info.bin_slot_sizes_[kBinImTable] += size;
1295}
1296
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001297void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1298 // No offset, or already assigned.
1299 if (table == nullptr || NativeRelocationAssigned(table)) {
1300 return;
1301 }
1302 CHECK(!IsInBootImage(table));
1303 // If the method is a conflict method we also want to assign the conflict table offset.
1304 ImageInfo& image_info = GetImageInfo(oat_index);
1305 const size_t size = table->ComputeSize(target_ptr_size_);
1306 native_object_relocations_.emplace(
1307 table,
1308 NativeObjectRelocation {
1309 oat_index,
1310 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1311 kNativeObjectRelocationTypeIMTConflictTable});
1312 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1313}
1314
Jeff Haodcdc85b2015-12-04 14:06:18 -08001315void ImageWriter::AssignMethodOffset(ArtMethod* method,
1316 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001317 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001318 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001319 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001320 << PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001321 if (method->IsRuntimeMethod()) {
1322 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1323 }
Vladimir Marko944da602016-02-19 12:27:55 +00001324 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001325 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001326 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001327 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001328}
1329
Mathieu Chartier590fee92013-09-13 13:46:47 -07001330void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1331 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1332 DCHECK(writer != nullptr);
1333 writer->WalkFieldsInOrder(obj);
1334}
1335
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001336void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1337 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1338 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001339 if (!writer->IsInBootImage(obj)) {
1340 writer->UnbinObjectsIntoOffset(obj);
1341 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001342}
1343
1344void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001345 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001346 CHECK(obj != nullptr);
1347
1348 // We know the bin slot, and the total bin sizes for all objects by now,
1349 // so calculate the object's final image offset.
1350
1351 DCHECK(IsImageBinSlotAssigned(obj));
1352 BinSlot bin_slot = GetImageBinSlot(obj);
1353 // Change the lockword from a bin slot into an offset
1354 AssignImageOffset(obj, bin_slot);
1355}
1356
Vladimir Markof4da6752014-08-01 19:04:18 +01001357void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001358 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001359 StackHandleScopeCollection handles(self);
1360 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001361 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1362 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001363 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001364
Mathieu Chartiere401d142015-04-22 13:56:20 -07001365 auto* runtime = Runtime::Current();
1366 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001367
Mathieu Chartier31e89252013-08-28 11:29:12 -07001368 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001369 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001370 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001371
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001372 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001373 // Write the image runtime methods.
1374 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1375 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1376 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001377 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
1378 runtime->GetCalleeSaveMethod(Runtime::kSaveAllCalleeSaves);
1379 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
1380 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsOnly);
1381 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
1382 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001383 image_methods_[ImageHeader::kSaveEverythingMethod] =
1384 runtime->GetCalleeSaveMethod(Runtime::kSaveEverything);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001385 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001386 for (auto* m : image_methods_) {
1387 CHECK(m != nullptr);
1388 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001389 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1390 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001391 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001392 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001393 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001394
1395 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1396 heap->VisitObjects(WalkFieldsCallback, this);
1397
Vladimir Marko05792b92015-08-03 11:56:49 +01001398 // Calculate size of the dex cache arrays slot and prepare offsets.
1399 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001400
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001401 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001402 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001403 // Calculate how big the intern table will be after being serialized.
1404 InternTable* const intern_table = image_info.intern_table_.get();
1405 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1406 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001407 // Calculate the size of the class table.
1408 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1409 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001410 }
1411
Vladimir Markocf36d492015-08-12 19:27:26 +01001412 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001413 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001414 size_t bin_offset = image_objects_offset_begin_;
1415 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001416 switch (i) {
1417 case kBinArtMethodClean:
1418 case kBinArtMethodDirty: {
1419 bin_offset = RoundUp(bin_offset, method_alignment);
1420 break;
1421 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001422 case kBinDexCacheArray:
1423 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment());
1424 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001425 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001426 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001427 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001428 break;
1429 }
1430 default: {
1431 // Normal alignment.
1432 }
1433 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001434 image_info.bin_slot_offsets_[i] = bin_offset;
1435 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001436 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001437 // NOTE: There may be additional padding between the bin slots and the intern table.
1438 DCHECK_EQ(image_info.image_end_,
1439 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001440 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001441
Jeff Haodcdc85b2015-12-04 14:06:18 -08001442 // Calculate image offsets.
1443 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001444 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001445 image_info.image_begin_ = global_image_begin_ + image_offset;
1446 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001447 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001448 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001449 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001450 image_offset += image_info.image_size_;
1451 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001452
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001453 // Transform each object's bin slot into an offset which will be used to do the final copy.
1454 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001455
Jeff Haodcdc85b2015-12-04 14:06:18 -08001456 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001457
Jeff Haodcdc85b2015-12-04 14:06:18 -08001458 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001459 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001460 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1461 i++;
1462 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001463
Mathieu Chartiere401d142015-04-22 13:56:20 -07001464 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001465 for (auto& pair : native_object_relocations_) {
1466 NativeObjectRelocation& relocation = pair.second;
1467 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001468 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001469 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001470 }
1471
Jeff Haodcdc85b2015-12-04 14:06:18 -08001472 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001473}
1474
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001475size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001476 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001477
1478 // Do not round up any sections here that are represented by the bins since it will break
1479 // offsets.
1480
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001481 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001482 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001483 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001484
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001485 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001486 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1487 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001488 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001489
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001490 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001491 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1492 *methods_section = ImageSection(
1493 bin_slot_offsets_[kBinArtMethodClean],
1494 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1495
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001496 // IMT section.
1497 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1498 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1499
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001500 // Conflict tables section.
1501 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1502 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1503 bin_slot_sizes_[kBinIMTConflictTable]);
1504
1505 // Runtime methods section.
1506 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1507 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1508 bin_slot_sizes_[kBinRuntimeMethod]);
1509
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001510 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001511 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1512 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1513 bin_slot_sizes_[kBinDexCacheArray]);
1514
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001515 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001516 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001517 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001518 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001519 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1520 cur_pos = interned_strings_section->End();
1521 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1522 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1523 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001524 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001525 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001526 cur_pos = class_table_section->End();
1527 // Image end goes right before the start of the image bitmap.
1528 return cur_pos;
1529}
1530
Vladimir Marko944da602016-02-19 12:27:55 +00001531void ImageWriter::CreateHeader(size_t oat_index) {
1532 ImageInfo& image_info = GetImageInfo(oat_index);
1533 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1534 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1535 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001536
1537 // Create the image sections.
1538 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001539 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001540
Mathieu Chartiere401d142015-04-22 13:56:20 -07001541 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001542 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001543 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001544 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001545 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001546 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001547 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001548 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001549 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1550 ++idx;
1551 }
1552 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001553 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1554 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1555 << " Image offset=" << image_info.image_offset_ << std::dec;
1556 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1557 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1558 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1559 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001560 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001561 // Store boot image info for app image so that we can relocate.
1562 uint32_t boot_image_begin = 0;
1563 uint32_t boot_image_end = 0;
1564 uint32_t boot_oat_begin = 0;
1565 uint32_t boot_oat_end = 0;
1566 gc::Heap* const heap = Runtime::Current()->GetHeap();
1567 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001568
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001569 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1570 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001571 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1572 image_end,
1573 sections,
1574 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001575 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001576 PointerToLowMemUInt32(oat_file_begin),
1577 PointerToLowMemUInt32(image_info.oat_data_begin_),
1578 PointerToLowMemUInt32(oat_data_end),
1579 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001580 boot_image_begin,
1581 boot_image_end - boot_image_begin,
1582 boot_oat_begin,
1583 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001584 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001585 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001586 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001587 image_storage_mode_,
1588 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001589}
1590
1591ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001592 auto it = native_object_relocations_.find(method);
1593 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001594 size_t oat_index = GetOatIndex(method->GetDexCache());
1595 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001596 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1597 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001598}
1599
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001600class FixupRootVisitor : public RootVisitor {
1601 public:
1602 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1603 }
1604
1605 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001606 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001607 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001608 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001609 }
1610 }
1611
1612 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1613 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001614 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001615 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001616 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001617 }
1618 }
1619
1620 private:
1621 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001622};
1623
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001624void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
1625 for (size_t i = 0; i < ImTable::kSize; ++i) {
1626 ArtMethod* method = orig->Get(i, target_ptr_size_);
1627 copy->Set(i, NativeLocationInImage(method), target_ptr_size_);
1628 }
1629}
1630
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001631void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
1632 const size_t count = orig->NumEntries(target_ptr_size_);
1633 for (size_t i = 0; i < count; ++i) {
1634 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
1635 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
1636 copy->SetInterfaceMethod(i, target_ptr_size_, NativeLocationInImage(interface_method));
1637 copy->SetImplementationMethod(i,
1638 target_ptr_size_,
1639 NativeLocationInImage(implementation_method));
1640 }
1641}
1642
Vladimir Marko944da602016-02-19 12:27:55 +00001643void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001644 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001645 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001646 for (auto& pair : native_object_relocations_) {
1647 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001648 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001649 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001650 continue;
1651 }
1652 auto* dest = image_info.image_->Begin() + relocation.offset;
1653 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001654 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001655 switch (relocation.type) {
1656 case kNativeObjectRelocationTypeArtField: {
1657 memcpy(dest, pair.first, sizeof(ArtField));
1658 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1659 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1660 break;
1661 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001662 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001663 case kNativeObjectRelocationTypeArtMethodClean:
1664 case kNativeObjectRelocationTypeArtMethodDirty: {
1665 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001666 reinterpret_cast<ArtMethod*>(dest),
1667 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001668 break;
1669 }
1670 // For arrays, copy just the header since the elements will get copied by their corresponding
1671 // relocations.
1672 case kNativeObjectRelocationTypeArtFieldArray: {
1673 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1674 break;
1675 }
1676 case kNativeObjectRelocationTypeArtMethodArrayClean:
1677 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00001678 size_t size = ArtMethod::Size(target_ptr_size_);
1679 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1680 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1681 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1682 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001683 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00001684 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001685 case kNativeObjectRelocationTypeDexCacheArray:
1686 // Nothing to copy here, everything is done in FixupDexCache().
1687 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001688 case kNativeObjectRelocationTypeIMTable: {
1689 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
1690 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
1691 CopyAndFixupImTable(orig_imt, dest_imt);
1692 break;
1693 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001694 case kNativeObjectRelocationTypeIMTConflictTable: {
1695 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
1696 CopyAndFixupImtConflictTable(
1697 orig_table,
1698 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
1699 break;
1700 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001701 }
1702 }
1703 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001704 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001705 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001706 ArtMethod* method = image_methods_[i];
1707 CHECK(method != nullptr);
1708 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001709 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001710 }
1711 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001712 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001713 FixupRootVisitor root_visitor(this);
1714
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001715 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001716 if (image_info.intern_table_bytes_ > 0) {
1717 const ImageSection& intern_table_section = image_header->GetImageSection(
1718 ImageHeader::kSectionInternedStrings);
1719 InternTable* const intern_table = image_info.intern_table_.get();
1720 uint8_t* const intern_table_memory_ptr =
1721 image_info.image_->Begin() + intern_table_section.Offset();
1722 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1723 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1724 // Fixup the pointers in the newly written intern table to contain image addresses.
1725 InternTable temp_intern_table;
1726 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1727 // the VisitRoots() will update the memory directly rather than the copies.
1728 // This also relies on visit roots not doing any verification which could fail after we update
1729 // the roots to be the image addresses.
1730 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1731 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1732 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1733 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001734 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1735 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001736 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001737 const ImageSection& class_table_section = image_header->GetImageSection(
1738 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001739 uint8_t* const class_table_memory_ptr =
1740 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001741 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001742
1743 ClassTable* table = image_info.class_table_.get();
1744 CHECK(table != nullptr);
1745 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1746 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1747 // Fixup the pointers in the newly written class table to contain image addresses. See
1748 // above comment for intern tables.
1749 ClassTable temp_class_table;
1750 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1751 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1752 table->NumZygoteClasses());
1753 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1754 RootInfo(kRootUnknown));
1755 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001756 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001757}
1758
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001759void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001760 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001761 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1762 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001763 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001764 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001765 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1766 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001767 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001768 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001769}
1770
Mathieu Chartier590fee92013-09-13 13:46:47 -07001771void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001772 DCHECK(obj != nullptr);
1773 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001774 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1775}
1776
Mathieu Chartiere401d142015-04-22 13:56:20 -07001777void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1778 mirror::Class* klass, Bin array_type) {
1779 CHECK(klass->IsArrayClass());
1780 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1781 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001782 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001783 dst->SetClass(GetImageAddress(arr->GetClass()));
1784 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001785 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001786 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1787 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001788 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001789 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001790 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001791 auto* method = reinterpret_cast<ArtMethod*>(elem);
1792 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1793 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1794 << PrettyClass(method->GetDeclaringClass());
1795 } else {
1796 CHECK_EQ(array_type, kBinArtField);
1797 auto* field = reinterpret_cast<ArtField*>(elem);
1798 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1799 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1800 << PrettyClass(field->GetDeclaringClass());
1801 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001802 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001803 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001804 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001805 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001806 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001807 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001808 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001809 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001810}
1811
1812void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001813 if (IsInBootImage(obj)) {
1814 return;
1815 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001816 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001817 size_t oat_index = GetOatIndex(obj);
1818 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001819 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1820 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001821 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001822
Jeff Haodcdc85b2015-12-04 14:06:18 -08001823 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001824
1825 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001826 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001827 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001828
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001829 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1830 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001831 const auto it = saved_hashcode_map_.find(obj);
1832 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1833 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001834 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
1835 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
1836 // safe since we mark all of the objects that may reference non immune objects as gray.
1837 CHECK(dst->AtomicSetMarkBit(0, 1));
1838 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001839 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001840}
1841
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001842// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001843class FixupVisitor {
1844 public:
1845 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1846 }
1847
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001848 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1849 // with other logic.
1850 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1851 const {}
1852 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1853
1854
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001855 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001856 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001857 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001858 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1859 // image.
1860 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001861 offset,
1862 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001863 }
1864
1865 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001866 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001867 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001868 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001869 mirror::Reference::ReferentOffset(),
1870 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001871 }
1872
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001873 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001874 ImageWriter* const image_writer_;
1875 mirror::Object* const copy_;
1876};
1877
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001878class FixupClassVisitor FINAL : public FixupVisitor {
1879 public:
1880 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1881 }
1882
Mathieu Chartierc7853442015-03-27 14:35:38 -07001883 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001884 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001885 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001886 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001887 }
1888
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001889 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1890 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001891 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001892 LOG(FATAL) << "Reference not expected here.";
1893 }
1894};
1895
Vladimir Marko05792b92015-08-03 11:56:49 +01001896uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1897 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001898 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001899 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001900 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1901 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001902 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001903 return relocation.offset;
1904}
1905
1906template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001907std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001908 std::ostringstream oss;
1909 oss << ptr;
1910 return oss.str();
1911}
1912
1913template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001914std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001915 return PrettyMethod(method);
1916}
1917
1918template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001919T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001920 if (obj == nullptr || IsInBootImage(obj)) {
1921 return obj;
1922 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001923 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001924 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
1925 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001926 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00001927 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001928 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001929 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001930}
1931
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001932template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001933T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1934 if (obj == nullptr || IsInBootImage(obj)) {
1935 return obj;
1936 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001937 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1938 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001939 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1940 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001941}
1942
1943class NativeLocationVisitor {
1944 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001945 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001946
1947 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001948 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001949 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001950 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001951
1952 private:
1953 ImageWriter* const image_writer_;
1954};
1955
1956void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001957 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001958 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001959 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001960
1961 // Remove the clinitThreadId. This is required for image determinism.
1962 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001963}
1964
Ian Rogersef7d42f2014-01-06 12:55:46 -08001965void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001966 DCHECK(orig != nullptr);
1967 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001968 if (kUseBakerOrBrooksReadBarrier) {
1969 orig->AssertReadBarrierPointer();
1970 if (kUseBrooksReadBarrier) {
1971 // Note the address 'copy' isn't the same as the image address of 'orig'.
1972 copy->SetReadBarrierPointer(GetImageAddress(orig));
1973 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1974 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001975 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001976 auto* klass = orig->GetClass();
1977 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001978 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001979 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1980 if (it != pointer_arrays_.end()) {
1981 // Should only need to fixup every pointer array exactly once.
1982 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1983 pointer_arrays_.erase(it);
1984 return;
1985 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001986 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001987 if (orig->IsClass()) {
1988 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001989 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001990 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1991 // Need to go update the ArtMethod.
1992 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1993 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1994 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05001995 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01001996 } else if (!klass->IsArrayClass()) {
1997 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1998 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1999 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002000 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002001 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002002 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2003 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002004 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002005 // Also set allocator to null to be safe. The allocator is created when we create the class
2006 // table. We also never expect to unload things in the image since they are held live as
2007 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002008 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002009 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002010 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002011 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002012 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002013 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002014}
2015
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002016
2017class ImageAddressVisitor {
2018 public:
2019 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
2020
2021 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002022 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002023 return image_writer_->GetImageAddress(ptr);
2024 }
2025
2026 private:
2027 ImageWriter* const image_writer_;
2028};
2029
2030
Vladimir Marko05792b92015-08-03 11:56:49 +01002031void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2032 mirror::DexCache* copy_dex_cache) {
2033 // Though the DexCache array fields are usually treated as native pointers, we set the full
2034 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2035 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2036 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002037 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002038 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002039 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002040 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002041 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002042 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
2043 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002044 }
2045 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
2046 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002047 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002048 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002049 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002050 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
2051 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002052 }
2053 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
2054 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002055 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002056 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002057 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002058 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002059 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
2060 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002061 // NativeLocationInImage also handles runtime methods since these have relocation info.
2062 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002063 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
2064 }
2065 }
2066 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
2067 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002068 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002069 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002070 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002071 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002072 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
2073 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002074 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002075 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
2076 }
2077 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002078
2079 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2080 // compiler pointers in here will make the output non-deterministic.
2081 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002082}
2083
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002084const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2085 DCHECK_LT(type, kOatAddressCount);
2086 // If we are compiling an app image, we need to use the stubs of the boot image.
2087 if (compile_app_image_) {
2088 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002089 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002090 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2091 DCHECK(!image_spaces.empty());
2092 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002093 CHECK(oat_file != nullptr);
2094 const OatHeader& header = oat_file->GetOatHeader();
2095 switch (type) {
2096 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2097 case kOatAddressQuickGenericJNITrampoline:
2098 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2099 case kOatAddressInterpreterToInterpreterBridge:
2100 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2101 case kOatAddressInterpreterToCompiledCodeBridge:
2102 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2103 case kOatAddressJNIDlsymLookup:
2104 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2105 case kOatAddressQuickIMTConflictTrampoline:
2106 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2107 case kOatAddressQuickResolutionTrampoline:
2108 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2109 case kOatAddressQuickToInterpreterBridge:
2110 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2111 default:
2112 UNREACHABLE();
2113 }
2114 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002115 const ImageInfo& primary_image_info = GetImageInfo(0);
2116 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002117}
2118
Jeff Haodcdc85b2015-12-04 14:06:18 -08002119const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2120 const ImageInfo& image_info,
2121 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002122 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
Nicolas Geoffray796d6302016-03-13 22:22:31 +00002123 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002124 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07002125 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002126 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002127
2128 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2129 // trampoline.
2130
2131 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002132 const void* quick_oat_entry_point =
2133 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2134 const uint8_t* quick_code;
2135
2136 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2137 DCHECK(method->IsCopied());
2138 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2139 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2140 } else {
2141 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2142 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2143 }
2144
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002145 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002146 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2147 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002148 // We have code for a non-static or initialized method, just use the code.
2149 } else if (quick_code == nullptr && method->IsNative() &&
2150 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2151 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002152 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002153 } else if (quick_code == nullptr && !method->IsNative()) {
2154 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002155 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002156 *quick_is_interpreted = true;
2157 } else {
2158 CHECK(!method->GetDeclaringClass()->IsInitialized());
2159 // We have code for a static method, but need to go through the resolution stub for class
2160 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002161 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2162 }
2163 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002164 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002165 }
2166 return quick_code;
2167}
2168
Jeff Haodcdc85b2015-12-04 14:06:18 -08002169void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2170 ArtMethod* copy,
2171 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002172 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002173
2174 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002175 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002176 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002177 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002178 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002179
Ian Rogers848871b2013-08-05 10:56:33 -07002180 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2181 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002182
Ian Rogers848871b2013-08-05 10:56:33 -07002183 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002184 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002185 if (orig->IsRuntimeMethod()) {
2186 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2187 if (orig_table != nullptr) {
2188 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2189 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2190 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2191 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2192 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2193 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2194 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2195 } else {
2196 bool found_one = false;
2197 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2198 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2199 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2200 found_one = true;
2201 break;
2202 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002203 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002204 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2205 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002206 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002207 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002208 // We assume all methods have code. If they don't currently then we set them to the use the
2209 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2210 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002211 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002212 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002213 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002214 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002215 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002216 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002217 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002218
Sebastien Hertze1d07812014-05-21 15:44:09 +02002219 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002220 if (orig->IsNative()) {
2221 // The native method's pointer is set to a stub to lookup via dlsym.
2222 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002223 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002224 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002225 }
2226 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002227 }
2228}
2229
Jeff Haodcdc85b2015-12-04 14:06:18 -08002230size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002231 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002232 return std::accumulate(&image_info.bin_slot_sizes_[0],
2233 &image_info.bin_slot_sizes_[up_to],
2234 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002235}
2236
2237ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2238 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002239 static_assert(kBinBits == 3, "wrong number of bin bits");
2240 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002241 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2242
2243 DCHECK_LT(GetBin(), kBinSize);
2244 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2245}
2246
2247ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2248 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2249 DCHECK_EQ(index, GetIndex());
2250}
2251
2252ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2253 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2254}
2255
2256uint32_t ImageWriter::BinSlot::GetIndex() const {
2257 return lockword_ & ~kBinMask;
2258}
2259
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002260ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2261 switch (type) {
2262 case kNativeObjectRelocationTypeArtField:
2263 case kNativeObjectRelocationTypeArtFieldArray:
2264 return kBinArtField;
2265 case kNativeObjectRelocationTypeArtMethodClean:
2266 case kNativeObjectRelocationTypeArtMethodArrayClean:
2267 return kBinArtMethodClean;
2268 case kNativeObjectRelocationTypeArtMethodDirty:
2269 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2270 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002271 case kNativeObjectRelocationTypeDexCacheArray:
2272 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002273 case kNativeObjectRelocationTypeRuntimeMethod:
2274 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002275 case kNativeObjectRelocationTypeIMTable:
2276 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002277 case kNativeObjectRelocationTypeIMTConflictTable:
2278 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002279 }
2280 UNREACHABLE();
2281}
2282
Vladimir Marko944da602016-02-19 12:27:55 +00002283size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002284 if (compile_app_image_) {
Vladimir Marko944da602016-02-19 12:27:55 +00002285 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002286 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002287 mirror::DexCache* dex_cache =
2288 obj->IsDexCache() ? obj->AsDexCache()
2289 : obj->IsClass() ? obj->AsClass()->GetDexCache()
2290 : obj->GetClass()->GetDexCache();
2291 return GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002292 }
2293}
2294
Vladimir Marko944da602016-02-19 12:27:55 +00002295size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
2296 if (compile_app_image_) {
2297 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002298 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002299 auto it = dex_file_oat_index_map_.find(dex_file);
2300 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002301 return it->second;
2302 }
2303}
2304
Vladimir Marko944da602016-02-19 12:27:55 +00002305size_t ImageWriter::GetOatIndexForDexCache(mirror::DexCache* dex_cache) const {
2306 if (dex_cache == nullptr) {
2307 return GetDefaultOatIndex();
2308 } else {
2309 return GetOatIndexForDexFile(dex_cache->GetDexFile());
2310 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002311}
2312
Vladimir Marko944da602016-02-19 12:27:55 +00002313void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2314 size_t oat_loaded_size,
2315 size_t oat_data_offset,
2316 size_t oat_data_size) {
2317 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2318 for (const ImageInfo& info : image_infos_) {
2319 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2320 }
2321 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002322
Vladimir Marko944da602016-02-19 12:27:55 +00002323 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2324 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2325 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2326 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2327 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002328
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002329 if (compile_app_image_) {
2330 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2331 return;
2332 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002333
2334 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002335 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002336 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002337 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002338 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2339 }
2340}
2341
Vladimir Marko944da602016-02-19 12:27:55 +00002342void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2343 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2344 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2345
2346 if (oat_index == GetDefaultOatIndex()) {
2347 // Primary oat file, read the trampolines.
2348 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2349 oat_header.GetInterpreterToInterpreterBridgeOffset();
2350 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2351 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2352 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2353 oat_header.GetJniDlsymLookupOffset();
2354 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2355 oat_header.GetQuickGenericJniTrampolineOffset();
2356 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2357 oat_header.GetQuickImtConflictTrampolineOffset();
2358 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2359 oat_header.GetQuickResolutionTrampolineOffset();
2360 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2361 oat_header.GetQuickToInterpreterBridgeOffset();
2362 }
2363}
2364
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002365ImageWriter::ImageWriter(
2366 const CompilerDriver& compiler_driver,
2367 uintptr_t image_begin,
2368 bool compile_pic,
2369 bool compile_app_image,
2370 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002371 const std::vector<const char*>& oat_filenames,
2372 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002373 : compiler_driver_(compiler_driver),
2374 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2375 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002376 compile_pic_(compile_pic),
2377 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002378 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002379 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002380 dirty_methods_(0u),
2381 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002382 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002383 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002384 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002385 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002386 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002387 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2388 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002389}
2390
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002391ImageWriter::ImageInfo::ImageInfo()
2392 : intern_table_(new InternTable),
2393 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002394
Brian Carlstrom7940e442013-07-12 13:46:57 -07002395} // namespace art