blob: 063eb11718b814804f7c0d6243b57db6bd33cc9c [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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070042#include "gc/heap.h"
43#include "gc/space/large_object_space.h"
44#include "gc/space/space-inl.h"
45#include "globals.h"
46#include "image.h"
47#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070048#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070049#include "lock_word.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070050#include "mirror/abstract_method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "mirror/array-inl.h"
52#include "mirror/class-inl.h"
53#include "mirror/class_loader.h"
54#include "mirror/dex_cache-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070055#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "mirror/object-inl.h"
57#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070058#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "oat.h"
60#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070061#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "runtime.h"
63#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070064#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000065#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070067using ::art::mirror::Class;
68using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070069using ::art::mirror::Object;
70using ::art::mirror::ObjectArray;
71using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070072
73namespace art {
74
Igor Murashkinf5b4c502014-11-14 15:01:59 -080075// Separate objects into multiple bins to optimize dirty memory use.
76static constexpr bool kBinObjects = true;
77
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080078// Return true if an object is already in an image space.
79bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080080 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080081 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080082 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080083 return false;
84 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080085 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
86 const uint8_t* image_begin = boot_image_space->Begin();
87 // Real image end including ArtMethods and ArtField sections.
88 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
89 if (image_begin <= obj && obj < image_end) {
90 return true;
91 }
92 }
93 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080094}
95
96bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080097 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080098 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080099 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800100 return false;
101 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800102 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
103 const ImageHeader& image_header = boot_image_space->GetImageHeader();
104 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
105 return true;
106 }
107 }
108 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800109}
110
Andreas Gampedd9d0552015-03-09 12:57:41 -0700111static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700112 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700113 Class* klass = obj->GetClass();
114 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
115}
116
117static void CheckNoDexObjects() {
118 ScopedObjectAccess soa(Thread::Current());
119 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
120}
121
Vladimir Markof4da6752014-08-01 19:04:18 +0100122bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800123 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800124 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100125 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700126 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100127 PruneNonImageClasses(); // Remove junk
Mathieu Chartier901e0702016-02-19 13:42:48 -0800128 if (!compile_app_image_) {
129 // Avoid for app image since this may increase RAM and image size.
130 ComputeLazyFieldsForImageClasses(); // Add useful information
131 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100132 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100133 heap->CollectGarbage(false); // Remove garbage.
134
Andreas Gampedd9d0552015-03-09 12:57:41 -0700135 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
136 // dex files.
137 //
138 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
139 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
140 // true.
141 if (kIsDebugBuild) {
142 CheckNoDexObjects();
143 }
144
Vladimir Markof4da6752014-08-01 19:04:18 +0100145 if (kIsDebugBuild) {
146 ScopedObjectAccess soa(Thread::Current());
147 CheckNonImageClassesRemoved();
148 }
149
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700150 {
151 ScopedObjectAccess soa(Thread::Current());
152 CalculateNewObjectOffsets();
153 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100154
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700155 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
156 // bin size sums being calculated.
157 if (!AllocMemory()) {
158 return false;
159 }
160
Vladimir Markof4da6752014-08-01 19:04:18 +0100161 return true;
162}
163
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700164bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800165 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000166 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800167 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
168 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800169 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800170 if (image_fd != kInvalidFd) {
171 CHECK_EQ(image_filenames.size(), 1u);
172 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800173 CHECK(!oat_filenames.empty());
174 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700175
Vladimir Marko944da602016-02-19 12:27:55 +0000176 {
177 ScopedObjectAccess soa(Thread::Current());
178 for (size_t i = 0; i < oat_filenames.size(); ++i) {
179 CreateHeader(i);
180 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800181 }
182 }
Alex Light53cb16b2014-06-12 11:26:29 -0700183
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700184 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700185 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800186 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700187 Runtime::Current()->GetHeap()->DisableObjectValidation();
188 CopyAndFixupObjects();
189 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190
Jeff Haodcdc85b2015-12-04 14:06:18 -0800191 for (size_t i = 0; i < image_filenames.size(); ++i) {
192 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000193 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800194 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800195 if (image_fd != kInvalidFd) {
196 if (strlen(image_filename) == 0u) {
197 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800198 // Empty the file in case it already exists.
199 if (image_file != nullptr) {
200 TEMP_FAILURE_RETRY(image_file->SetLength(0));
201 TEMP_FAILURE_RETRY(image_file->Flush());
202 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800203 } else {
204 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
205 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800206 } else {
207 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800208 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800209
Jeff Haodcdc85b2015-12-04 14:06:18 -0800210 if (image_file == nullptr) {
211 LOG(ERROR) << "Failed to open image file " << image_filename;
212 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800213 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800214
215 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800216 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
217 image_file->Erase();
218 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800219 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800220
Jeff Haodcdc85b2015-12-04 14:06:18 -0800221 std::unique_ptr<char[]> compressed_data;
222 // Image data size excludes the bitmap and the header.
223 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
224 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
225 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
226 size_t data_size;
227 const char* image_data_to_write;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800228 const uint64_t compress_start_time = NanoTime();
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000229
Jeff Haodcdc85b2015-12-04 14:06:18 -0800230 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
231 switch (image_storage_mode_) {
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700232 case ImageHeader::kStorageModeLZ4HC: // Fall-through.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800233 case ImageHeader::kStorageModeLZ4: {
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800234 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800235 compressed_data.reset(new char[compressed_max_size]);
236 data_size = LZ4_compress(
237 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
238 &compressed_data[0],
239 image_data_size);
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800240
241 break;
242 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700243 /*
244 * Disabled due to image_test64 flakyness. Both use same decompression. b/27560444
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800245 case ImageHeader::kStorageModeLZ4HC: {
246 // Bound is same as non HC.
247 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
248 compressed_data.reset(new char[compressed_max_size]);
249 data_size = LZ4_compressHC(
250 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
251 &compressed_data[0],
252 image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800253 break;
254 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700255 */
Jeff Haodcdc85b2015-12-04 14:06:18 -0800256 case ImageHeader::kStorageModeUncompressed: {
257 data_size = image_data_size;
258 image_data_to_write = image_data;
259 break;
260 }
261 default: {
262 LOG(FATAL) << "Unsupported";
263 UNREACHABLE();
264 }
265 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800266
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800267 if (compressed_data != nullptr) {
268 image_data_to_write = &compressed_data[0];
269 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
270 << PrettyDuration(NanoTime() - compress_start_time);
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700271 if (kIsDebugBuild) {
272 std::unique_ptr<uint8_t[]> temp(new uint8_t[image_data_size]);
273 const size_t decompressed_size = LZ4_decompress_safe(
274 reinterpret_cast<char*>(&compressed_data[0]),
275 reinterpret_cast<char*>(&temp[0]),
276 data_size,
277 image_data_size);
278 CHECK_EQ(decompressed_size, image_data_size);
279 CHECK_EQ(memcmp(image_data, &temp[0], image_data_size), 0) << image_storage_mode_;
280 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800281 }
282
Jeff Haodcdc85b2015-12-04 14:06:18 -0800283 // Write out the image + fields + methods.
284 const bool is_compressed = compressed_data != nullptr;
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800285 if (!image_file->PwriteFully(image_data_to_write, data_size, sizeof(ImageHeader))) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800286 PLOG(ERROR) << "Failed to write image file data " << image_filename;
287 image_file->Erase();
288 return false;
289 }
290
291 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
292 // convenience.
293 const ImageSection& bitmap_section = image_header->GetImageSection(
294 ImageHeader::kSectionImageBitmap);
295 // Align up since data size may be unaligned if the image is compressed.
296 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
297 if (!is_compressed) {
298 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
299 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800300 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
301 bitmap_section.Size(),
302 bitmap_position_in_file)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800303 PLOG(ERROR) << "Failed to write image file " << image_filename;
304 image_file->Erase();
305 return false;
306 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800307
308 int err = image_file->Flush();
309 if (err < 0) {
310 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
311 image_file->Erase();
312 return false;
313 }
314
315 // Write header last in case the compiler gets killed in the middle of image writing.
316 // We do not want to have a corrupted image with a valid header.
317 // The header is uncompressed since it contains whether the image is compressed or not.
318 image_header->data_size_ = data_size;
319 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
320 sizeof(ImageHeader),
321 0)) {
322 PLOG(ERROR) << "Failed to write image file header " << image_filename;
323 image_file->Erase();
324 return false;
325 }
326
Jeff Haodcdc85b2015-12-04 14:06:18 -0800327 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
328 static_cast<size_t>(image_file->GetLength()));
329 if (image_file->FlushCloseOrErase() != 0) {
330 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
331 return false;
332 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800333 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700334 return true;
335}
336
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700337void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700338 DCHECK(object != nullptr);
339 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800340
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800341 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700342 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700343 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700344 DCHECK(IsImageOffsetAssigned(object));
345}
346
Mathieu Chartiere401d142015-04-22 13:56:20 -0700347void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
348 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
349 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
350 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
351}
352
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800353void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700354 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800355 DCHECK_NE(image_objects_offset_begin_, 0u);
356
Vladimir Marko944da602016-02-19 12:27:55 +0000357 size_t oat_index = GetOatIndex(object);
358 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800359 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100360 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800361 DCHECK_ALIGNED(new_offset, kObjectAlignment);
362
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700363 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800364 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700365}
366
Ian Rogersef7d42f2014-01-06 12:55:46 -0800367bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800368 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700369 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700370 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700371}
372
Ian Rogersef7d42f2014-01-06 12:55:46 -0800373size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700374 DCHECK(object != nullptr);
375 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700376 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700377 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000378 size_t oat_index = GetOatIndex(object);
379 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800380 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700381 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700382}
383
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800384void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
385 DCHECK(object != nullptr);
386 DCHECK(!IsImageOffsetAssigned(object));
387 DCHECK(!IsImageBinSlotAssigned(object));
388
389 // Before we stomp over the lock word, save the hash code for later.
390 Monitor::Deflate(Thread::Current(), object);;
391 LockWord lw(object->GetLockWord(false));
392 switch (lw.GetState()) {
393 case LockWord::kFatLocked: {
394 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
395 break;
396 }
397 case LockWord::kThinLocked: {
398 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
399 break;
400 }
401 case LockWord::kUnlocked:
402 // No hash, don't need to save it.
403 break;
404 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700405 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
406 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800407 break;
408 default:
409 LOG(FATAL) << "Unreachable.";
410 UNREACHABLE();
411 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700412 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700413 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800414 DCHECK(IsImageBinSlotAssigned(object));
415}
416
Vladimir Marko20f85592015-03-19 10:07:02 +0000417void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000418 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000419 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
420 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800421 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000422 auto it = dex_file_oat_index_map_.find(dex_file);
423 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800424 ImageInfo& image_info = GetImageInfo(it->second);
425 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
426 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
427 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
428 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000429
Vladimir Marko20f85592015-03-19 10:07:02 +0000430 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700431 Thread* const self = Thread::Current();
432 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800433 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700434 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800435 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800436 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700437 continue;
438 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000439 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartier0b490842016-05-25 15:05:59 -0700440 CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
441 << "Dex cache should have been pruned " << dex_file->GetLocation()
442 << "; possibly in class path";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700443 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000444 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000445 size_t oat_index = GetOatIndexForDexCache(dex_cache);
446 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800447 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100448 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800449 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
450 start + layout.TypesOffset(),
451 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100452 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800453 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
454 start + layout.MethodsOffset(),
455 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100456 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800457 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
458 start + layout.FieldsOffset(),
459 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100460 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800461 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000462 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000463}
464
Jeff Haodcdc85b2015-12-04 14:06:18 -0800465void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100466 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800467 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000468 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800469 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000470 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100471 }
472}
473
Mathieu Chartiere401d142015-04-22 13:56:20 -0700474void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
475 DCHECK(arr != nullptr);
476 if (kIsDebugBuild) {
477 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800478 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700479 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800480 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800481 CHECK(klass == nullptr || KeepClass(klass))
482 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700483 }
484 }
485 }
486 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
487 // ArtMethods.
488 pointer_arrays_.emplace(arr, kBinArtMethodClean);
489}
490
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800491void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
492 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800493 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800494
495 // The magic happens here. We segregate objects into different bins based
496 // on how likely they are to get dirty at runtime.
497 //
498 // Likely-to-dirty objects get packed together into the same bin so that
499 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
500 // maximized.
501 //
502 // This means more pages will stay either clean or shared dirty (with zygote) and
503 // the app will use less of its own (private) memory.
504 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000505 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800506
507 if (kBinObjects) {
508 //
509 // Changing the bin of an object is purely a memory-use tuning.
510 // It has no change on runtime correctness.
511 //
512 // Memory analysis has determined that the following types of objects get dirtied
513 // the most:
514 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000515 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
516 // a fixed layout which helps improve generated code (using PC-relative addressing),
517 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
518 // Since these arrays are huge, most pages do not overlap other objects and it's not
519 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100520 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800521 // * Class'es which are verified [their clinit runs only at runtime]
522 // - classes in general [because their static fields get overwritten]
523 // - initialized classes with all-final statics are unlikely to be ever dirty,
524 // so bin them separately
525 // * Art Methods that are:
526 // - native [their native entry point is not looked up until runtime]
527 // - have declaring classes that aren't initialized
528 // [their interpreter/quick entry points are trampolines until the class
529 // becomes initialized]
530 //
531 // We also assume the following objects get dirtied either never or extremely rarely:
532 // * Strings (they are immutable)
533 // * Art methods that aren't native and have initialized declared classes
534 //
535 // We assume that "regular" bin objects are highly unlikely to become dirtied,
536 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
537 //
538 if (object->IsClass()) {
539 bin = kBinClassVerified;
540 mirror::Class* klass = object->AsClass();
541
Mathieu Chartiere401d142015-04-22 13:56:20 -0700542 // Add non-embedded vtable to the pointer array table if there is one.
543 auto* vtable = klass->GetVTable();
544 if (vtable != nullptr) {
545 AddMethodPointerArray(vtable);
546 }
547 auto* iftable = klass->GetIfTable();
548 if (iftable != nullptr) {
549 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
550 if (iftable->GetMethodArrayCount(i) > 0) {
551 AddMethodPointerArray(iftable->GetMethodArray(i));
552 }
553 }
554 }
555
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800556 if (klass->GetStatus() == Class::kStatusInitialized) {
557 bin = kBinClassInitialized;
558
559 // If the class's static fields are all final, put it into a separate bin
560 // since it's very likely it will stay clean.
561 uint32_t num_static_fields = klass->NumStaticFields();
562 if (num_static_fields == 0) {
563 bin = kBinClassInitializedFinalStatics;
564 } else {
565 // Maybe all the statics are final?
566 bool all_final = true;
567 for (uint32_t i = 0; i < num_static_fields; ++i) {
568 ArtField* field = klass->GetStaticField(i);
569 if (!field->IsFinal()) {
570 all_final = false;
571 break;
572 }
573 }
574
575 if (all_final) {
576 bin = kBinClassInitializedFinalStatics;
577 }
578 }
579 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800580 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
581 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700582 } else if (object->GetClass<kVerifyNone>() ==
583 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
584 // Instance of java lang object, probably a lock object. This means it will be dirty when we
585 // synchronize on it.
586 bin = kBinMiscDirty;
587 } else if (object->IsDexCache()) {
588 // Dex file field becomes dirty when the image is loaded.
589 bin = kBinMiscDirty;
590 }
591 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800592 }
593
Vladimir Marko944da602016-02-19 12:27:55 +0000594 size_t oat_index = GetOatIndex(object);
595 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800596
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800597 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800598 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
599 // Move the current bin size up to accommodate the object we just assigned a bin slot.
600 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800601
602 BinSlot new_bin_slot(bin, current_offset);
603 SetImageBinSlot(object, new_bin_slot);
604
Jeff Haodcdc85b2015-12-04 14:06:18 -0800605 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800606
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800607 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800608 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800609}
610
Mathieu Chartiere401d142015-04-22 13:56:20 -0700611bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
612 if (m->IsNative()) {
613 return true;
614 }
615 mirror::Class* declaring_class = m->GetDeclaringClass();
616 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
617 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
618}
619
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800620bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
621 DCHECK(object != nullptr);
622
623 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
624 // If it's in some other state, then we haven't yet assigned an image bin slot.
625 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
626 return false;
627 } else if (kIsDebugBuild) {
628 LockWord lock_word = object->GetLockWord(false);
629 size_t offset = lock_word.ForwardingAddress();
630 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000631 size_t oat_index = GetOatIndex(object);
632 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800633 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800634 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800635 }
636 return true;
637}
638
639ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
640 DCHECK(object != nullptr);
641 DCHECK(IsImageBinSlotAssigned(object));
642
643 LockWord lock_word = object->GetLockWord(false);
644 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
645 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
646
647 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000648 size_t oat_index = GetOatIndex(object);
649 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800650 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800651
652 return bin_slot;
653}
654
Brian Carlstrom7940e442013-07-12 13:46:57 -0700655bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000656 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800657 ImageSection unused_sections[ImageHeader::kSectionCount];
658 const size_t length = RoundUp(
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700659 image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800660
Jeff Haodcdc85b2015-12-04 14:06:18 -0800661 std::string error_msg;
662 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
663 nullptr,
664 length,
665 PROT_READ | PROT_WRITE,
666 false,
667 false,
668 &error_msg));
669 if (UNLIKELY(image_info.image_.get() == nullptr)) {
670 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
671 return false;
672 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700673
Jeff Haodcdc85b2015-12-04 14:06:18 -0800674 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
675 CHECK_LE(image_info.image_end_, length);
676 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
677 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
678 if (image_info.image_bitmap_.get() == nullptr) {
679 LOG(ERROR) << "Failed to allocate memory for image bitmap";
680 return false;
681 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700682 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700683 return true;
684}
685
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700686class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
687 public:
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800688 bool operator()(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700689 StackHandleScope<1> hs(Thread::Current());
690 mirror::Class::ComputeName(hs.NewHandle(c));
691 return true;
692 }
693};
694
Brian Carlstrom7940e442013-07-12 13:46:57 -0700695void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700696 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700697 ComputeLazyFieldsForClassesVisitor visitor;
698 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700699}
700
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800701static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
702 return klass->GetClassLoader() == nullptr;
703}
704
705bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
706 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
707}
708
Mathieu Chartier901e0702016-02-19 13:42:48 -0800709bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800710 bool early_exit = false;
711 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800712 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800713}
714
Mathieu Chartier901e0702016-02-19 13:42:48 -0800715bool ImageWriter::PruneAppImageClassInternal(
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800716 mirror::Class* klass,
717 bool* early_exit,
718 std::unordered_set<mirror::Class*>* visited) {
719 DCHECK(early_exit != nullptr);
720 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800721 DCHECK(compile_app_image_);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800722 if (klass == nullptr || IsInBootImage(klass)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700723 return false;
724 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800725 auto found = prune_class_memo_.find(klass);
726 if (found != prune_class_memo_.end()) {
727 // Already computed, return the found value.
728 return found->second;
729 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800730 // Circular dependencies, return false but do not store the result in the memoization table.
731 if (visited->find(klass) != visited->end()) {
732 *early_exit = true;
733 return false;
734 }
735 visited->emplace(klass);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800736 bool result = IsBootClassLoaderClass(klass);
737 std::string temp;
738 // Prune if not an image class, this handles any broken sets of image classes such as having a
739 // class in the set but not it's superclass.
740 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800741 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800742 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
743 // app image.
744 if (klass->GetStatus() == mirror::Class::kStatusError) {
745 result = true;
746 } else {
747 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
748 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800749 if (!result) {
750 // Check interfaces since these wont be visited through VisitReferences.)
751 mirror::IfTable* if_table = klass->GetIfTable();
752 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800753 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
754 &my_early_exit,
755 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800756 }
757 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800758 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800759 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
760 &my_early_exit,
761 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800762 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800763 // Check static fields and their classes.
764 size_t num_static_fields = klass->NumReferenceStaticFields();
765 if (num_static_fields != 0 && klass->IsResolved()) {
766 // Presumably GC can happen when we are cross compiling, it should not cause performance
767 // problems to do pointer size logic.
768 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
769 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
770 for (size_t i = 0u; i < num_static_fields; ++i) {
771 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
772 if (ref != nullptr) {
773 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800774 result = result || PruneAppImageClassInternal(ref->AsClass(),
775 &my_early_exit,
776 visited);
777 } else {
778 result = result || PruneAppImageClassInternal(ref->GetClass(),
779 &my_early_exit,
780 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800781 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800782 }
783 field_offset = MemberOffset(field_offset.Uint32Value() +
784 sizeof(mirror::HeapReference<mirror::Object>));
785 }
786 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800787 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
788 &my_early_exit,
789 visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800790 // Erase the element we stored earlier since we are exiting the function.
791 auto it = visited->find(klass);
792 DCHECK(it != visited->end());
793 visited->erase(it);
794 // Only store result if it is true or none of the calls early exited due to circular
795 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
796 // a child call and we can remember the result.
797 if (result == true || !my_early_exit || visited->empty()) {
798 prune_class_memo_[klass] = result;
799 }
800 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800801 return result;
802}
803
804bool ImageWriter::KeepClass(Class* klass) {
805 if (klass == nullptr) {
806 return false;
807 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800808 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
809 // Already in boot image, return true.
810 return true;
811 }
812 std::string temp;
813 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
814 return false;
815 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800816 if (compile_app_image_) {
817 // For app images, we need to prune boot loader classes that are not in the boot image since
818 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800819 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800820 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800821 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800822 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700823}
824
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700825class NonImageClassesVisitor : public ClassVisitor {
826 public:
827 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
828
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800829 bool operator()(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800830 if (!image_writer_->KeepClass(klass)) {
831 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700832 }
833 return true;
834 }
835
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800836 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700837 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700838};
839
840void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700841 Runtime* runtime = Runtime::Current();
842 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700843 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700844
Mathieu Chartier696632e2016-06-03 17:47:32 -0700845 // Clear class table strong roots so that dex caches can get pruned. We require pruning the class
846 // path dex caches.
847 class_linker->ClearClassTableStrongRoots();
848
Brian Carlstrom7940e442013-07-12 13:46:57 -0700849 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700850 NonImageClassesVisitor visitor(this);
851 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700852
853 // Remove the undesired classes from the class roots.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800854 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800855 for (mirror::Class* klass : visitor.classes_to_prune_) {
856 std::string temp;
857 const char* name = klass->GetDescriptor(&temp);
858 VLOG(compiler) << "Pruning class " << name;
859 if (!compile_app_image_) {
860 DCHECK(IsBootClassLoaderClass(klass));
861 }
862 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800863 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700864 }
865
866 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100867 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700868
869 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
870 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
871 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800872 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800873 if (self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700874 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700875 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800876 mirror::DexCache* dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700877 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
878 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800879 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700880 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700881 }
882 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100883 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
884 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
885 ArtMethod* method =
886 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800887 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
888 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800889 // 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 -0800890 // declaring class which is an image class. Set it to the resolution method to be safe and
891 // prevent dangling pointers.
Alex Light36121492016-02-22 13:43:29 -0800892 if (method->IsCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800893 mirror::DexCache::SetElementPtrSize(resolved_methods,
894 i,
895 resolution_method,
896 target_ptr_size_);
897 } else {
898 // Check that the class is still in the classes table.
899 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
900 << PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700901 }
902 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800903 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700904 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800905 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800906 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700907 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700908 }
909 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700910 // Clean the dex field. It might have been populated during the initialization phase, but
911 // contains data only valid during a real run.
912 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700913 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700914
915 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
916 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800917
918 // Clear to save RAM.
919 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700920}
921
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800922void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700923 if (compiler_driver_.GetImageClasses() != nullptr) {
924 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700925 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700926 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700927}
928
929void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
930 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800931 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700932 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800933 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700934 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700935 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800936 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
937 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700938 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700939 }
940}
941
942void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700943 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700944 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700945 for (const std::string& image_class : *image_classes) {
946 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700947 }
948}
949
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800950mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
951 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +0000952 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800953 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
954 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
955 << string->ToModifiedUtf8();
956 if (found != nullptr) {
957 return found;
958 }
959 }
960 if (compile_app_image_) {
961 Runtime* const runtime = Runtime::Current();
962 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
963 // If we found it in the runtime intern table it could either be in the boot image or interned
964 // during app image compilation. If it was in the boot image return that, otherwise return null
965 // since it belongs to another image space.
966 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
967 return found;
968 }
969 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
970 << string->ToModifiedUtf8();
971 }
972 return nullptr;
973}
974
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800975void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700976 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700977 // if it is a string, we want to intern it if its not interned.
978 if (obj->GetClass()->IsStringClass()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000979 size_t oat_index = GetOatIndex(obj);
980 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800981
Brian Carlstrom7940e442013-07-12 13:46:57 -0700982 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800983 if (IsImageBinSlotAssigned(obj)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800984 DCHECK_EQ(obj, FindInternedString(obj->AsString()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700985 return;
986 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800987 // Need to check if the string is already interned in another image info so that we don't have
988 // the intern tables of two different images contain the same string.
989 mirror::String* interned = FindInternedString(obj->AsString());
990 if (interned == nullptr) {
991 // Not in another image space, insert to our table.
992 interned = image_info.intern_table_->InternStrongImageString(obj->AsString());
993 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700994 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800995 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700996 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800997 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700998 }
999 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001000 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001001 return;
1002 }
1003 // else (obj == interned), nothing to do but fall through to the normal case
1004 }
1005
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001006 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001007}
1008
Vladimir Marko944da602016-02-19 12:27:55 +00001009ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001010 Runtime* runtime = Runtime::Current();
1011 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001012 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001013 StackHandleScope<3> hs(self);
1014 Handle<Class> object_array_class(hs.NewHandle(
1015 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001016
Jeff Haodcdc85b2015-12-04 14:06:18 -08001017 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +00001018 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001019 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +00001020 size_t image_oat_index = pair.second;
1021 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001022 image_dex_files.insert(image_dex_file);
1023 }
1024 }
1025
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001026 // build an Object[] of all the DexCaches used in the source_space_.
1027 // Since we can't hold the dex lock when allocating the dex_caches
1028 // ObjectArray, we lock the dex lock twice, first to get the number
1029 // of dex caches first and then lock it again to copy the dex
1030 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001031 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001032 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001033 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001034 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001035 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1036 mirror::DexCache* dex_cache =
1037 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001038 if (dex_cache == nullptr) {
1039 continue;
1040 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001041 const DexFile* dex_file = dex_cache->GetDexFile();
1042 if (!IsInBootImage(dex_cache)) {
1043 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1044 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001045 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001046 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001047 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001048 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001049 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1050 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001051 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001052 size_t non_image_dex_caches = 0;
1053 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001054 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1055 mirror::DexCache* dex_cache =
1056 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001057 if (dex_cache == nullptr) {
1058 continue;
1059 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001060 const DexFile* dex_file = dex_cache->GetDexFile();
1061 if (!IsInBootImage(dex_cache)) {
1062 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1063 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001064 }
1065 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1066 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001067 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001068 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1069 mirror::DexCache* dex_cache =
1070 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001071 if (dex_cache == nullptr) {
1072 continue;
1073 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001074 const DexFile* dex_file = dex_cache->GetDexFile();
1075 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001076 dex_caches->Set<false>(i, dex_cache);
1077 ++i;
1078 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001079 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001080 }
1081
1082 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001083 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001084 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001085 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001086 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001087 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001088 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001089 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001090 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001091}
1092
Mathieu Chartier590fee92013-09-13 13:46:47 -07001093// Walk instance fields of the given Class. Separate function to allow recursion on the super
1094// class.
1095void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1096 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001097 StackHandleScope<1> hs(Thread::Current());
1098 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1099 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001100 if (super != nullptr) {
1101 WalkInstanceFields(obj, super);
1102 }
1103 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001104 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +00001105 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001106 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001107 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001108 if (value != nullptr) {
1109 WalkFieldsInOrder(value);
1110 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001111 field_offset = MemberOffset(field_offset.Uint32Value() +
1112 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001113 }
1114}
1115
1116// For an unvisited object, visit it then all its children found via fields.
1117void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001118 if (IsInBootImage(obj)) {
1119 // Object is in the image, don't need to fix it up.
1120 return;
1121 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001122 // Use our own visitor routine (instead of GC visitor) to get better locality between
1123 // an object and its fields
1124 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001125 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001126 StackHandleScope<2> hs(Thread::Current());
1127 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1128 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001129 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001130 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001131 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001132 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001133 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001134 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001135 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001136 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001137 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001138 if (value != nullptr) {
1139 WalkFieldsInOrder(value);
1140 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001141 field_offset = MemberOffset(field_offset.Uint32Value() +
1142 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001143 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001144 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001145 auto* as_klass = h_obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001146 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001147 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1148 if (compile_app_image_) {
1149 // Extra sanity, no boot loader classes should be left!
1150 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1151 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001152 LengthPrefixedArray<ArtField>* fields[] = {
1153 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1154 };
Vladimir Marko944da602016-02-19 12:27:55 +00001155 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1156 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001157 {
1158 // Note: This table is only accessed from the image writer, so the lock is technically
1159 // unnecessary.
1160 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1161 // Insert in the class table for this iamge.
1162 image_info.class_table_->Insert(as_klass);
1163 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001164 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1165 // Total array length including header.
1166 if (cur_fields != nullptr) {
1167 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1168 // Forward the entire array at once.
1169 auto it = native_object_relocations_.find(cur_fields);
1170 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1171 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001172 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001173 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001174 native_object_relocations_.emplace(
1175 cur_fields,
1176 NativeObjectRelocation {
1177 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1178 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001179 offset += header_size;
1180 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001181 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001182 // Need to forward arrays separate of fields.
1183 ArtField* field = &cur_fields->At(i);
1184 auto it2 = native_object_relocations_.find(field);
1185 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1186 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001187 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001188 native_object_relocations_.emplace(
1189 field,
1190 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001191 offset += sizeof(ArtField);
1192 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001193 }
1194 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001195 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001196 size_t num_methods = as_klass->NumMethods();
1197 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001198 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001199 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1200 if (WillMethodBeDirty(&m)) {
1201 any_dirty = true;
1202 break;
1203 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001204 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001205 NativeObjectRelocationType type = any_dirty
1206 ? kNativeObjectRelocationTypeArtMethodDirty
1207 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001208 Bin bin_type = BinTypeForNativeRelocationType(type);
1209 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001210 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1211 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001212 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1213 method_size,
1214 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001215 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001216 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001217 CHECK(it == native_object_relocations_.end())
1218 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001219 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001220 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001221 native_object_relocations_.emplace(array,
1222 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001223 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001224 offset,
1225 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1226 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001227 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001228 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001229 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001230 }
Alex Lighte64300b2015-12-15 15:02:47 -08001231 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001232 }
1233 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1234 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001235 if (as_klass->ShouldHaveImt()) {
1236 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1237 for (size_t i = 0; i < ImTable::kSize; ++i) {
1238 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001239 DCHECK(imt_method != nullptr);
1240 if (imt_method->IsRuntimeMethod() &&
1241 !IsInBootImage(imt_method) &&
1242 !NativeRelocationAssigned(imt_method)) {
1243 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001244 }
1245 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001246 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001247
1248 if (as_klass->ShouldHaveImt()) {
1249 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1250 TryAssignImTableOffset(imt, oat_index);
1251 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001252 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001253 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001254 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001255 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001256 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001257 mirror::Object* value = obj_array->Get(i);
1258 if (value != nullptr) {
1259 WalkFieldsInOrder(value);
1260 }
1261 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001262 } else if (h_obj->IsClassLoader()) {
1263 // Register the class loader if it has a class table.
1264 // The fake boot class loader should not get registered and we should end up with only one
1265 // class loader.
1266 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1267 if (class_loader->GetClassTable() != nullptr) {
1268 class_loaders_.insert(class_loader);
1269 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001270 }
1271 }
1272}
1273
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001274bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1275 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1276}
1277
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001278void ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
1279 // No offset, or already assigned.
1280 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
1281 return;
1282 }
1283 // If the method is a conflict method we also want to assign the conflict table offset.
1284 ImageInfo& image_info = GetImageInfo(oat_index);
1285 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1286 native_object_relocations_.emplace(
1287 imt,
1288 NativeObjectRelocation {
1289 oat_index,
1290 image_info.bin_slot_sizes_[kBinImTable],
1291 kNativeObjectRelocationTypeIMTable});
1292 image_info.bin_slot_sizes_[kBinImTable] += size;
1293}
1294
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001295void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1296 // No offset, or already assigned.
1297 if (table == nullptr || NativeRelocationAssigned(table)) {
1298 return;
1299 }
1300 CHECK(!IsInBootImage(table));
1301 // If the method is a conflict method we also want to assign the conflict table offset.
1302 ImageInfo& image_info = GetImageInfo(oat_index);
1303 const size_t size = table->ComputeSize(target_ptr_size_);
1304 native_object_relocations_.emplace(
1305 table,
1306 NativeObjectRelocation {
1307 oat_index,
1308 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1309 kNativeObjectRelocationTypeIMTConflictTable});
1310 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1311}
1312
Jeff Haodcdc85b2015-12-04 14:06:18 -08001313void ImageWriter::AssignMethodOffset(ArtMethod* method,
1314 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001315 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001316 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001317 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001318 << PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001319 if (method->IsRuntimeMethod()) {
1320 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1321 }
Vladimir Marko944da602016-02-19 12:27:55 +00001322 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001323 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001324 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001325 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001326}
1327
Mathieu Chartier590fee92013-09-13 13:46:47 -07001328void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1329 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1330 DCHECK(writer != nullptr);
1331 writer->WalkFieldsInOrder(obj);
1332}
1333
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001334void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1335 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1336 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001337 if (!writer->IsInBootImage(obj)) {
1338 writer->UnbinObjectsIntoOffset(obj);
1339 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001340}
1341
1342void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001343 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001344 CHECK(obj != nullptr);
1345
1346 // We know the bin slot, and the total bin sizes for all objects by now,
1347 // so calculate the object's final image offset.
1348
1349 DCHECK(IsImageBinSlotAssigned(obj));
1350 BinSlot bin_slot = GetImageBinSlot(obj);
1351 // Change the lockword from a bin slot into an offset
1352 AssignImageOffset(obj, bin_slot);
1353}
1354
Vladimir Markof4da6752014-08-01 19:04:18 +01001355void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001356 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001357 StackHandleScopeCollection handles(self);
1358 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001359 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1360 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001361 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001362
Mathieu Chartiere401d142015-04-22 13:56:20 -07001363 auto* runtime = Runtime::Current();
1364 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001365
Mathieu Chartier31e89252013-08-28 11:29:12 -07001366 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001367 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001368 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001369
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001370 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001371 // Write the image runtime methods.
1372 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1373 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1374 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1375 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1376 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1377 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1378 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1379 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001380 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001381 for (auto* m : image_methods_) {
1382 CHECK(m != nullptr);
1383 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001384 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1385 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001386 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001387 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001388 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001389
1390 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1391 heap->VisitObjects(WalkFieldsCallback, this);
1392
Vladimir Marko05792b92015-08-03 11:56:49 +01001393 // Calculate size of the dex cache arrays slot and prepare offsets.
1394 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001395
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001396 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001397 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001398 // Calculate how big the intern table will be after being serialized.
1399 InternTable* const intern_table = image_info.intern_table_.get();
1400 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1401 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001402 // Calculate the size of the class table.
1403 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1404 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001405 }
1406
Vladimir Markocf36d492015-08-12 19:27:26 +01001407 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001408 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001409 size_t bin_offset = image_objects_offset_begin_;
1410 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001411 switch (i) {
1412 case kBinArtMethodClean:
1413 case kBinArtMethodDirty: {
1414 bin_offset = RoundUp(bin_offset, method_alignment);
1415 break;
1416 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001417 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001418 case kBinIMTConflictTable: {
1419 bin_offset = RoundUp(bin_offset, target_ptr_size_);
1420 break;
1421 }
1422 default: {
1423 // Normal alignment.
1424 }
1425 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001426 image_info.bin_slot_offsets_[i] = bin_offset;
1427 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001428 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001429 // NOTE: There may be additional padding between the bin slots and the intern table.
1430 DCHECK_EQ(image_info.image_end_,
1431 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001432 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001433
Jeff Haodcdc85b2015-12-04 14:06:18 -08001434 // Calculate image offsets.
1435 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001436 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001437 image_info.image_begin_ = global_image_begin_ + image_offset;
1438 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001439 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001440 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001441 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001442 image_offset += image_info.image_size_;
1443 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001444
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001445 // Transform each object's bin slot into an offset which will be used to do the final copy.
1446 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001447
Jeff Haodcdc85b2015-12-04 14:06:18 -08001448 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001449
Jeff Haodcdc85b2015-12-04 14:06:18 -08001450 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001451 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001452 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1453 i++;
1454 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001455
Mathieu Chartiere401d142015-04-22 13:56:20 -07001456 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001457 for (auto& pair : native_object_relocations_) {
1458 NativeObjectRelocation& relocation = pair.second;
1459 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001460 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001461 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001462 }
1463
Jeff Haodcdc85b2015-12-04 14:06:18 -08001464 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001465}
1466
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001467size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001468 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001469
1470 // Do not round up any sections here that are represented by the bins since it will break
1471 // offsets.
1472
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001473 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001474 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001475 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001476
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001477 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001478 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1479 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001480 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001481
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001482 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001483 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1484 *methods_section = ImageSection(
1485 bin_slot_offsets_[kBinArtMethodClean],
1486 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1487
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001488 // IMT section.
1489 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1490 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1491
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001492 // Conflict tables section.
1493 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1494 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1495 bin_slot_sizes_[kBinIMTConflictTable]);
1496
1497 // Runtime methods section.
1498 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1499 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1500 bin_slot_sizes_[kBinRuntimeMethod]);
1501
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001502 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001503 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1504 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1505 bin_slot_sizes_[kBinDexCacheArray]);
1506
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001507 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001508 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001509 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001510 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001511 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1512 cur_pos = interned_strings_section->End();
1513 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1514 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1515 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001516 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001517 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001518 cur_pos = class_table_section->End();
1519 // Image end goes right before the start of the image bitmap.
1520 return cur_pos;
1521}
1522
Vladimir Marko944da602016-02-19 12:27:55 +00001523void ImageWriter::CreateHeader(size_t oat_index) {
1524 ImageInfo& image_info = GetImageInfo(oat_index);
1525 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1526 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1527 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001528
1529 // Create the image sections.
1530 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001531 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001532
Mathieu Chartiere401d142015-04-22 13:56:20 -07001533 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001534 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001535 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001536 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001537 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001538 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001539 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001540 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001541 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1542 ++idx;
1543 }
1544 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001545 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1546 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1547 << " Image offset=" << image_info.image_offset_ << std::dec;
1548 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1549 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1550 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1551 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001552 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001553 // Store boot image info for app image so that we can relocate.
1554 uint32_t boot_image_begin = 0;
1555 uint32_t boot_image_end = 0;
1556 uint32_t boot_oat_begin = 0;
1557 uint32_t boot_oat_end = 0;
1558 gc::Heap* const heap = Runtime::Current()->GetHeap();
1559 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001560
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001561 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1562 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001563 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1564 image_end,
1565 sections,
1566 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001567 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001568 PointerToLowMemUInt32(oat_file_begin),
1569 PointerToLowMemUInt32(image_info.oat_data_begin_),
1570 PointerToLowMemUInt32(oat_data_end),
1571 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001572 boot_image_begin,
1573 boot_image_end - boot_image_begin,
1574 boot_oat_begin,
1575 boot_oat_end - boot_oat_begin,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001576 target_ptr_size_,
1577 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001578 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001579 image_storage_mode_,
1580 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001581}
1582
1583ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001584 auto it = native_object_relocations_.find(method);
1585 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001586 size_t oat_index = GetOatIndex(method->GetDexCache());
1587 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001588 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1589 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001590}
1591
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001592class FixupRootVisitor : public RootVisitor {
1593 public:
1594 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1595 }
1596
1597 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001598 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001599 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001600 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001601 }
1602 }
1603
1604 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1605 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001606 OVERRIDE SHARED_REQUIRES(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]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001609 }
1610 }
1611
1612 private:
1613 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001614};
1615
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001616void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
1617 for (size_t i = 0; i < ImTable::kSize; ++i) {
1618 ArtMethod* method = orig->Get(i, target_ptr_size_);
1619 copy->Set(i, NativeLocationInImage(method), target_ptr_size_);
1620 }
1621}
1622
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001623void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
1624 const size_t count = orig->NumEntries(target_ptr_size_);
1625 for (size_t i = 0; i < count; ++i) {
1626 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
1627 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
1628 copy->SetInterfaceMethod(i, target_ptr_size_, NativeLocationInImage(interface_method));
1629 copy->SetImplementationMethod(i,
1630 target_ptr_size_,
1631 NativeLocationInImage(implementation_method));
1632 }
1633}
1634
Vladimir Marko944da602016-02-19 12:27:55 +00001635void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001636 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001637 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001638 for (auto& pair : native_object_relocations_) {
1639 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001640 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001641 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001642 continue;
1643 }
1644 auto* dest = image_info.image_->Begin() + relocation.offset;
1645 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001646 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001647 switch (relocation.type) {
1648 case kNativeObjectRelocationTypeArtField: {
1649 memcpy(dest, pair.first, sizeof(ArtField));
1650 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1651 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1652 break;
1653 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001654 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001655 case kNativeObjectRelocationTypeArtMethodClean:
1656 case kNativeObjectRelocationTypeArtMethodDirty: {
1657 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001658 reinterpret_cast<ArtMethod*>(dest),
1659 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001660 break;
1661 }
1662 // For arrays, copy just the header since the elements will get copied by their corresponding
1663 // relocations.
1664 case kNativeObjectRelocationTypeArtFieldArray: {
1665 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1666 break;
1667 }
1668 case kNativeObjectRelocationTypeArtMethodArrayClean:
1669 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00001670 size_t size = ArtMethod::Size(target_ptr_size_);
1671 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1672 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1673 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1674 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001675 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00001676 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001677 case kNativeObjectRelocationTypeDexCacheArray:
1678 // Nothing to copy here, everything is done in FixupDexCache().
1679 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001680 case kNativeObjectRelocationTypeIMTable: {
1681 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
1682 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
1683 CopyAndFixupImTable(orig_imt, dest_imt);
1684 break;
1685 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001686 case kNativeObjectRelocationTypeIMTConflictTable: {
1687 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
1688 CopyAndFixupImtConflictTable(
1689 orig_table,
1690 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
1691 break;
1692 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001693 }
1694 }
1695 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001696 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001697 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001698 ArtMethod* method = image_methods_[i];
1699 CHECK(method != nullptr);
1700 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001701 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001702 }
1703 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001704 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001705 FixupRootVisitor root_visitor(this);
1706
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001707 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001708 if (image_info.intern_table_bytes_ > 0) {
1709 const ImageSection& intern_table_section = image_header->GetImageSection(
1710 ImageHeader::kSectionInternedStrings);
1711 InternTable* const intern_table = image_info.intern_table_.get();
1712 uint8_t* const intern_table_memory_ptr =
1713 image_info.image_->Begin() + intern_table_section.Offset();
1714 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1715 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1716 // Fixup the pointers in the newly written intern table to contain image addresses.
1717 InternTable temp_intern_table;
1718 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1719 // the VisitRoots() will update the memory directly rather than the copies.
1720 // This also relies on visit roots not doing any verification which could fail after we update
1721 // the roots to be the image addresses.
1722 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1723 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1724 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1725 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001726 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1727 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001728 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001729 const ImageSection& class_table_section = image_header->GetImageSection(
1730 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001731 uint8_t* const class_table_memory_ptr =
1732 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001733 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001734
1735 ClassTable* table = image_info.class_table_.get();
1736 CHECK(table != nullptr);
1737 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1738 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1739 // Fixup the pointers in the newly written class table to contain image addresses. See
1740 // above comment for intern tables.
1741 ClassTable temp_class_table;
1742 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1743 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1744 table->NumZygoteClasses());
1745 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1746 RootInfo(kRootUnknown));
1747 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001748 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001749}
1750
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001751void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001752 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001753 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1754 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001755 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001756 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001757 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1758 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001759 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001760 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001761}
1762
Mathieu Chartier590fee92013-09-13 13:46:47 -07001763void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001764 DCHECK(obj != nullptr);
1765 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001766 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1767}
1768
Mathieu Chartiere401d142015-04-22 13:56:20 -07001769void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1770 mirror::Class* klass, Bin array_type) {
1771 CHECK(klass->IsArrayClass());
1772 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1773 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001774 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001775 dst->SetClass(GetImageAddress(arr->GetClass()));
1776 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001777 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001778 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1779 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001780 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001781 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001782 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001783 auto* method = reinterpret_cast<ArtMethod*>(elem);
1784 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1785 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1786 << PrettyClass(method->GetDeclaringClass());
1787 } else {
1788 CHECK_EQ(array_type, kBinArtField);
1789 auto* field = reinterpret_cast<ArtField*>(elem);
1790 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1791 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1792 << PrettyClass(field->GetDeclaringClass());
1793 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001794 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001795 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001796 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001797 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001798 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001799 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001800 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001801 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001802}
1803
1804void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001805 if (IsInBootImage(obj)) {
1806 return;
1807 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001808 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001809 size_t oat_index = GetOatIndex(obj);
1810 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001811 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1812 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001813 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001814
Jeff Haodcdc85b2015-12-04 14:06:18 -08001815 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001816
1817 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001818 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001819 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001820
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001821 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1822 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001823 const auto it = saved_hashcode_map_.find(obj);
1824 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1825 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001826 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001827}
1828
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001829// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001830class FixupVisitor {
1831 public:
1832 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1833 }
1834
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001835 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1836 // with other logic.
1837 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1838 const {}
1839 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1840
1841
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001842 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001843 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001844 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001845 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1846 // image.
1847 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001848 offset,
1849 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001850 }
1851
1852 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001853 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001854 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001855 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001856 mirror::Reference::ReferentOffset(),
1857 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001858 }
1859
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001860 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001861 ImageWriter* const image_writer_;
1862 mirror::Object* const copy_;
1863};
1864
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001865class FixupClassVisitor FINAL : public FixupVisitor {
1866 public:
1867 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1868 }
1869
Mathieu Chartierc7853442015-03-27 14:35:38 -07001870 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001871 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001872 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001873 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001874 }
1875
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001876 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1877 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001878 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001879 LOG(FATAL) << "Reference not expected here.";
1880 }
1881};
1882
Vladimir Marko05792b92015-08-03 11:56:49 +01001883uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1884 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001885 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001886 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001887 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1888 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001889 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001890 return relocation.offset;
1891}
1892
1893template <typename T>
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001894std::string PrettyPrint(T* ptr) SHARED_REQUIRES(Locks::mutator_lock_) {
1895 std::ostringstream oss;
1896 oss << ptr;
1897 return oss.str();
1898}
1899
1900template <>
1901std::string PrettyPrint(ArtMethod* method) SHARED_REQUIRES(Locks::mutator_lock_) {
1902 return PrettyMethod(method);
1903}
1904
1905template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001906T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001907 if (obj == nullptr || IsInBootImage(obj)) {
1908 return obj;
1909 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001910 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001911 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
1912 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001913 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00001914 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001915 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001916 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001917}
1918
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001919template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001920T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1921 if (obj == nullptr || IsInBootImage(obj)) {
1922 return obj;
1923 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001924 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1925 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001926 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1927 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001928}
1929
1930class NativeLocationVisitor {
1931 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001932 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001933
1934 template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001935 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001936 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001937 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001938
1939 private:
1940 ImageWriter* const image_writer_;
1941};
1942
1943void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001944 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001945 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001946 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001947
1948 // Remove the clinitThreadId. This is required for image determinism.
1949 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001950}
1951
Ian Rogersef7d42f2014-01-06 12:55:46 -08001952void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001953 DCHECK(orig != nullptr);
1954 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001955 if (kUseBakerOrBrooksReadBarrier) {
1956 orig->AssertReadBarrierPointer();
1957 if (kUseBrooksReadBarrier) {
1958 // Note the address 'copy' isn't the same as the image address of 'orig'.
1959 copy->SetReadBarrierPointer(GetImageAddress(orig));
1960 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1961 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001962 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001963 auto* klass = orig->GetClass();
1964 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001965 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001966 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1967 if (it != pointer_arrays_.end()) {
1968 // Should only need to fixup every pointer array exactly once.
1969 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1970 pointer_arrays_.erase(it);
1971 return;
1972 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001973 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001974 if (orig->IsClass()) {
1975 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001976 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001977 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1978 // Need to go update the ArtMethod.
1979 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1980 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1981 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001982 auto it = native_object_relocations_.find(src_method);
1983 CHECK(it != native_object_relocations_.end())
1984 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001985 dest->SetArtMethod(
Jeff Haodcdc85b2015-12-04 14:06:18 -08001986 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001987 } else if (!klass->IsArrayClass()) {
1988 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1989 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1990 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001991 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001992 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01001993 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1994 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001995 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001996 // Also set allocator to null to be safe. The allocator is created when we create the class
1997 // table. We also never expect to unload things in the image since they are held live as
1998 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001999 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002000 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002001 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002002 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002003 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002004 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002005}
2006
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002007
2008class ImageAddressVisitor {
2009 public:
2010 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
2011
2012 template <typename T>
2013 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
2014 return image_writer_->GetImageAddress(ptr);
2015 }
2016
2017 private:
2018 ImageWriter* const image_writer_;
2019};
2020
2021
Vladimir Marko05792b92015-08-03 11:56:49 +01002022void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2023 mirror::DexCache* copy_dex_cache) {
2024 // Though the DexCache array fields are usually treated as native pointers, we set the full
2025 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2026 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2027 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
2028 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
2029 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002030 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002031 NativeLocationInImage(orig_strings),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002032 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002033 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
2034 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002035 }
2036 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
2037 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002038 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002039 NativeLocationInImage(orig_types),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002040 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002041 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
2042 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002043 }
2044 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
2045 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002046 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002047 NativeLocationInImage(orig_methods),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002048 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002049 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002050 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
2051 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002052 // NativeLocationInImage also handles runtime methods since these have relocation info.
2053 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002054 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
2055 }
2056 }
2057 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
2058 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002059 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002060 NativeLocationInImage(orig_fields),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002061 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002062 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002063 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
2064 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002065 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002066 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
2067 }
2068 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002069
2070 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2071 // compiler pointers in here will make the output non-deterministic.
2072 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002073}
2074
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002075const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2076 DCHECK_LT(type, kOatAddressCount);
2077 // If we are compiling an app image, we need to use the stubs of the boot image.
2078 if (compile_app_image_) {
2079 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002080 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002081 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2082 DCHECK(!image_spaces.empty());
2083 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002084 CHECK(oat_file != nullptr);
2085 const OatHeader& header = oat_file->GetOatHeader();
2086 switch (type) {
2087 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2088 case kOatAddressQuickGenericJNITrampoline:
2089 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2090 case kOatAddressInterpreterToInterpreterBridge:
2091 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2092 case kOatAddressInterpreterToCompiledCodeBridge:
2093 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2094 case kOatAddressJNIDlsymLookup:
2095 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2096 case kOatAddressQuickIMTConflictTrampoline:
2097 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2098 case kOatAddressQuickResolutionTrampoline:
2099 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2100 case kOatAddressQuickToInterpreterBridge:
2101 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2102 default:
2103 UNREACHABLE();
2104 }
2105 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002106 const ImageInfo& primary_image_info = GetImageInfo(0);
2107 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002108}
2109
Jeff Haodcdc85b2015-12-04 14:06:18 -08002110const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2111 const ImageInfo& image_info,
2112 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002113 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
Nicolas Geoffray796d6302016-03-13 22:22:31 +00002114 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002115 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07002116 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002117 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002118
2119 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2120 // trampoline.
2121
2122 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002123 const void* quick_oat_entry_point =
2124 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2125 const uint8_t* quick_code;
2126
2127 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2128 DCHECK(method->IsCopied());
2129 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2130 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2131 } else {
2132 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2133 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2134 }
2135
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002136 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002137 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2138 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002139 // We have code for a non-static or initialized method, just use the code.
2140 } else if (quick_code == nullptr && method->IsNative() &&
2141 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2142 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002143 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002144 } else if (quick_code == nullptr && !method->IsNative()) {
2145 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002146 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002147 *quick_is_interpreted = true;
2148 } else {
2149 CHECK(!method->GetDeclaringClass()->IsInitialized());
2150 // We have code for a static method, but need to go through the resolution stub for class
2151 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002152 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2153 }
2154 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002155 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002156 }
2157 return quick_code;
2158}
2159
Jeff Haodcdc85b2015-12-04 14:06:18 -08002160void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2161 ArtMethod* copy,
2162 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002163 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002164
2165 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002166 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002167 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002168 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002169 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002170
Ian Rogers848871b2013-08-05 10:56:33 -07002171 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2172 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002173
Ian Rogers848871b2013-08-05 10:56:33 -07002174 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002175 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002176 if (orig->IsRuntimeMethod()) {
2177 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2178 if (orig_table != nullptr) {
2179 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2180 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2181 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2182 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2183 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2184 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2185 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2186 } else {
2187 bool found_one = false;
2188 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2189 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2190 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2191 found_one = true;
2192 break;
2193 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002194 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002195 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2196 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002197 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002198 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002199 // We assume all methods have code. If they don't currently then we set them to the use the
2200 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2201 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002202 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002203 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002204 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002205 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002206 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002207 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002208 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002209
Sebastien Hertze1d07812014-05-21 15:44:09 +02002210 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002211 if (orig->IsNative()) {
2212 // The native method's pointer is set to a stub to lookup via dlsym.
2213 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002214 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002215 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002216 }
2217 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002218 }
2219}
2220
Jeff Haodcdc85b2015-12-04 14:06:18 -08002221size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002222 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002223 return std::accumulate(&image_info.bin_slot_sizes_[0],
2224 &image_info.bin_slot_sizes_[up_to],
2225 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002226}
2227
2228ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2229 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002230 static_assert(kBinBits == 3, "wrong number of bin bits");
2231 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002232 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2233
2234 DCHECK_LT(GetBin(), kBinSize);
2235 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2236}
2237
2238ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2239 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2240 DCHECK_EQ(index, GetIndex());
2241}
2242
2243ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2244 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2245}
2246
2247uint32_t ImageWriter::BinSlot::GetIndex() const {
2248 return lockword_ & ~kBinMask;
2249}
2250
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002251ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2252 switch (type) {
2253 case kNativeObjectRelocationTypeArtField:
2254 case kNativeObjectRelocationTypeArtFieldArray:
2255 return kBinArtField;
2256 case kNativeObjectRelocationTypeArtMethodClean:
2257 case kNativeObjectRelocationTypeArtMethodArrayClean:
2258 return kBinArtMethodClean;
2259 case kNativeObjectRelocationTypeArtMethodDirty:
2260 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2261 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002262 case kNativeObjectRelocationTypeDexCacheArray:
2263 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002264 case kNativeObjectRelocationTypeRuntimeMethod:
2265 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002266 case kNativeObjectRelocationTypeIMTable:
2267 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002268 case kNativeObjectRelocationTypeIMTConflictTable:
2269 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002270 }
2271 UNREACHABLE();
2272}
2273
Vladimir Marko944da602016-02-19 12:27:55 +00002274size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002275 if (compile_app_image_) {
Vladimir Marko944da602016-02-19 12:27:55 +00002276 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002277 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002278 mirror::DexCache* dex_cache =
2279 obj->IsDexCache() ? obj->AsDexCache()
2280 : obj->IsClass() ? obj->AsClass()->GetDexCache()
2281 : obj->GetClass()->GetDexCache();
2282 return GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002283 }
2284}
2285
Vladimir Marko944da602016-02-19 12:27:55 +00002286size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
2287 if (compile_app_image_) {
2288 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002289 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002290 auto it = dex_file_oat_index_map_.find(dex_file);
2291 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002292 return it->second;
2293 }
2294}
2295
Vladimir Marko944da602016-02-19 12:27:55 +00002296size_t ImageWriter::GetOatIndexForDexCache(mirror::DexCache* dex_cache) const {
2297 if (dex_cache == nullptr) {
2298 return GetDefaultOatIndex();
2299 } else {
2300 return GetOatIndexForDexFile(dex_cache->GetDexFile());
2301 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002302}
2303
Vladimir Marko944da602016-02-19 12:27:55 +00002304void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2305 size_t oat_loaded_size,
2306 size_t oat_data_offset,
2307 size_t oat_data_size) {
2308 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2309 for (const ImageInfo& info : image_infos_) {
2310 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2311 }
2312 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002313
Vladimir Marko944da602016-02-19 12:27:55 +00002314 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2315 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2316 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2317 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2318 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002319
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002320 if (compile_app_image_) {
2321 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2322 return;
2323 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002324
2325 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002326 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002327 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002328 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002329 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2330 }
2331}
2332
Vladimir Marko944da602016-02-19 12:27:55 +00002333void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2334 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2335 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2336
2337 if (oat_index == GetDefaultOatIndex()) {
2338 // Primary oat file, read the trampolines.
2339 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2340 oat_header.GetInterpreterToInterpreterBridgeOffset();
2341 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2342 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2343 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2344 oat_header.GetJniDlsymLookupOffset();
2345 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2346 oat_header.GetQuickGenericJniTrampolineOffset();
2347 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2348 oat_header.GetQuickImtConflictTrampolineOffset();
2349 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2350 oat_header.GetQuickResolutionTrampolineOffset();
2351 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2352 oat_header.GetQuickToInterpreterBridgeOffset();
2353 }
2354}
2355
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002356ImageWriter::ImageWriter(
2357 const CompilerDriver& compiler_driver,
2358 uintptr_t image_begin,
2359 bool compile_pic,
2360 bool compile_app_image,
2361 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002362 const std::vector<const char*>& oat_filenames,
2363 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002364 : compiler_driver_(compiler_driver),
2365 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2366 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002367 compile_pic_(compile_pic),
2368 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002369 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002370 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002371 dirty_methods_(0u),
2372 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002373 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002374 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002375 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002376 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002377 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002378 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2379 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002380}
2381
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002382ImageWriter::ImageInfo::ImageInfo()
2383 : intern_table_(new InternTable),
2384 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002385
Brian Carlstrom7940e442013-07-12 13:46:57 -07002386} // namespace art