blob: 8bb462c6679aded7b3a5c3404e98f83f2bbe65bc [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 Chartierc7853442015-03-27 14:35:38 -0700440 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000441 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000442 size_t oat_index = GetOatIndexForDexCache(dex_cache);
443 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800444 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100445 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800446 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
447 start + layout.TypesOffset(),
448 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100449 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800450 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
451 start + layout.MethodsOffset(),
452 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100453 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800454 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
455 start + layout.FieldsOffset(),
456 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100457 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800458 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000459 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000460}
461
Jeff Haodcdc85b2015-12-04 14:06:18 -0800462void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100463 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800464 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000465 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800466 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000467 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100468 }
469}
470
Mathieu Chartiere401d142015-04-22 13:56:20 -0700471void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
472 DCHECK(arr != nullptr);
473 if (kIsDebugBuild) {
474 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800475 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700476 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800477 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800478 CHECK(klass == nullptr || KeepClass(klass))
479 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700480 }
481 }
482 }
483 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
484 // ArtMethods.
485 pointer_arrays_.emplace(arr, kBinArtMethodClean);
486}
487
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800488void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
489 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800490 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800491
492 // The magic happens here. We segregate objects into different bins based
493 // on how likely they are to get dirty at runtime.
494 //
495 // Likely-to-dirty objects get packed together into the same bin so that
496 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
497 // maximized.
498 //
499 // This means more pages will stay either clean or shared dirty (with zygote) and
500 // the app will use less of its own (private) memory.
501 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000502 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800503
504 if (kBinObjects) {
505 //
506 // Changing the bin of an object is purely a memory-use tuning.
507 // It has no change on runtime correctness.
508 //
509 // Memory analysis has determined that the following types of objects get dirtied
510 // the most:
511 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000512 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
513 // a fixed layout which helps improve generated code (using PC-relative addressing),
514 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
515 // Since these arrays are huge, most pages do not overlap other objects and it's not
516 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100517 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800518 // * Class'es which are verified [their clinit runs only at runtime]
519 // - classes in general [because their static fields get overwritten]
520 // - initialized classes with all-final statics are unlikely to be ever dirty,
521 // so bin them separately
522 // * Art Methods that are:
523 // - native [their native entry point is not looked up until runtime]
524 // - have declaring classes that aren't initialized
525 // [their interpreter/quick entry points are trampolines until the class
526 // becomes initialized]
527 //
528 // We also assume the following objects get dirtied either never or extremely rarely:
529 // * Strings (they are immutable)
530 // * Art methods that aren't native and have initialized declared classes
531 //
532 // We assume that "regular" bin objects are highly unlikely to become dirtied,
533 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
534 //
535 if (object->IsClass()) {
536 bin = kBinClassVerified;
537 mirror::Class* klass = object->AsClass();
538
Mathieu Chartiere401d142015-04-22 13:56:20 -0700539 // Add non-embedded vtable to the pointer array table if there is one.
540 auto* vtable = klass->GetVTable();
541 if (vtable != nullptr) {
542 AddMethodPointerArray(vtable);
543 }
544 auto* iftable = klass->GetIfTable();
545 if (iftable != nullptr) {
546 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
547 if (iftable->GetMethodArrayCount(i) > 0) {
548 AddMethodPointerArray(iftable->GetMethodArray(i));
549 }
550 }
551 }
552
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800553 if (klass->GetStatus() == Class::kStatusInitialized) {
554 bin = kBinClassInitialized;
555
556 // If the class's static fields are all final, put it into a separate bin
557 // since it's very likely it will stay clean.
558 uint32_t num_static_fields = klass->NumStaticFields();
559 if (num_static_fields == 0) {
560 bin = kBinClassInitializedFinalStatics;
561 } else {
562 // Maybe all the statics are final?
563 bool all_final = true;
564 for (uint32_t i = 0; i < num_static_fields; ++i) {
565 ArtField* field = klass->GetStaticField(i);
566 if (!field->IsFinal()) {
567 all_final = false;
568 break;
569 }
570 }
571
572 if (all_final) {
573 bin = kBinClassInitializedFinalStatics;
574 }
575 }
576 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800577 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
578 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700579 } else if (object->GetClass<kVerifyNone>() ==
580 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
581 // Instance of java lang object, probably a lock object. This means it will be dirty when we
582 // synchronize on it.
583 bin = kBinMiscDirty;
584 } else if (object->IsDexCache()) {
585 // Dex file field becomes dirty when the image is loaded.
586 bin = kBinMiscDirty;
587 }
588 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800589 }
590
Vladimir Marko944da602016-02-19 12:27:55 +0000591 size_t oat_index = GetOatIndex(object);
592 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800593
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800594 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800595 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
596 // Move the current bin size up to accommodate the object we just assigned a bin slot.
597 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800598
599 BinSlot new_bin_slot(bin, current_offset);
600 SetImageBinSlot(object, new_bin_slot);
601
Jeff Haodcdc85b2015-12-04 14:06:18 -0800602 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800603
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800604 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800605 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800606}
607
Mathieu Chartiere401d142015-04-22 13:56:20 -0700608bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
609 if (m->IsNative()) {
610 return true;
611 }
612 mirror::Class* declaring_class = m->GetDeclaringClass();
613 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
614 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
615}
616
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800617bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
618 DCHECK(object != nullptr);
619
620 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
621 // If it's in some other state, then we haven't yet assigned an image bin slot.
622 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
623 return false;
624 } else if (kIsDebugBuild) {
625 LockWord lock_word = object->GetLockWord(false);
626 size_t offset = lock_word.ForwardingAddress();
627 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000628 size_t oat_index = GetOatIndex(object);
629 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800630 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800631 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800632 }
633 return true;
634}
635
636ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
637 DCHECK(object != nullptr);
638 DCHECK(IsImageBinSlotAssigned(object));
639
640 LockWord lock_word = object->GetLockWord(false);
641 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
642 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
643
644 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000645 size_t oat_index = GetOatIndex(object);
646 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800647 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800648
649 return bin_slot;
650}
651
Brian Carlstrom7940e442013-07-12 13:46:57 -0700652bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000653 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800654 ImageSection unused_sections[ImageHeader::kSectionCount];
655 const size_t length = RoundUp(
656 image_info.CreateImageSections(target_ptr_size_, unused_sections),
657 kPageSize);
658
Jeff Haodcdc85b2015-12-04 14:06:18 -0800659 std::string error_msg;
660 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
661 nullptr,
662 length,
663 PROT_READ | PROT_WRITE,
664 false,
665 false,
666 &error_msg));
667 if (UNLIKELY(image_info.image_.get() == nullptr)) {
668 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
669 return false;
670 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700671
Jeff Haodcdc85b2015-12-04 14:06:18 -0800672 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
673 CHECK_LE(image_info.image_end_, length);
674 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
675 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
676 if (image_info.image_bitmap_.get() == nullptr) {
677 LOG(ERROR) << "Failed to allocate memory for image bitmap";
678 return false;
679 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700680 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700681 return true;
682}
683
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700684class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
685 public:
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800686 bool operator()(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700687 StackHandleScope<1> hs(Thread::Current());
688 mirror::Class::ComputeName(hs.NewHandle(c));
689 return true;
690 }
691};
692
Brian Carlstrom7940e442013-07-12 13:46:57 -0700693void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700694 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700695 ComputeLazyFieldsForClassesVisitor visitor;
696 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700697}
698
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800699static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
700 return klass->GetClassLoader() == nullptr;
701}
702
703bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
704 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
705}
706
Mathieu Chartier901e0702016-02-19 13:42:48 -0800707bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800708 bool early_exit = false;
709 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800710 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800711}
712
Mathieu Chartier901e0702016-02-19 13:42:48 -0800713bool ImageWriter::PruneAppImageClassInternal(
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800714 mirror::Class* klass,
715 bool* early_exit,
716 std::unordered_set<mirror::Class*>* visited) {
717 DCHECK(early_exit != nullptr);
718 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800719 DCHECK(compile_app_image_);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800720 if (klass == nullptr || IsInBootImage(klass)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700721 return false;
722 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800723 auto found = prune_class_memo_.find(klass);
724 if (found != prune_class_memo_.end()) {
725 // Already computed, return the found value.
726 return found->second;
727 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800728 // Circular dependencies, return false but do not store the result in the memoization table.
729 if (visited->find(klass) != visited->end()) {
730 *early_exit = true;
731 return false;
732 }
733 visited->emplace(klass);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800734 bool result = IsBootClassLoaderClass(klass);
735 std::string temp;
736 // Prune if not an image class, this handles any broken sets of image classes such as having a
737 // class in the set but not it's superclass.
738 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800739 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800740 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
741 // app image.
742 if (klass->GetStatus() == mirror::Class::kStatusError) {
743 result = true;
744 } else {
745 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
746 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800747 if (!result) {
748 // Check interfaces since these wont be visited through VisitReferences.)
749 mirror::IfTable* if_table = klass->GetIfTable();
750 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800751 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
752 &my_early_exit,
753 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800754 }
755 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800756 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800757 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
758 &my_early_exit,
759 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800760 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800761 // Check static fields and their classes.
762 size_t num_static_fields = klass->NumReferenceStaticFields();
763 if (num_static_fields != 0 && klass->IsResolved()) {
764 // Presumably GC can happen when we are cross compiling, it should not cause performance
765 // problems to do pointer size logic.
766 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
767 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
768 for (size_t i = 0u; i < num_static_fields; ++i) {
769 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
770 if (ref != nullptr) {
771 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800772 result = result || PruneAppImageClassInternal(ref->AsClass(),
773 &my_early_exit,
774 visited);
775 } else {
776 result = result || PruneAppImageClassInternal(ref->GetClass(),
777 &my_early_exit,
778 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800779 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800780 }
781 field_offset = MemberOffset(field_offset.Uint32Value() +
782 sizeof(mirror::HeapReference<mirror::Object>));
783 }
784 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800785 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
786 &my_early_exit,
787 visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800788 // Erase the element we stored earlier since we are exiting the function.
789 auto it = visited->find(klass);
790 DCHECK(it != visited->end());
791 visited->erase(it);
792 // Only store result if it is true or none of the calls early exited due to circular
793 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
794 // a child call and we can remember the result.
795 if (result == true || !my_early_exit || visited->empty()) {
796 prune_class_memo_[klass] = result;
797 }
798 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800799 return result;
800}
801
802bool ImageWriter::KeepClass(Class* klass) {
803 if (klass == nullptr) {
804 return false;
805 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800806 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
807 // Already in boot image, return true.
808 return true;
809 }
810 std::string temp;
811 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
812 return false;
813 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800814 if (compile_app_image_) {
815 // For app images, we need to prune boot loader classes that are not in the boot image since
816 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800817 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800818 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800819 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800820 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700821}
822
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700823class NonImageClassesVisitor : public ClassVisitor {
824 public:
825 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
826
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800827 bool operator()(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800828 if (!image_writer_->KeepClass(klass)) {
829 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700830 }
831 return true;
832 }
833
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800834 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700835 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700836};
837
838void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700839 Runtime* runtime = Runtime::Current();
840 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700841 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700842
843 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700844 NonImageClassesVisitor visitor(this);
845 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700846
847 // Remove the undesired classes from the class roots.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800848 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800849 for (mirror::Class* klass : visitor.classes_to_prune_) {
850 std::string temp;
851 const char* name = klass->GetDescriptor(&temp);
852 VLOG(compiler) << "Pruning class " << name;
853 if (!compile_app_image_) {
854 DCHECK(IsBootClassLoaderClass(klass));
855 }
856 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800857 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700858 }
859
860 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100861 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700862
863 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
864 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
865 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800866 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800867 if (self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700868 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700869 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800870 mirror::DexCache* dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700871 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
872 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800873 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700874 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700875 }
876 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100877 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
878 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
879 ArtMethod* method =
880 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800881 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
882 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800883 // 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 -0800884 // declaring class which is an image class. Set it to the resolution method to be safe and
885 // prevent dangling pointers.
Alex Light36121492016-02-22 13:43:29 -0800886 if (method->IsCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800887 mirror::DexCache::SetElementPtrSize(resolved_methods,
888 i,
889 resolution_method,
890 target_ptr_size_);
891 } else {
892 // Check that the class is still in the classes table.
893 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
894 << PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700895 }
896 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800897 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700898 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800899 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800900 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700901 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700902 }
903 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700904 // Clean the dex field. It might have been populated during the initialization phase, but
905 // contains data only valid during a real run.
906 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700907 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700908
909 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
910 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800911
912 // Clear to save RAM.
913 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700914}
915
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800916void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700917 if (compiler_driver_.GetImageClasses() != nullptr) {
918 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700919 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700920 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700921}
922
923void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
924 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800925 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700926 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800927 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700928 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700929 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800930 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
931 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700932 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700933 }
934}
935
936void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700937 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700938 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700939 for (const std::string& image_class : *image_classes) {
940 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700941 }
942}
943
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800944mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
945 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +0000946 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800947 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
948 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
949 << string->ToModifiedUtf8();
950 if (found != nullptr) {
951 return found;
952 }
953 }
954 if (compile_app_image_) {
955 Runtime* const runtime = Runtime::Current();
956 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
957 // If we found it in the runtime intern table it could either be in the boot image or interned
958 // during app image compilation. If it was in the boot image return that, otherwise return null
959 // since it belongs to another image space.
960 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
961 return found;
962 }
963 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
964 << string->ToModifiedUtf8();
965 }
966 return nullptr;
967}
968
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800969void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700970 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700971 // if it is a string, we want to intern it if its not interned.
972 if (obj->GetClass()->IsStringClass()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000973 size_t oat_index = GetOatIndex(obj);
974 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800975
Brian Carlstrom7940e442013-07-12 13:46:57 -0700976 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800977 if (IsImageBinSlotAssigned(obj)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800978 DCHECK_EQ(obj, FindInternedString(obj->AsString()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700979 return;
980 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800981 // Need to check if the string is already interned in another image info so that we don't have
982 // the intern tables of two different images contain the same string.
983 mirror::String* interned = FindInternedString(obj->AsString());
984 if (interned == nullptr) {
985 // Not in another image space, insert to our table.
986 interned = image_info.intern_table_->InternStrongImageString(obj->AsString());
987 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700988 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800989 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700990 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800991 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700992 }
993 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800994 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700995 return;
996 }
997 // else (obj == interned), nothing to do but fall through to the normal case
998 }
999
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001000 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001001}
1002
Vladimir Marko944da602016-02-19 12:27:55 +00001003ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001004 Runtime* runtime = Runtime::Current();
1005 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001006 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001007 StackHandleScope<3> hs(self);
1008 Handle<Class> object_array_class(hs.NewHandle(
1009 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001010
Jeff Haodcdc85b2015-12-04 14:06:18 -08001011 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +00001012 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001013 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +00001014 size_t image_oat_index = pair.second;
1015 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001016 image_dex_files.insert(image_dex_file);
1017 }
1018 }
1019
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001020 // build an Object[] of all the DexCaches used in the source_space_.
1021 // Since we can't hold the dex lock when allocating the dex_caches
1022 // ObjectArray, we lock the dex lock twice, first to get the number
1023 // of dex caches first and then lock it again to copy the dex
1024 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001025 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001026 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001027 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001028 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001029 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1030 mirror::DexCache* dex_cache =
1031 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001032 const DexFile* dex_file = dex_cache->GetDexFile();
1033 if (!IsInBootImage(dex_cache)) {
1034 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1035 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001036 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001037 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001038 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001039 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001040 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1041 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001042 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001043 size_t non_image_dex_caches = 0;
1044 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001045 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1046 mirror::DexCache* dex_cache =
1047 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001048 const DexFile* dex_file = dex_cache->GetDexFile();
1049 if (!IsInBootImage(dex_cache)) {
1050 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1051 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001052 }
1053 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1054 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001055 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001056 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1057 mirror::DexCache* dex_cache =
1058 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001059 const DexFile* dex_file = dex_cache->GetDexFile();
1060 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001061 dex_caches->Set<false>(i, dex_cache);
1062 ++i;
1063 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001064 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001065 }
1066
1067 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001068 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001069 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001070 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001071 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001072 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001073 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001074 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001075 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001076}
1077
Mathieu Chartier590fee92013-09-13 13:46:47 -07001078// Walk instance fields of the given Class. Separate function to allow recursion on the super
1079// class.
1080void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1081 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001082 StackHandleScope<1> hs(Thread::Current());
1083 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1084 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001085 if (super != nullptr) {
1086 WalkInstanceFields(obj, super);
1087 }
1088 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001089 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +00001090 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001091 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001092 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001093 if (value != nullptr) {
1094 WalkFieldsInOrder(value);
1095 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001096 field_offset = MemberOffset(field_offset.Uint32Value() +
1097 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001098 }
1099}
1100
1101// For an unvisited object, visit it then all its children found via fields.
1102void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001103 if (IsInBootImage(obj)) {
1104 // Object is in the image, don't need to fix it up.
1105 return;
1106 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001107 // Use our own visitor routine (instead of GC visitor) to get better locality between
1108 // an object and its fields
1109 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001110 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001111 StackHandleScope<2> hs(Thread::Current());
1112 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1113 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001114 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001115 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001116 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001117 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001118 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001119 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001120 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001121 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001122 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001123 if (value != nullptr) {
1124 WalkFieldsInOrder(value);
1125 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001126 field_offset = MemberOffset(field_offset.Uint32Value() +
1127 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001128 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001129 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001130 auto* as_klass = h_obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001131 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001132 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1133 if (compile_app_image_) {
1134 // Extra sanity, no boot loader classes should be left!
1135 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1136 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001137 LengthPrefixedArray<ArtField>* fields[] = {
1138 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1139 };
Vladimir Marko944da602016-02-19 12:27:55 +00001140 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1141 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001142 {
1143 // Note: This table is only accessed from the image writer, so the lock is technically
1144 // unnecessary.
1145 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1146 // Insert in the class table for this iamge.
1147 image_info.class_table_->Insert(as_klass);
1148 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001149 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1150 // Total array length including header.
1151 if (cur_fields != nullptr) {
1152 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1153 // Forward the entire array at once.
1154 auto it = native_object_relocations_.find(cur_fields);
1155 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1156 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001157 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001158 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001159 native_object_relocations_.emplace(
1160 cur_fields,
1161 NativeObjectRelocation {
1162 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1163 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001164 offset += header_size;
1165 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001166 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001167 // Need to forward arrays separate of fields.
1168 ArtField* field = &cur_fields->At(i);
1169 auto it2 = native_object_relocations_.find(field);
1170 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1171 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001172 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001173 native_object_relocations_.emplace(
1174 field,
1175 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001176 offset += sizeof(ArtField);
1177 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001178 }
1179 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001180 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001181 size_t num_methods = as_klass->NumMethods();
1182 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001183 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001184 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1185 if (WillMethodBeDirty(&m)) {
1186 any_dirty = true;
1187 break;
1188 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001189 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001190 NativeObjectRelocationType type = any_dirty
1191 ? kNativeObjectRelocationTypeArtMethodDirty
1192 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001193 Bin bin_type = BinTypeForNativeRelocationType(type);
1194 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001195 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1196 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001197 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1198 method_size,
1199 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001200 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001201 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001202 CHECK(it == native_object_relocations_.end())
1203 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001204 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001205 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001206 native_object_relocations_.emplace(array,
1207 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001208 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001209 offset,
1210 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1211 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001212 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001213 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001214 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001215 }
Alex Lighte64300b2015-12-15 15:02:47 -08001216 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001217 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001218 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001219 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001220 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001221 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001222 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001223 mirror::Object* value = obj_array->Get(i);
1224 if (value != nullptr) {
1225 WalkFieldsInOrder(value);
1226 }
1227 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001228 } else if (h_obj->IsClassLoader()) {
1229 // Register the class loader if it has a class table.
1230 // The fake boot class loader should not get registered and we should end up with only one
1231 // class loader.
1232 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1233 if (class_loader->GetClassTable() != nullptr) {
1234 class_loaders_.insert(class_loader);
1235 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001236 }
1237 }
1238}
1239
Jeff Haodcdc85b2015-12-04 14:06:18 -08001240void ImageWriter::AssignMethodOffset(ArtMethod* method,
1241 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001242 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001243 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001244 auto it = native_object_relocations_.find(method);
1245 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001246 << PrettyMethod(method);
Vladimir Marko944da602016-02-19 12:27:55 +00001247 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001248 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001249 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001250 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001251}
1252
Mathieu Chartier590fee92013-09-13 13:46:47 -07001253void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1254 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1255 DCHECK(writer != nullptr);
1256 writer->WalkFieldsInOrder(obj);
1257}
1258
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001259void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1260 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1261 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001262 if (!writer->IsInBootImage(obj)) {
1263 writer->UnbinObjectsIntoOffset(obj);
1264 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001265}
1266
1267void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001268 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001269 CHECK(obj != nullptr);
1270
1271 // We know the bin slot, and the total bin sizes for all objects by now,
1272 // so calculate the object's final image offset.
1273
1274 DCHECK(IsImageBinSlotAssigned(obj));
1275 BinSlot bin_slot = GetImageBinSlot(obj);
1276 // Change the lockword from a bin slot into an offset
1277 AssignImageOffset(obj, bin_slot);
1278}
1279
Vladimir Markof4da6752014-08-01 19:04:18 +01001280void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001281 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001282 StackHandleScopeCollection handles(self);
1283 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001284 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1285 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001286 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001287
Mathieu Chartiere401d142015-04-22 13:56:20 -07001288 auto* runtime = Runtime::Current();
1289 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001290
Mathieu Chartier31e89252013-08-28 11:29:12 -07001291 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001292 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001293 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001294
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001295 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1296 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001297 // Write the image runtime methods.
1298 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1299 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1300 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1301 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1302 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1303 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1304 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1305 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001306
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001307 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001308 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1309 auto it = native_object_relocations_.find(&image_method_array_);
1310 CHECK(it == native_object_relocations_.end());
Vladimir Marko944da602016-02-19 12:27:55 +00001311 ImageInfo& default_image_info = GetImageInfo(GetDefaultOatIndex());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001312 size_t& offset =
1313 default_image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001314 if (!compile_app_image_) {
1315 native_object_relocations_.emplace(&image_method_array_,
Vladimir Marko944da602016-02-19 12:27:55 +00001316 NativeObjectRelocation { GetDefaultOatIndex(), offset, image_method_type });
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001317 }
Vladimir Marko14632852015-08-17 12:07:23 +01001318 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001319 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001320 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001321 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001322 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001323 for (auto* m : image_methods_) {
1324 CHECK(m != nullptr);
1325 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001326 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1327 if (!IsInBootImage(m)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001328 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001329 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001330 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001331 // Calculate size of the dex cache arrays slot and prepare offsets.
1332 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001333
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001334 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001335 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001336 // Calculate how big the intern table will be after being serialized.
1337 InternTable* const intern_table = image_info.intern_table_.get();
1338 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1339 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001340 // Calculate the size of the class table.
1341 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1342 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001343 }
1344
Vladimir Markocf36d492015-08-12 19:27:26 +01001345 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001346 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001347 size_t bin_offset = image_objects_offset_begin_;
1348 for (size_t i = 0; i != kBinSize; ++i) {
1349 image_info.bin_slot_offsets_[i] = bin_offset;
1350 bin_offset += image_info.bin_slot_sizes_[i];
1351 if (i == kBinArtField) {
1352 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1353 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1354 DCHECK_ALIGNED(bin_offset, 4u);
1355 DCHECK(method_alignment == 4u || method_alignment == 8u);
1356 bin_offset = RoundUp(bin_offset, method_alignment);
1357 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001358 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001359 // NOTE: There may be additional padding between the bin slots and the intern table.
1360 DCHECK_EQ(image_info.image_end_,
1361 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001362 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001363
Jeff Haodcdc85b2015-12-04 14:06:18 -08001364 // Calculate image offsets.
1365 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001366 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001367 image_info.image_begin_ = global_image_begin_ + image_offset;
1368 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001369 ImageSection unused_sections[ImageHeader::kSectionCount];
1370 image_info.image_size_ = RoundUp(
1371 image_info.CreateImageSections(target_ptr_size_, unused_sections),
1372 kPageSize);
1373 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001374 image_offset += image_info.image_size_;
1375 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001376
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001377 // Transform each object's bin slot into an offset which will be used to do the final copy.
1378 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001379
Jeff Haodcdc85b2015-12-04 14:06:18 -08001380 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001381
Jeff Haodcdc85b2015-12-04 14:06:18 -08001382 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001383 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001384 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1385 i++;
1386 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001387
Mathieu Chartiere401d142015-04-22 13:56:20 -07001388 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001389 for (auto& pair : native_object_relocations_) {
1390 NativeObjectRelocation& relocation = pair.second;
1391 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001392 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001393 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001394 }
1395
Jeff Haodcdc85b2015-12-04 14:06:18 -08001396 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001397}
1398
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001399size_t ImageWriter::ImageInfo::CreateImageSections(size_t target_ptr_size,
1400 ImageSection* out_sections) const {
1401 DCHECK(out_sections != nullptr);
1402 // Objects section
1403 auto* objects_section = &out_sections[ImageHeader::kSectionObjects];
1404 *objects_section = ImageSection(0u, image_end_);
1405 size_t cur_pos = objects_section->End();
1406 // Add field section.
1407 auto* field_section = &out_sections[ImageHeader::kSectionArtFields];
1408 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
1409 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
1410 cur_pos = field_section->End();
1411 // Round up to the alignment the required by the method section.
1412 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size));
1413 // Add method section.
1414 auto* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1415 *methods_section = ImageSection(cur_pos,
1416 bin_slot_sizes_[kBinArtMethodClean] +
1417 bin_slot_sizes_[kBinArtMethodDirty]);
1418 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
1419 cur_pos = methods_section->End();
1420 // Add dex cache arrays section.
1421 auto* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1422 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1423 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1424 cur_pos = dex_cache_arrays_section->End();
1425 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1426 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1427 // Calculate the size of the interned strings.
1428 auto* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
1429 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1430 cur_pos = interned_strings_section->End();
1431 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1432 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1433 // Calculate the size of the class table section.
1434 auto* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001435 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001436 cur_pos = class_table_section->End();
1437 // Image end goes right before the start of the image bitmap.
1438 return cur_pos;
1439}
1440
Vladimir Marko944da602016-02-19 12:27:55 +00001441void ImageWriter::CreateHeader(size_t oat_index) {
1442 ImageInfo& image_info = GetImageInfo(oat_index);
1443 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1444 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1445 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001446
1447 // Create the image sections.
1448 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001449 const size_t image_end = image_info.CreateImageSections(target_ptr_size_, sections);
1450
Mathieu Chartiere401d142015-04-22 13:56:20 -07001451 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001452 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001453 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001454 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001455 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001456 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001457 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001458 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001459 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1460 ++idx;
1461 }
1462 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001463 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1464 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1465 << " Image offset=" << image_info.image_offset_ << std::dec;
1466 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1467 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1468 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1469 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001470 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001471 // Store boot image info for app image so that we can relocate.
1472 uint32_t boot_image_begin = 0;
1473 uint32_t boot_image_end = 0;
1474 uint32_t boot_oat_begin = 0;
1475 uint32_t boot_oat_end = 0;
1476 gc::Heap* const heap = Runtime::Current()->GetHeap();
1477 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001478
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001479 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1480 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001481 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1482 image_end,
1483 sections,
1484 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001485 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001486 PointerToLowMemUInt32(oat_file_begin),
1487 PointerToLowMemUInt32(image_info.oat_data_begin_),
1488 PointerToLowMemUInt32(oat_data_end),
1489 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001490 boot_image_begin,
1491 boot_image_end - boot_image_begin,
1492 boot_oat_begin,
1493 boot_oat_end - boot_oat_begin,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001494 target_ptr_size_,
1495 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001496 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001497 image_storage_mode_,
1498 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001499}
1500
1501ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001502 auto it = native_object_relocations_.find(method);
1503 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001504 size_t oat_index = GetOatIndex(method->GetDexCache());
1505 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001506 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1507 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001508}
1509
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001510class FixupRootVisitor : public RootVisitor {
1511 public:
1512 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1513 }
1514
1515 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001516 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001517 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001518 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001519 }
1520 }
1521
1522 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1523 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001524 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001525 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001526 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001527 }
1528 }
1529
1530 private:
1531 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001532};
1533
Vladimir Marko944da602016-02-19 12:27:55 +00001534void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
1535 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001536 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001537 for (auto& pair : native_object_relocations_) {
1538 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001539 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001540 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001541 continue;
1542 }
1543 auto* dest = image_info.image_->Begin() + relocation.offset;
1544 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001545 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001546 switch (relocation.type) {
1547 case kNativeObjectRelocationTypeArtField: {
1548 memcpy(dest, pair.first, sizeof(ArtField));
1549 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1550 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1551 break;
1552 }
1553 case kNativeObjectRelocationTypeArtMethodClean:
1554 case kNativeObjectRelocationTypeArtMethodDirty: {
1555 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001556 reinterpret_cast<ArtMethod*>(dest),
1557 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001558 break;
1559 }
1560 // For arrays, copy just the header since the elements will get copied by their corresponding
1561 // relocations.
1562 case kNativeObjectRelocationTypeArtFieldArray: {
1563 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1564 break;
1565 }
1566 case kNativeObjectRelocationTypeArtMethodArrayClean:
1567 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00001568 size_t size = ArtMethod::Size(target_ptr_size_);
1569 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1570 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1571 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1572 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001573 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00001574 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001575 case kNativeObjectRelocationTypeDexCacheArray:
1576 // Nothing to copy here, everything is done in FixupDexCache().
1577 break;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001578 }
1579 }
1580 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001581 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001582 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001583 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001584 ArtMethod* method = image_methods_[i];
1585 CHECK(method != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001586 // Only place runtime methods in the image of the default oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001587 if (method->IsRuntimeMethod() && oat_index != GetDefaultOatIndex()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001588 continue;
1589 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001590 if (!IsInBootImage(method)) {
1591 auto it = native_object_relocations_.find(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001592 CHECK(it != native_object_relocations_.end()) << "No forwarding for " << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001593 NativeObjectRelocation& relocation = it->second;
1594 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1595 << methods_section;
1596 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001597 method = reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001598 }
1599 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001600 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001601 FixupRootVisitor root_visitor(this);
1602
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001603 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001604 if (image_info.intern_table_bytes_ > 0) {
1605 const ImageSection& intern_table_section = image_header->GetImageSection(
1606 ImageHeader::kSectionInternedStrings);
1607 InternTable* const intern_table = image_info.intern_table_.get();
1608 uint8_t* const intern_table_memory_ptr =
1609 image_info.image_->Begin() + intern_table_section.Offset();
1610 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1611 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1612 // Fixup the pointers in the newly written intern table to contain image addresses.
1613 InternTable temp_intern_table;
1614 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1615 // the VisitRoots() will update the memory directly rather than the copies.
1616 // This also relies on visit roots not doing any verification which could fail after we update
1617 // the roots to be the image addresses.
1618 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1619 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1620 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1621 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001622 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1623 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001624 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001625 const ImageSection& class_table_section = image_header->GetImageSection(
1626 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001627 uint8_t* const class_table_memory_ptr =
1628 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001629 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001630
1631 ClassTable* table = image_info.class_table_.get();
1632 CHECK(table != nullptr);
1633 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1634 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1635 // Fixup the pointers in the newly written class table to contain image addresses. See
1636 // above comment for intern tables.
1637 ClassTable temp_class_table;
1638 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1639 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1640 table->NumZygoteClasses());
1641 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1642 RootInfo(kRootUnknown));
1643 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001644 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001645}
1646
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001647void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001648 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001649 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1650 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001651 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001652 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001653 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1654 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001655 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001656 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001657}
1658
Mathieu Chartier590fee92013-09-13 13:46:47 -07001659void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001660 DCHECK(obj != nullptr);
1661 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001662 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1663}
1664
Mathieu Chartiere401d142015-04-22 13:56:20 -07001665void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1666 mirror::Class* klass, Bin array_type) {
1667 CHECK(klass->IsArrayClass());
1668 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1669 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001670 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001671 dst->SetClass(GetImageAddress(arr->GetClass()));
1672 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001673 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001674 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1675 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001676 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001677 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001678 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001679 auto* method = reinterpret_cast<ArtMethod*>(elem);
1680 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1681 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1682 << PrettyClass(method->GetDeclaringClass());
1683 } else {
1684 CHECK_EQ(array_type, kBinArtField);
1685 auto* field = reinterpret_cast<ArtField*>(elem);
1686 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1687 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1688 << PrettyClass(field->GetDeclaringClass());
1689 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001690 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001691 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001692 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001693 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001694 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001695 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001696 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001697 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001698}
1699
1700void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001701 if (IsInBootImage(obj)) {
1702 return;
1703 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001704 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001705 size_t oat_index = GetOatIndex(obj);
1706 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001707 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1708 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001709 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001710
Jeff Haodcdc85b2015-12-04 14:06:18 -08001711 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001712
1713 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001714 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001715 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001716
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001717 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1718 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001719 const auto it = saved_hashcode_map_.find(obj);
1720 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1721 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001722 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001723}
1724
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001725// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001726class FixupVisitor {
1727 public:
1728 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1729 }
1730
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001731 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1732 // with other logic.
1733 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1734 const {}
1735 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1736
1737
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001738 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001739 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001740 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001741 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1742 // image.
1743 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001744 offset,
1745 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001746 }
1747
1748 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001749 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001750 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001751 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001752 mirror::Reference::ReferentOffset(),
1753 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001754 }
1755
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001756 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001757 ImageWriter* const image_writer_;
1758 mirror::Object* const copy_;
1759};
1760
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001761class FixupClassVisitor FINAL : public FixupVisitor {
1762 public:
1763 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1764 }
1765
Mathieu Chartierc7853442015-03-27 14:35:38 -07001766 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001767 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001768 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001769 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001770 }
1771
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001772 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1773 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001774 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001775 LOG(FATAL) << "Reference not expected here.";
1776 }
1777};
1778
Vladimir Marko05792b92015-08-03 11:56:49 +01001779uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1780 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001781 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001782 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001783 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1784 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001785 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001786 return relocation.offset;
1787}
1788
1789template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001790T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001791 if (obj == nullptr || IsInBootImage(obj)) {
1792 return obj;
1793 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001794 auto it = native_object_relocations_.find(obj);
1795 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1796 << Runtime::Current()->GetHeap()->DumpSpaces();
1797 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00001798 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001799 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001800 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001801}
1802
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001803template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001804T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1805 if (obj == nullptr || IsInBootImage(obj)) {
1806 return obj;
1807 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001808 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1809 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001810 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1811 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001812}
1813
1814class NativeLocationVisitor {
1815 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001816 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001817
1818 template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001819 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001820 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001821 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001822
1823 private:
1824 ImageWriter* const image_writer_;
1825};
1826
1827void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001828 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001829 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001830 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001831
1832 // Remove the clinitThreadId. This is required for image determinism.
1833 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001834}
1835
Ian Rogersef7d42f2014-01-06 12:55:46 -08001836void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001837 DCHECK(orig != nullptr);
1838 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001839 if (kUseBakerOrBrooksReadBarrier) {
1840 orig->AssertReadBarrierPointer();
1841 if (kUseBrooksReadBarrier) {
1842 // Note the address 'copy' isn't the same as the image address of 'orig'.
1843 copy->SetReadBarrierPointer(GetImageAddress(orig));
1844 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1845 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001846 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001847 auto* klass = orig->GetClass();
1848 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001849 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001850 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1851 if (it != pointer_arrays_.end()) {
1852 // Should only need to fixup every pointer array exactly once.
1853 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1854 pointer_arrays_.erase(it);
1855 return;
1856 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001857 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001858 if (orig->IsClass()) {
1859 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001860 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001861 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1862 // Need to go update the ArtMethod.
1863 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1864 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1865 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001866 auto it = native_object_relocations_.find(src_method);
1867 CHECK(it != native_object_relocations_.end())
1868 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001869 dest->SetArtMethod(
Jeff Haodcdc85b2015-12-04 14:06:18 -08001870 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001871 } else if (!klass->IsArrayClass()) {
1872 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1873 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1874 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001875 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001876 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01001877 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1878 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001879 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001880 // Also set allocator to null to be safe. The allocator is created when we create the class
1881 // table. We also never expect to unload things in the image since they are held live as
1882 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001883 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001884 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001885 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001886 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001887 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001888 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001889}
1890
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001891
1892class ImageAddressVisitor {
1893 public:
1894 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1895
1896 template <typename T>
1897 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1898 return image_writer_->GetImageAddress(ptr);
1899 }
1900
1901 private:
1902 ImageWriter* const image_writer_;
1903};
1904
1905
Vladimir Marko05792b92015-08-03 11:56:49 +01001906void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1907 mirror::DexCache* copy_dex_cache) {
1908 // Though the DexCache array fields are usually treated as native pointers, we set the full
1909 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1910 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1911 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1912 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1913 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001914 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001915 NativeLocationInImage(orig_strings),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001916 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001917 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
1918 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001919 }
1920 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1921 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001922 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001923 NativeLocationInImage(orig_types),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001924 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001925 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
1926 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001927 }
1928 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1929 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001930 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001931 NativeLocationInImage(orig_methods),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001932 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001933 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001934 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1935 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001936 // NativeLocationInImage also handles runtime methods since these have relocation info.
1937 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001938 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1939 }
1940 }
1941 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1942 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001943 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001944 NativeLocationInImage(orig_fields),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001945 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001946 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001947 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1948 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001949 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001950 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1951 }
1952 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001953
1954 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
1955 // compiler pointers in here will make the output non-deterministic.
1956 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001957}
1958
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001959const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1960 DCHECK_LT(type, kOatAddressCount);
1961 // If we are compiling an app image, we need to use the stubs of the boot image.
1962 if (compile_app_image_) {
1963 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001964 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08001965 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1966 DCHECK(!image_spaces.empty());
1967 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001968 CHECK(oat_file != nullptr);
1969 const OatHeader& header = oat_file->GetOatHeader();
1970 switch (type) {
1971 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1972 case kOatAddressQuickGenericJNITrampoline:
1973 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1974 case kOatAddressInterpreterToInterpreterBridge:
1975 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1976 case kOatAddressInterpreterToCompiledCodeBridge:
1977 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1978 case kOatAddressJNIDlsymLookup:
1979 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1980 case kOatAddressQuickIMTConflictTrampoline:
1981 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1982 case kOatAddressQuickResolutionTrampoline:
1983 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1984 case kOatAddressQuickToInterpreterBridge:
1985 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1986 default:
1987 UNREACHABLE();
1988 }
1989 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001990 const ImageInfo& primary_image_info = GetImageInfo(0);
1991 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001992}
1993
Jeff Haodcdc85b2015-12-04 14:06:18 -08001994const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
1995 const ImageInfo& image_info,
1996 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001997 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
Nicolas Geoffray796d6302016-03-13 22:22:31 +00001998 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001999 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07002000 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002001 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002002
2003 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2004 // trampoline.
2005
2006 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002007 const void* quick_oat_entry_point =
2008 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2009 const uint8_t* quick_code;
2010
2011 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2012 DCHECK(method->IsCopied());
2013 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2014 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2015 } else {
2016 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2017 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2018 }
2019
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002020 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002021 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2022 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002023 // We have code for a non-static or initialized method, just use the code.
2024 } else if (quick_code == nullptr && method->IsNative() &&
2025 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2026 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002027 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002028 } else if (quick_code == nullptr && !method->IsNative()) {
2029 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002030 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002031 *quick_is_interpreted = true;
2032 } else {
2033 CHECK(!method->GetDeclaringClass()->IsInitialized());
2034 // We have code for a static method, but need to go through the resolution stub for class
2035 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002036 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2037 }
2038 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002039 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002040 }
2041 return quick_code;
2042}
2043
Jeff Haodcdc85b2015-12-04 14:06:18 -08002044void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2045 ArtMethod* copy,
2046 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002047 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002048
2049 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002050 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002051 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002052 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002053 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002054
Ian Rogers848871b2013-08-05 10:56:33 -07002055 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2056 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002057
Ian Rogers848871b2013-08-05 10:56:33 -07002058 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002059 Runtime* runtime = Runtime::Current();
2060 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002061 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002062 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002063 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
2064 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002065 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002066 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002067 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
2068 bool found_one = false;
2069 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2070 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2071 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2072 found_one = true;
2073 break;
2074 }
2075 }
2076 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2077 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002078 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002079 // We assume all methods have code. If they don't currently then we set them to the use the
2080 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2081 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002082 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002083 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002084 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002085 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002086 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002087 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002088 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002089
Sebastien Hertze1d07812014-05-21 15:44:09 +02002090 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002091 if (orig->IsNative()) {
2092 // The native method's pointer is set to a stub to lookup via dlsym.
2093 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002094 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002095 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002096 }
2097 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002098 }
2099}
2100
Jeff Haodcdc85b2015-12-04 14:06:18 -08002101size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002102 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002103 return std::accumulate(&image_info.bin_slot_sizes_[0],
2104 &image_info.bin_slot_sizes_[up_to],
2105 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002106}
2107
2108ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2109 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002110 static_assert(kBinBits == 3, "wrong number of bin bits");
2111 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002112 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2113
2114 DCHECK_LT(GetBin(), kBinSize);
2115 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2116}
2117
2118ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2119 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2120 DCHECK_EQ(index, GetIndex());
2121}
2122
2123ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2124 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2125}
2126
2127uint32_t ImageWriter::BinSlot::GetIndex() const {
2128 return lockword_ & ~kBinMask;
2129}
2130
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002131ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2132 switch (type) {
2133 case kNativeObjectRelocationTypeArtField:
2134 case kNativeObjectRelocationTypeArtFieldArray:
2135 return kBinArtField;
2136 case kNativeObjectRelocationTypeArtMethodClean:
2137 case kNativeObjectRelocationTypeArtMethodArrayClean:
2138 return kBinArtMethodClean;
2139 case kNativeObjectRelocationTypeArtMethodDirty:
2140 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2141 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002142 case kNativeObjectRelocationTypeDexCacheArray:
2143 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002144 }
2145 UNREACHABLE();
2146}
2147
Vladimir Marko944da602016-02-19 12:27:55 +00002148size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002149 if (compile_app_image_) {
Vladimir Marko944da602016-02-19 12:27:55 +00002150 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002151 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002152 mirror::DexCache* dex_cache =
2153 obj->IsDexCache() ? obj->AsDexCache()
2154 : obj->IsClass() ? obj->AsClass()->GetDexCache()
2155 : obj->GetClass()->GetDexCache();
2156 return GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002157 }
2158}
2159
Vladimir Marko944da602016-02-19 12:27:55 +00002160size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
2161 if (compile_app_image_) {
2162 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002163 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002164 auto it = dex_file_oat_index_map_.find(dex_file);
2165 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002166 return it->second;
2167 }
2168}
2169
Vladimir Marko944da602016-02-19 12:27:55 +00002170size_t ImageWriter::GetOatIndexForDexCache(mirror::DexCache* dex_cache) const {
2171 if (dex_cache == nullptr) {
2172 return GetDefaultOatIndex();
2173 } else {
2174 return GetOatIndexForDexFile(dex_cache->GetDexFile());
2175 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002176}
2177
Vladimir Marko944da602016-02-19 12:27:55 +00002178void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2179 size_t oat_loaded_size,
2180 size_t oat_data_offset,
2181 size_t oat_data_size) {
2182 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2183 for (const ImageInfo& info : image_infos_) {
2184 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2185 }
2186 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002187
Vladimir Marko944da602016-02-19 12:27:55 +00002188 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2189 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2190 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2191 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2192 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002193
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002194 if (compile_app_image_) {
2195 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2196 return;
2197 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002198
2199 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002200 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002201 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002202 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002203 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2204 }
2205}
2206
Vladimir Marko944da602016-02-19 12:27:55 +00002207void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2208 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2209 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2210
2211 if (oat_index == GetDefaultOatIndex()) {
2212 // Primary oat file, read the trampolines.
2213 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2214 oat_header.GetInterpreterToInterpreterBridgeOffset();
2215 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2216 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2217 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2218 oat_header.GetJniDlsymLookupOffset();
2219 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2220 oat_header.GetQuickGenericJniTrampolineOffset();
2221 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2222 oat_header.GetQuickImtConflictTrampolineOffset();
2223 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2224 oat_header.GetQuickResolutionTrampolineOffset();
2225 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2226 oat_header.GetQuickToInterpreterBridgeOffset();
2227 }
2228}
2229
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002230ImageWriter::ImageWriter(
2231 const CompilerDriver& compiler_driver,
2232 uintptr_t image_begin,
2233 bool compile_pic,
2234 bool compile_app_image,
2235 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002236 const std::vector<const char*>& oat_filenames,
2237 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002238 : compiler_driver_(compiler_driver),
2239 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2240 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002241 compile_pic_(compile_pic),
2242 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002243 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002244 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002245 image_method_array_(ImageHeader::kImageMethodsCount),
2246 dirty_methods_(0u),
2247 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002248 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002249 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002250 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002251 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002252 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002253 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2254 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002255}
2256
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002257ImageWriter::ImageInfo::ImageInfo()
2258 : intern_table_(new InternTable),
2259 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002260
Brian Carlstrom7940e442013-07-12 13:46:57 -07002261} // namespace art