blob: 412225c3be77929630989a509d42e606c5cd4016 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "image_writer.h"
18
19#include <sys/stat.h>
Mathieu Chartierceb07b32015-12-10 09:33:21 -080020#include <lz4.h>
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -080021#include <lz4hc.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Vladimir Marko20f85592015-03-19 10:07:02 +000024#include <numeric>
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080025#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070026#include <vector>
27
Mathieu Chartierc7853442015-03-27 14:35:38 -070028#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070029#include "art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070030#include "base/logging.h"
31#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010032#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070033#include "compiled_method.h"
34#include "dex_file-inl.h"
35#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070036#include "elf_file.h"
37#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "elf_writer.h"
39#include "gc/accounting/card_table-inl.h"
40#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070041#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier36a270a2016-07-28 18:08:51 -070042#include "gc/collector/concurrent_copying.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070043#include "gc/heap.h"
44#include "gc/space/large_object_space.h"
45#include "gc/space/space-inl.h"
46#include "globals.h"
47#include "image.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070048#include "imt_conflict_table.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070050#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070051#include "lock_word.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070052#include "mirror/array-inl.h"
53#include "mirror/class-inl.h"
54#include "mirror/class_loader.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070055#include "mirror/dex_cache.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "mirror/dex_cache-inl.h"
Neil Fuller0e844392016-09-08 13:43:31 +010057#include "mirror/executable.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070058#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "mirror/object-inl.h"
60#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070061#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "oat.h"
63#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070064#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070066#include "scoped_thread_state_change-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070067#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000068#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070069
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070070using ::art::mirror::Class;
71using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070072using ::art::mirror::Object;
73using ::art::mirror::ObjectArray;
74using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070075
76namespace art {
77
Igor Murashkinf5b4c502014-11-14 15:01:59 -080078// Separate objects into multiple bins to optimize dirty memory use.
79static constexpr bool kBinObjects = true;
80
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080081// Return true if an object is already in an image space.
82bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080083 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080084 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080085 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080086 return false;
87 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080088 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
89 const uint8_t* image_begin = boot_image_space->Begin();
90 // Real image end including ArtMethods and ArtField sections.
91 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
92 if (image_begin <= obj && obj < image_end) {
93 return true;
94 }
95 }
96 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080097}
98
99bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800100 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800101 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800102 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800103 return false;
104 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800105 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
106 const ImageHeader& image_header = boot_image_space->GetImageHeader();
107 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
108 return true;
109 }
110 }
111 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800112}
113
Andreas Gampedd9d0552015-03-09 12:57:41 -0700114static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700115 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700116 Class* klass = obj->GetClass();
117 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
118}
119
120static void CheckNoDexObjects() {
121 ScopedObjectAccess soa(Thread::Current());
122 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
123}
124
Vladimir Markof4da6752014-08-01 19:04:18 +0100125bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800126 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800127 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100128 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700129 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100130 PruneNonImageClasses(); // Remove junk
Mathieu Chartier901e0702016-02-19 13:42:48 -0800131 if (!compile_app_image_) {
132 // Avoid for app image since this may increase RAM and image size.
133 ComputeLazyFieldsForImageClasses(); // Add useful information
134 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100135 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100136 heap->CollectGarbage(false); // Remove garbage.
137
Andreas Gampedd9d0552015-03-09 12:57:41 -0700138 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
139 // dex files.
140 //
141 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
142 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
143 // true.
144 if (kIsDebugBuild) {
145 CheckNoDexObjects();
146 }
147
Vladimir Markof4da6752014-08-01 19:04:18 +0100148 if (kIsDebugBuild) {
149 ScopedObjectAccess soa(Thread::Current());
150 CheckNonImageClassesRemoved();
151 }
152
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700153 {
154 ScopedObjectAccess soa(Thread::Current());
155 CalculateNewObjectOffsets();
156 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100157
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700158 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
159 // bin size sums being calculated.
160 if (!AllocMemory()) {
161 return false;
162 }
163
Vladimir Markof4da6752014-08-01 19:04:18 +0100164 return true;
165}
166
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700167bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800168 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000169 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800170 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
171 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800172 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800173 if (image_fd != kInvalidFd) {
174 CHECK_EQ(image_filenames.size(), 1u);
175 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800176 CHECK(!oat_filenames.empty());
177 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178
Vladimir Marko944da602016-02-19 12:27:55 +0000179 {
180 ScopedObjectAccess soa(Thread::Current());
181 for (size_t i = 0; i < oat_filenames.size(); ++i) {
182 CreateHeader(i);
183 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800184 }
185 }
Alex Light53cb16b2014-06-12 11:26:29 -0700186
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700187 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700188 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800189 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700190 Runtime::Current()->GetHeap()->DisableObjectValidation();
191 CopyAndFixupObjects();
192 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700193
Jeff Haodcdc85b2015-12-04 14:06:18 -0800194 for (size_t i = 0; i < image_filenames.size(); ++i) {
195 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000196 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800197 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800198 if (image_fd != kInvalidFd) {
199 if (strlen(image_filename) == 0u) {
200 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800201 // Empty the file in case it already exists.
202 if (image_file != nullptr) {
203 TEMP_FAILURE_RETRY(image_file->SetLength(0));
204 TEMP_FAILURE_RETRY(image_file->Flush());
205 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800206 } else {
207 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
208 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800209 } else {
210 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800211 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800212
Jeff Haodcdc85b2015-12-04 14:06:18 -0800213 if (image_file == nullptr) {
214 LOG(ERROR) << "Failed to open image file " << image_filename;
215 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800216 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800217
218 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800219 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
220 image_file->Erase();
221 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800222 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800223
Jeff Haodcdc85b2015-12-04 14:06:18 -0800224 std::unique_ptr<char[]> compressed_data;
225 // Image data size excludes the bitmap and the header.
226 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
227 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
228 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
229 size_t data_size;
230 const char* image_data_to_write;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800231 const uint64_t compress_start_time = NanoTime();
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000232
Jeff Haodcdc85b2015-12-04 14:06:18 -0800233 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
234 switch (image_storage_mode_) {
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700235 case ImageHeader::kStorageModeLZ4HC: // Fall-through.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800236 case ImageHeader::kStorageModeLZ4: {
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800237 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800238 compressed_data.reset(new char[compressed_max_size]);
239 data_size = LZ4_compress(
240 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
241 &compressed_data[0],
242 image_data_size);
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800243
244 break;
245 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700246 /*
247 * Disabled due to image_test64 flakyness. Both use same decompression. b/27560444
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800248 case ImageHeader::kStorageModeLZ4HC: {
249 // Bound is same as non HC.
250 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
251 compressed_data.reset(new char[compressed_max_size]);
252 data_size = LZ4_compressHC(
253 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
254 &compressed_data[0],
255 image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800256 break;
257 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700258 */
Jeff Haodcdc85b2015-12-04 14:06:18 -0800259 case ImageHeader::kStorageModeUncompressed: {
260 data_size = image_data_size;
261 image_data_to_write = image_data;
262 break;
263 }
264 default: {
265 LOG(FATAL) << "Unsupported";
266 UNREACHABLE();
267 }
268 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800269
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800270 if (compressed_data != nullptr) {
271 image_data_to_write = &compressed_data[0];
272 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
273 << PrettyDuration(NanoTime() - compress_start_time);
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700274 if (kIsDebugBuild) {
275 std::unique_ptr<uint8_t[]> temp(new uint8_t[image_data_size]);
276 const size_t decompressed_size = LZ4_decompress_safe(
277 reinterpret_cast<char*>(&compressed_data[0]),
278 reinterpret_cast<char*>(&temp[0]),
279 data_size,
280 image_data_size);
281 CHECK_EQ(decompressed_size, image_data_size);
282 CHECK_EQ(memcmp(image_data, &temp[0], image_data_size), 0) << image_storage_mode_;
283 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800284 }
285
Jeff Haodcdc85b2015-12-04 14:06:18 -0800286 // Write out the image + fields + methods.
287 const bool is_compressed = compressed_data != nullptr;
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800288 if (!image_file->PwriteFully(image_data_to_write, data_size, sizeof(ImageHeader))) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800289 PLOG(ERROR) << "Failed to write image file data " << image_filename;
290 image_file->Erase();
291 return false;
292 }
293
294 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
295 // convenience.
296 const ImageSection& bitmap_section = image_header->GetImageSection(
297 ImageHeader::kSectionImageBitmap);
298 // Align up since data size may be unaligned if the image is compressed.
299 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
300 if (!is_compressed) {
301 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
302 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800303 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
304 bitmap_section.Size(),
305 bitmap_position_in_file)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800306 PLOG(ERROR) << "Failed to write image file " << image_filename;
307 image_file->Erase();
308 return false;
309 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800310
311 int err = image_file->Flush();
312 if (err < 0) {
313 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
314 image_file->Erase();
315 return false;
316 }
317
318 // Write header last in case the compiler gets killed in the middle of image writing.
319 // We do not want to have a corrupted image with a valid header.
320 // The header is uncompressed since it contains whether the image is compressed or not.
321 image_header->data_size_ = data_size;
322 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
323 sizeof(ImageHeader),
324 0)) {
325 PLOG(ERROR) << "Failed to write image file header " << image_filename;
326 image_file->Erase();
327 return false;
328 }
329
Jeff Haodcdc85b2015-12-04 14:06:18 -0800330 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
331 static_cast<size_t>(image_file->GetLength()));
332 if (image_file->FlushCloseOrErase() != 0) {
333 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
334 return false;
335 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800336 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700337 return true;
338}
339
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700340void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700341 DCHECK(object != nullptr);
342 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800343
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800344 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700345 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700346 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700347 DCHECK(IsImageOffsetAssigned(object));
348}
349
Mathieu Chartiere401d142015-04-22 13:56:20 -0700350void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
351 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
352 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
353 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
354}
355
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800356void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700357 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800358 DCHECK_NE(image_objects_offset_begin_, 0u);
359
Vladimir Marko944da602016-02-19 12:27:55 +0000360 size_t oat_index = GetOatIndex(object);
361 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800362 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100363 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800364 DCHECK_ALIGNED(new_offset, kObjectAlignment);
365
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700366 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800367 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700368}
369
Ian Rogersef7d42f2014-01-06 12:55:46 -0800370bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800371 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700372 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700373 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700374}
375
Ian Rogersef7d42f2014-01-06 12:55:46 -0800376size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700377 DCHECK(object != nullptr);
378 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700379 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700380 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000381 size_t oat_index = GetOatIndex(object);
382 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800383 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700384 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700385}
386
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800387void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
388 DCHECK(object != nullptr);
389 DCHECK(!IsImageOffsetAssigned(object));
390 DCHECK(!IsImageBinSlotAssigned(object));
391
392 // Before we stomp over the lock word, save the hash code for later.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800393 LockWord lw(object->GetLockWord(false));
394 switch (lw.GetState()) {
395 case LockWord::kFatLocked: {
396 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
397 break;
398 }
399 case LockWord::kThinLocked: {
400 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
401 break;
402 }
403 case LockWord::kUnlocked:
404 // No hash, don't need to save it.
405 break;
406 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700407 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
408 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800409 break;
410 default:
411 LOG(FATAL) << "Unreachable.";
412 UNREACHABLE();
413 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700414 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700415 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800416 DCHECK(IsImageBinSlotAssigned(object));
417}
418
Vladimir Marko20f85592015-03-19 10:07:02 +0000419void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000420 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000421 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
422 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800423 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000424 auto it = dex_file_oat_index_map_.find(dex_file);
425 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800426 ImageInfo& image_info = GetImageInfo(it->second);
427 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
428 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
429 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
430 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000431
Vladimir Marko20f85592015-03-19 10:07:02 +0000432 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700433 Thread* const self = Thread::Current();
434 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800435 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700436 ObjPtr<mirror::DexCache> dex_cache =
437 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
438 if (dex_cache == nullptr || IsInBootImage(dex_cache.Ptr())) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700439 continue;
440 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000441 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartier0b490842016-05-25 15:05:59 -0700442 CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
443 << "Dex cache should have been pruned " << dex_file->GetLocation()
444 << "; possibly in class path";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700445 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000446 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000447 size_t oat_index = GetOatIndexForDexCache(dex_cache);
448 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800449 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100450 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800451 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
452 start + layout.TypesOffset(),
453 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100454 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800455 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
456 start + layout.MethodsOffset(),
457 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100458 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800459 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
460 start + layout.FieldsOffset(),
461 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100462 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800463 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000464 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000465}
466
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700467void ImageWriter::AddDexCacheArrayRelocation(void* array,
468 size_t offset,
469 ObjPtr<mirror::DexCache> dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100470 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800471 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000472 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800473 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000474 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100475 }
476}
477
Mathieu Chartiere401d142015-04-22 13:56:20 -0700478void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
479 DCHECK(arr != nullptr);
480 if (kIsDebugBuild) {
481 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800482 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700483 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800484 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800485 CHECK(klass == nullptr || KeepClass(klass))
486 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700487 }
488 }
489 }
490 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
491 // ArtMethods.
492 pointer_arrays_.emplace(arr, kBinArtMethodClean);
493}
494
Mathieu Chartier496577f2016-09-20 15:33:31 -0700495void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800496 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800497 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800498
499 // The magic happens here. We segregate objects into different bins based
500 // on how likely they are to get dirty at runtime.
501 //
502 // Likely-to-dirty objects get packed together into the same bin so that
503 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
504 // maximized.
505 //
506 // This means more pages will stay either clean or shared dirty (with zygote) and
507 // the app will use less of its own (private) memory.
508 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000509 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800510
511 if (kBinObjects) {
512 //
513 // Changing the bin of an object is purely a memory-use tuning.
514 // It has no change on runtime correctness.
515 //
516 // Memory analysis has determined that the following types of objects get dirtied
517 // the most:
518 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000519 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
520 // a fixed layout which helps improve generated code (using PC-relative addressing),
521 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
522 // Since these arrays are huge, most pages do not overlap other objects and it's not
523 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100524 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800525 // * Class'es which are verified [their clinit runs only at runtime]
526 // - classes in general [because their static fields get overwritten]
527 // - initialized classes with all-final statics are unlikely to be ever dirty,
528 // so bin them separately
529 // * Art Methods that are:
530 // - native [their native entry point is not looked up until runtime]
531 // - have declaring classes that aren't initialized
532 // [their interpreter/quick entry points are trampolines until the class
533 // becomes initialized]
534 //
535 // We also assume the following objects get dirtied either never or extremely rarely:
536 // * Strings (they are immutable)
537 // * Art methods that aren't native and have initialized declared classes
538 //
539 // We assume that "regular" bin objects are highly unlikely to become dirtied,
540 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
541 //
542 if (object->IsClass()) {
543 bin = kBinClassVerified;
544 mirror::Class* klass = object->AsClass();
545
Mathieu Chartiere401d142015-04-22 13:56:20 -0700546 // Add non-embedded vtable to the pointer array table if there is one.
547 auto* vtable = klass->GetVTable();
548 if (vtable != nullptr) {
549 AddMethodPointerArray(vtable);
550 }
551 auto* iftable = klass->GetIfTable();
552 if (iftable != nullptr) {
553 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
554 if (iftable->GetMethodArrayCount(i) > 0) {
555 AddMethodPointerArray(iftable->GetMethodArray(i));
556 }
557 }
558 }
559
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800560 if (klass->GetStatus() == Class::kStatusInitialized) {
561 bin = kBinClassInitialized;
562
563 // If the class's static fields are all final, put it into a separate bin
564 // since it's very likely it will stay clean.
565 uint32_t num_static_fields = klass->NumStaticFields();
566 if (num_static_fields == 0) {
567 bin = kBinClassInitializedFinalStatics;
568 } else {
569 // Maybe all the statics are final?
570 bool all_final = true;
571 for (uint32_t i = 0; i < num_static_fields; ++i) {
572 ArtField* field = klass->GetStaticField(i);
573 if (!field->IsFinal()) {
574 all_final = false;
575 break;
576 }
577 }
578
579 if (all_final) {
580 bin = kBinClassInitializedFinalStatics;
581 }
582 }
583 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800584 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
585 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700586 } else if (object->GetClass<kVerifyNone>() ==
587 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
588 // Instance of java lang object, probably a lock object. This means it will be dirty when we
589 // synchronize on it.
590 bin = kBinMiscDirty;
591 } else if (object->IsDexCache()) {
592 // Dex file field becomes dirty when the image is loaded.
593 bin = kBinMiscDirty;
594 }
595 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800596 }
597
Mathieu Chartier496577f2016-09-20 15:33:31 -0700598 // Assign the oat index too.
599 DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
600 oat_index_map_.emplace(object, oat_index);
601
Vladimir Marko944da602016-02-19 12:27:55 +0000602 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800603
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800604 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800605 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
606 // Move the current bin size up to accommodate the object we just assigned a bin slot.
607 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800608
609 BinSlot new_bin_slot(bin, current_offset);
610 SetImageBinSlot(object, new_bin_slot);
611
Jeff Haodcdc85b2015-12-04 14:06:18 -0800612 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800613
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800614 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800615 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800616}
617
Mathieu Chartiere401d142015-04-22 13:56:20 -0700618bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
619 if (m->IsNative()) {
620 return true;
621 }
622 mirror::Class* declaring_class = m->GetDeclaringClass();
623 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
624 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
625}
626
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800627bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
628 DCHECK(object != nullptr);
629
630 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
631 // If it's in some other state, then we haven't yet assigned an image bin slot.
632 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
633 return false;
634 } else if (kIsDebugBuild) {
635 LockWord lock_word = object->GetLockWord(false);
636 size_t offset = lock_word.ForwardingAddress();
637 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000638 size_t oat_index = GetOatIndex(object);
639 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800640 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800641 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800642 }
643 return true;
644}
645
646ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
647 DCHECK(object != nullptr);
648 DCHECK(IsImageBinSlotAssigned(object));
649
650 LockWord lock_word = object->GetLockWord(false);
651 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
652 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
653
654 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000655 size_t oat_index = GetOatIndex(object);
656 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800657 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800658
659 return bin_slot;
660}
661
Brian Carlstrom7940e442013-07-12 13:46:57 -0700662bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000663 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800664 ImageSection unused_sections[ImageHeader::kSectionCount];
665 const size_t length = RoundUp(
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700666 image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800667
Jeff Haodcdc85b2015-12-04 14:06:18 -0800668 std::string error_msg;
669 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
670 nullptr,
671 length,
672 PROT_READ | PROT_WRITE,
673 false,
674 false,
675 &error_msg));
676 if (UNLIKELY(image_info.image_.get() == nullptr)) {
677 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
678 return false;
679 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700680
Jeff Haodcdc85b2015-12-04 14:06:18 -0800681 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
682 CHECK_LE(image_info.image_end_, length);
683 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
684 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
685 if (image_info.image_bitmap_.get() == nullptr) {
686 LOG(ERROR) << "Failed to allocate memory for image bitmap";
687 return false;
688 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700689 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700690 return true;
691}
692
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700693class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
694 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700695 bool operator()(Class* c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700696 StackHandleScope<1> hs(Thread::Current());
697 mirror::Class::ComputeName(hs.NewHandle(c));
698 return true;
699 }
700};
701
Brian Carlstrom7940e442013-07-12 13:46:57 -0700702void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700703 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700704 ComputeLazyFieldsForClassesVisitor visitor;
705 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700706}
707
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700708static bool IsBootClassLoaderClass(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800709 return klass->GetClassLoader() == nullptr;
710}
711
712bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
713 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
714}
715
Mathieu Chartier901e0702016-02-19 13:42:48 -0800716bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800717 bool early_exit = false;
718 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800719 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800720}
721
Mathieu Chartier901e0702016-02-19 13:42:48 -0800722bool ImageWriter::PruneAppImageClassInternal(
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800723 mirror::Class* klass,
724 bool* early_exit,
725 std::unordered_set<mirror::Class*>* visited) {
726 DCHECK(early_exit != nullptr);
727 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800728 DCHECK(compile_app_image_);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800729 if (klass == nullptr || IsInBootImage(klass)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700730 return false;
731 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800732 auto found = prune_class_memo_.find(klass);
733 if (found != prune_class_memo_.end()) {
734 // Already computed, return the found value.
735 return found->second;
736 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800737 // Circular dependencies, return false but do not store the result in the memoization table.
738 if (visited->find(klass) != visited->end()) {
739 *early_exit = true;
740 return false;
741 }
742 visited->emplace(klass);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800743 bool result = IsBootClassLoaderClass(klass);
744 std::string temp;
745 // Prune if not an image class, this handles any broken sets of image classes such as having a
746 // class in the set but not it's superclass.
747 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800748 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800749 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
750 // app image.
751 if (klass->GetStatus() == mirror::Class::kStatusError) {
752 result = true;
753 } else {
754 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
755 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800756 if (!result) {
757 // Check interfaces since these wont be visited through VisitReferences.)
758 mirror::IfTable* if_table = klass->GetIfTable();
759 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800760 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
761 &my_early_exit,
762 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800763 }
764 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800765 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800766 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
767 &my_early_exit,
768 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800769 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800770 // Check static fields and their classes.
771 size_t num_static_fields = klass->NumReferenceStaticFields();
772 if (num_static_fields != 0 && klass->IsResolved()) {
773 // Presumably GC can happen when we are cross compiling, it should not cause performance
774 // problems to do pointer size logic.
775 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
776 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
777 for (size_t i = 0u; i < num_static_fields; ++i) {
778 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
779 if (ref != nullptr) {
780 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800781 result = result || PruneAppImageClassInternal(ref->AsClass(),
782 &my_early_exit,
783 visited);
784 } else {
785 result = result || PruneAppImageClassInternal(ref->GetClass(),
786 &my_early_exit,
787 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800788 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800789 }
790 field_offset = MemberOffset(field_offset.Uint32Value() +
791 sizeof(mirror::HeapReference<mirror::Object>));
792 }
793 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800794 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
795 &my_early_exit,
796 visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800797 // Erase the element we stored earlier since we are exiting the function.
798 auto it = visited->find(klass);
799 DCHECK(it != visited->end());
800 visited->erase(it);
801 // Only store result if it is true or none of the calls early exited due to circular
802 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
803 // a child call and we can remember the result.
804 if (result == true || !my_early_exit || visited->empty()) {
805 prune_class_memo_[klass] = result;
806 }
807 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800808 return result;
809}
810
811bool ImageWriter::KeepClass(Class* klass) {
812 if (klass == nullptr) {
813 return false;
814 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800815 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
816 // Already in boot image, return true.
817 return true;
818 }
819 std::string temp;
820 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
821 return false;
822 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800823 if (compile_app_image_) {
824 // For app images, we need to prune boot loader classes that are not in the boot image since
825 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800826 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800827 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800828 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800829 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700830}
831
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700832class NonImageClassesVisitor : public ClassVisitor {
833 public:
834 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
835
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700836 bool operator()(Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800837 if (!image_writer_->KeepClass(klass)) {
838 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700839 }
840 return true;
841 }
842
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800843 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700844 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700845};
846
847void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700848 Runtime* runtime = Runtime::Current();
849 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700850 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700851
Mathieu Chartier696632e2016-06-03 17:47:32 -0700852 // Clear class table strong roots so that dex caches can get pruned. We require pruning the class
853 // path dex caches.
854 class_linker->ClearClassTableStrongRoots();
855
Brian Carlstrom7940e442013-07-12 13:46:57 -0700856 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700857 NonImageClassesVisitor visitor(this);
858 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700859
860 // Remove the undesired classes from the class roots.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800861 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800862 for (mirror::Class* klass : visitor.classes_to_prune_) {
863 std::string temp;
864 const char* name = klass->GetDescriptor(&temp);
865 VLOG(compiler) << "Pruning class " << name;
866 if (!compile_app_image_) {
867 DCHECK(IsBootClassLoaderClass(klass));
868 }
869 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800870 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700871 }
872
873 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100874 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700875
Mathieu Chartier268764d2016-09-13 12:09:38 -0700876 ScopedAssertNoThreadSuspension sa(__FUNCTION__);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700877 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
878 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800879 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800880 if (self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700881 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700882 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700883 ObjPtr<mirror::DexCache> dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700884 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
885 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800886 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700887 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700888 }
889 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100890 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
891 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
892 ArtMethod* method =
893 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800894 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
895 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800896 // 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 -0800897 // declaring class which is an image class. Set it to the resolution method to be safe and
898 // prevent dangling pointers.
Alex Light36121492016-02-22 13:43:29 -0800899 if (method->IsCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800900 mirror::DexCache::SetElementPtrSize(resolved_methods,
901 i,
902 resolution_method,
903 target_ptr_size_);
904 } else {
905 // Check that the class is still in the classes table.
906 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
907 << PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700908 }
909 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800910 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700911 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800912 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700913 if (field != nullptr && !KeepClass(field->GetDeclaringClass().Ptr())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700914 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700915 }
916 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700917 // Clean the dex field. It might have been populated during the initialization phase, but
918 // contains data only valid during a real run.
919 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700920 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700921
922 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
923 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800924
925 // Clear to save RAM.
926 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700927}
928
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800929void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700930 if (compiler_driver_.GetImageClasses() != nullptr) {
931 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700932 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700933 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700934}
935
936void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
937 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800938 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700939 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800940 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700941 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700942 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800943 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
944 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700945 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700946 }
947}
948
949void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700950 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700951 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700952 for (const std::string& image_class : *image_classes) {
953 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700954 }
955}
956
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800957mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
958 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +0000959 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800960 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
961 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
962 << string->ToModifiedUtf8();
963 if (found != nullptr) {
964 return found;
965 }
966 }
967 if (compile_app_image_) {
968 Runtime* const runtime = Runtime::Current();
969 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
970 // If we found it in the runtime intern table it could either be in the boot image or interned
971 // during app image compilation. If it was in the boot image return that, otherwise return null
972 // since it belongs to another image space.
973 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
974 return found;
975 }
976 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
977 << string->ToModifiedUtf8();
978 }
979 return nullptr;
980}
981
Brian Carlstrom7940e442013-07-12 13:46:57 -0700982
Vladimir Marko944da602016-02-19 12:27:55 +0000983ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700984 Runtime* runtime = Runtime::Current();
985 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700986 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700987 StackHandleScope<3> hs(self);
988 Handle<Class> object_array_class(hs.NewHandle(
989 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700990
Jeff Haodcdc85b2015-12-04 14:06:18 -0800991 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +0000992 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800993 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +0000994 size_t image_oat_index = pair.second;
995 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800996 image_dex_files.insert(image_dex_file);
997 }
998 }
999
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001000 // build an Object[] of all the DexCaches used in the source_space_.
1001 // Since we can't hold the dex lock when allocating the dex_caches
1002 // ObjectArray, we lock the dex lock twice, first to get the number
1003 // of dex caches first and then lock it again to copy the dex
1004 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001005 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001006 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001007 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001008 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001009 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001010 ObjPtr<mirror::DexCache> dex_cache =
1011 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001012 if (dex_cache == nullptr) {
1013 continue;
1014 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001015 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001016 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001017 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1018 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001019 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001020 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001021 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001022 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001023 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1024 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001025 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001026 size_t non_image_dex_caches = 0;
1027 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001028 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001029 ObjPtr<mirror::DexCache> dex_cache =
1030 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001031 if (dex_cache == nullptr) {
1032 continue;
1033 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001034 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001035 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001036 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1037 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001038 }
1039 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1040 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001041 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001042 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001043 ObjPtr<mirror::DexCache> dex_cache =
1044 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001045 if (dex_cache == nullptr) {
1046 continue;
1047 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001048 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001049 if (!IsInBootImage(dex_cache.Ptr()) &&
1050 image_dex_files.find(dex_file) != image_dex_files.end()) {
1051 dex_caches->Set<false>(i, dex_cache.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001052 ++i;
1053 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001054 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001055 }
1056
1057 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001058 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001059 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001060 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001061 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001062 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001063 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001064 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001065 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001066}
1067
Mathieu Chartier496577f2016-09-20 15:33:31 -07001068mirror::Object* ImageWriter::TryAssignBinSlot(WorkStack& work_stack,
1069 mirror::Object* obj,
1070 size_t oat_index) {
1071 if (obj == nullptr || IsInBootImage(obj)) {
1072 // Object is null or already in the image, there is no work to do.
1073 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001074 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001075 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001076 // We want to intern all strings but also assign offsets for the source string. Since the
1077 // pruning phase has already happened, if we intern a string to one in the image we still
1078 // end up copying an unreachable string.
1079 if (obj->IsString()) {
1080 // Need to check if the string is already interned in another image info so that we don't have
1081 // the intern tables of two different images contain the same string.
1082 mirror::String* interned = FindInternedString(obj->AsString());
1083 if (interned == nullptr) {
1084 // Not in another image space, insert to our table.
1085 interned = GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString());
1086 DCHECK_EQ(interned, obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001087 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001088 } else if (obj->IsDexCache()) {
1089 oat_index = GetOatIndexForDexCache(obj->AsDexCache());
1090 } else if (obj->IsClass()) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001091 // Visit and assign offsets for fields and field arrays.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001092 mirror::Class* as_klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001093 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001094 DCHECK_NE(as_klass->GetStatus(), mirror::Class::kStatusError);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001095 if (compile_app_image_) {
1096 // Extra sanity, no boot loader classes should be left!
1097 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1098 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001099 LengthPrefixedArray<ArtField>* fields[] = {
1100 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1101 };
Mathieu Chartier496577f2016-09-20 15:33:31 -07001102 // Overwrite the oat index value since the class' dex cache is more accurate of where it
1103 // belongs.
1104 oat_index = GetOatIndexForDexCache(dex_cache);
Vladimir Marko944da602016-02-19 12:27:55 +00001105 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001106 {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001107 // Note: This table is only accessed from the image writer, avoid locking to prevent lock
1108 // order violations from root visiting.
1109 image_info.class_table_->InsertWithoutLocks(as_klass);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001110 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001111 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1112 // Total array length including header.
1113 if (cur_fields != nullptr) {
1114 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1115 // Forward the entire array at once.
1116 auto it = native_object_relocations_.find(cur_fields);
1117 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1118 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001119 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001120 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001121 native_object_relocations_.emplace(
1122 cur_fields,
1123 NativeObjectRelocation {
1124 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1125 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001126 offset += header_size;
1127 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001128 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001129 // Need to forward arrays separate of fields.
1130 ArtField* field = &cur_fields->At(i);
1131 auto it2 = native_object_relocations_.find(field);
1132 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1133 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001134 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001135 native_object_relocations_.emplace(
1136 field,
1137 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001138 offset += sizeof(ArtField);
1139 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001140 }
1141 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001142 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001143 size_t num_methods = as_klass->NumMethods();
1144 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001145 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001146 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1147 if (WillMethodBeDirty(&m)) {
1148 any_dirty = true;
1149 break;
1150 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001151 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001152 NativeObjectRelocationType type = any_dirty
1153 ? kNativeObjectRelocationTypeArtMethodDirty
1154 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001155 Bin bin_type = BinTypeForNativeRelocationType(type);
1156 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001157 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1158 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001159 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1160 method_size,
1161 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001162 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001163 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001164 CHECK(it == native_object_relocations_.end())
1165 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001166 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001167 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001168 native_object_relocations_.emplace(array,
1169 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001170 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001171 offset,
1172 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1173 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001174 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001175 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001176 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001177 }
Alex Lighte64300b2015-12-15 15:02:47 -08001178 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001179 }
1180 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1181 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001182 if (as_klass->ShouldHaveImt()) {
1183 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1184 for (size_t i = 0; i < ImTable::kSize; ++i) {
1185 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001186 DCHECK(imt_method != nullptr);
1187 if (imt_method->IsRuntimeMethod() &&
1188 !IsInBootImage(imt_method) &&
1189 !NativeRelocationAssigned(imt_method)) {
1190 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001191 }
1192 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001193 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001194
1195 if (as_klass->ShouldHaveImt()) {
1196 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1197 TryAssignImTableOffset(imt, oat_index);
1198 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001199 } else if (obj->IsClassLoader()) {
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001200 // Register the class loader if it has a class table.
1201 // The fake boot class loader should not get registered and we should end up with only one
1202 // class loader.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001203 mirror::ClassLoader* class_loader = obj->AsClassLoader();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001204 if (class_loader->GetClassTable() != nullptr) {
1205 class_loaders_.insert(class_loader);
1206 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001207 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001208 AssignImageBinSlot(obj, oat_index);
1209 work_stack.emplace(obj, oat_index);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001210 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001211 if (obj->IsString()) {
1212 // Always return the interned string if there exists one.
1213 mirror::String* interned = FindInternedString(obj->AsString());
1214 if (interned != nullptr) {
1215 return interned;
1216 }
1217 }
1218 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001219}
1220
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001221bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1222 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1223}
1224
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001225void ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
1226 // No offset, or already assigned.
1227 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
1228 return;
1229 }
1230 // If the method is a conflict method we also want to assign the conflict table offset.
1231 ImageInfo& image_info = GetImageInfo(oat_index);
1232 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1233 native_object_relocations_.emplace(
1234 imt,
1235 NativeObjectRelocation {
1236 oat_index,
1237 image_info.bin_slot_sizes_[kBinImTable],
1238 kNativeObjectRelocationTypeIMTable});
1239 image_info.bin_slot_sizes_[kBinImTable] += size;
1240}
1241
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001242void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1243 // No offset, or already assigned.
1244 if (table == nullptr || NativeRelocationAssigned(table)) {
1245 return;
1246 }
1247 CHECK(!IsInBootImage(table));
1248 // If the method is a conflict method we also want to assign the conflict table offset.
1249 ImageInfo& image_info = GetImageInfo(oat_index);
1250 const size_t size = table->ComputeSize(target_ptr_size_);
1251 native_object_relocations_.emplace(
1252 table,
1253 NativeObjectRelocation {
1254 oat_index,
1255 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1256 kNativeObjectRelocationTypeIMTConflictTable});
1257 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1258}
1259
Jeff Haodcdc85b2015-12-04 14:06:18 -08001260void ImageWriter::AssignMethodOffset(ArtMethod* method,
1261 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001262 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001263 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001264 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001265 << PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001266 if (method->IsRuntimeMethod()) {
1267 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1268 }
Vladimir Marko944da602016-02-19 12:27:55 +00001269 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001270 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001271 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001272 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001273}
1274
Mathieu Chartier496577f2016-09-20 15:33:31 -07001275void ImageWriter::EnsureBinSlotAssignedCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001276 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1277 DCHECK(writer != nullptr);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001278 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) {
1279 CHECK(writer->IsImageBinSlotAssigned(obj)) << PrettyTypeOf(obj) << " " << obj;
1280 }
1281}
1282
1283void ImageWriter::DeflateMonitorCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED) {
1284 Monitor::Deflate(Thread::Current(), obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001285}
1286
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001287void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1288 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1289 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001290 if (!writer->IsInBootImage(obj)) {
1291 writer->UnbinObjectsIntoOffset(obj);
1292 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001293}
1294
1295void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001296 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001297 CHECK(obj != nullptr);
1298
1299 // We know the bin slot, and the total bin sizes for all objects by now,
1300 // so calculate the object's final image offset.
1301
1302 DCHECK(IsImageBinSlotAssigned(obj));
1303 BinSlot bin_slot = GetImageBinSlot(obj);
1304 // Change the lockword from a bin slot into an offset
1305 AssignImageOffset(obj, bin_slot);
1306}
1307
Mathieu Chartier496577f2016-09-20 15:33:31 -07001308class ImageWriter::VisitReferencesVisitor {
1309 public:
1310 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index)
1311 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {}
1312
1313 // Fix up separately since we also need to fix up method entrypoints.
1314 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1315 REQUIRES_SHARED(Locks::mutator_lock_) {
1316 if (!root->IsNull()) {
1317 VisitRoot(root);
1318 }
1319 }
1320
1321 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1322 REQUIRES_SHARED(Locks::mutator_lock_) {
1323 root->Assign(VisitReference(root->AsMirrorPtr()));
1324 }
1325
Mathieu Chartier31e88222016-10-14 18:43:19 -07001326 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
Mathieu Chartier496577f2016-09-20 15:33:31 -07001327 MemberOffset offset,
1328 bool is_static ATTRIBUTE_UNUSED) const
1329 REQUIRES_SHARED(Locks::mutator_lock_) {
1330 mirror::Object* ref =
1331 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1332 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1333 }
1334
Mathieu Chartier31e88222016-10-14 18:43:19 -07001335 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1336 ObjPtr<mirror::Reference> ref) const
Mathieu Chartier496577f2016-09-20 15:33:31 -07001337 REQUIRES_SHARED(Locks::mutator_lock_) {
1338 ref->SetReferent</*kTransactionActive*/false>(
1339 VisitReference(ref->GetReferent<kWithoutReadBarrier>()));
1340 }
1341
1342 private:
1343 mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1344 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_);
1345 }
1346
1347 ImageWriter* const image_writer_;
1348 WorkStack* const work_stack_;
1349 const size_t oat_index_;
1350};
1351
1352class ImageWriter::GetRootsVisitor : public RootVisitor {
1353 public:
1354 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {}
1355
1356 void VisitRoots(mirror::Object*** roots,
1357 size_t count,
1358 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1359 REQUIRES_SHARED(Locks::mutator_lock_) {
1360 for (size_t i = 0; i < count; ++i) {
1361 roots_->push_back(*roots[i]);
1362 }
1363 }
1364
1365 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1366 size_t count,
1367 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1368 REQUIRES_SHARED(Locks::mutator_lock_) {
1369 for (size_t i = 0; i < count; ++i) {
1370 roots_->push_back(roots[i]->AsMirrorPtr());
1371 }
1372 }
1373
1374 private:
1375 std::vector<mirror::Object*>* const roots_;
1376};
1377
1378void ImageWriter::ProcessWorkStack(WorkStack* work_stack) {
1379 while (!work_stack->empty()) {
1380 std::pair<mirror::Object*, size_t> pair(work_stack->top());
1381 work_stack->pop();
1382 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second);
1383 // Walk references and assign bin slots for them.
1384 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1385 visitor,
1386 visitor);
1387 }
1388}
1389
Vladimir Markof4da6752014-08-01 19:04:18 +01001390void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001391 Thread* const self = Thread::Current();
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07001392 VariableSizedHandleScope handles(self);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001393 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001394 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1395 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001396 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001397
Mathieu Chartier496577f2016-09-20 15:33:31 -07001398 Runtime* const runtime = Runtime::Current();
1399 gc::Heap* const heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001400
Mathieu Chartier31e89252013-08-28 11:29:12 -07001401 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001402 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001403 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001404
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001405 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001406 // Write the image runtime methods.
1407 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1408 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1409 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001410 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
1411 runtime->GetCalleeSaveMethod(Runtime::kSaveAllCalleeSaves);
1412 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
1413 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsOnly);
1414 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
1415 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001416 image_methods_[ImageHeader::kSaveEverythingMethod] =
1417 runtime->GetCalleeSaveMethod(Runtime::kSaveEverything);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001418 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001419 for (auto* m : image_methods_) {
1420 CHECK(m != nullptr);
1421 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001422 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1423 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001424 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001425 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001426 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001427
Mathieu Chartier496577f2016-09-20 15:33:31 -07001428 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
1429 // this lock while holding other locks may cause lock order violations.
1430 heap->VisitObjects(DeflateMonitorCallback, this);
1431
1432 // Work list of <object, oat_index> for objects. Everything on the stack must already be
1433 // assigned a bin slot.
1434 WorkStack work_stack;
1435
1436 // Special case interned strings to put them in the image they are likely to be resolved from.
1437 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
1438 auto it = dex_file_oat_index_map_.find(dex_file);
1439 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1440 const size_t oat_index = it->second;
1441 InternTable* const intern_table = runtime->GetInternTable();
1442 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
1443 uint32_t utf16_length;
1444 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(i, &utf16_length);
1445 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data);
1446 TryAssignBinSlot(work_stack, string, oat_index);
1447 }
1448 }
1449
1450 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor
1451 // visits roots while holding various locks.
1452 {
1453 std::vector<mirror::Object*> roots;
1454 GetRootsVisitor root_visitor(&roots);
1455 runtime->VisitRoots(&root_visitor);
1456 for (mirror::Object* obj : roots) {
1457 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex());
1458 }
1459 }
1460 ProcessWorkStack(&work_stack);
1461
1462 // For app images, there may be objects that are only held live by the by the boot image. One
1463 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback
1464 // does not fail any checks. TODO: We should probably avoid copying these objects.
1465 if (compile_app_image_) {
1466 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) {
1467 DCHECK(space->IsImageSpace());
1468 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1469 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1470 reinterpret_cast<uintptr_t>(space->Limit()),
1471 [this, &work_stack](mirror::Object* obj)
1472 REQUIRES_SHARED(Locks::mutator_lock_) {
1473 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex());
1474 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot).
1475 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1476 visitor,
1477 visitor);
1478 });
1479 }
1480 // Process the work stack in case anything was added by TryAssignBinSlot.
1481 ProcessWorkStack(&work_stack);
1482 }
1483
1484 // Verify that all objects have assigned image bin slots.
1485 heap->VisitObjects(EnsureBinSlotAssignedCallback, this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001486
Vladimir Marko05792b92015-08-03 11:56:49 +01001487 // Calculate size of the dex cache arrays slot and prepare offsets.
1488 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001489
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001490 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001491 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001492 // Calculate how big the intern table will be after being serialized.
1493 InternTable* const intern_table = image_info.intern_table_.get();
1494 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1495 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001496 // Calculate the size of the class table.
1497 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1498 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001499 }
1500
Vladimir Markocf36d492015-08-12 19:27:26 +01001501 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001502 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001503 size_t bin_offset = image_objects_offset_begin_;
1504 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001505 switch (i) {
1506 case kBinArtMethodClean:
1507 case kBinArtMethodDirty: {
1508 bin_offset = RoundUp(bin_offset, method_alignment);
1509 break;
1510 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001511 case kBinDexCacheArray:
1512 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment());
1513 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001514 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001515 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001516 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001517 break;
1518 }
1519 default: {
1520 // Normal alignment.
1521 }
1522 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001523 image_info.bin_slot_offsets_[i] = bin_offset;
1524 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001525 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001526 // NOTE: There may be additional padding between the bin slots and the intern table.
1527 DCHECK_EQ(image_info.image_end_,
1528 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001529 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001530
Jeff Haodcdc85b2015-12-04 14:06:18 -08001531 // Calculate image offsets.
1532 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001533 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001534 image_info.image_begin_ = global_image_begin_ + image_offset;
1535 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001536 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001537 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001538 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001539 image_offset += image_info.image_size_;
1540 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001541
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001542 // Transform each object's bin slot into an offset which will be used to do the final copy.
1543 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001544
Jeff Haodcdc85b2015-12-04 14:06:18 -08001545 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001546
Jeff Haodcdc85b2015-12-04 14:06:18 -08001547 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001548 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001549 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1550 i++;
1551 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001552
Mathieu Chartiere401d142015-04-22 13:56:20 -07001553 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001554 for (auto& pair : native_object_relocations_) {
1555 NativeObjectRelocation& relocation = pair.second;
1556 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001557 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001558 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001559 }
1560
Jeff Haodcdc85b2015-12-04 14:06:18 -08001561 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001562}
1563
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001564size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001565 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001566
1567 // Do not round up any sections here that are represented by the bins since it will break
1568 // offsets.
1569
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001570 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001571 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001572 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001573
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001574 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001575 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1576 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001577 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001578
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001579 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001580 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1581 *methods_section = ImageSection(
1582 bin_slot_offsets_[kBinArtMethodClean],
1583 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1584
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001585 // IMT section.
1586 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1587 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1588
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001589 // Conflict tables section.
1590 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1591 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1592 bin_slot_sizes_[kBinIMTConflictTable]);
1593
1594 // Runtime methods section.
1595 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1596 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1597 bin_slot_sizes_[kBinRuntimeMethod]);
1598
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001599 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001600 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1601 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1602 bin_slot_sizes_[kBinDexCacheArray]);
1603
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001604 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001605 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001606 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001607 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001608 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1609 cur_pos = interned_strings_section->End();
1610 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1611 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1612 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001613 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001614 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001615 cur_pos = class_table_section->End();
1616 // Image end goes right before the start of the image bitmap.
1617 return cur_pos;
1618}
1619
Vladimir Marko944da602016-02-19 12:27:55 +00001620void ImageWriter::CreateHeader(size_t oat_index) {
1621 ImageInfo& image_info = GetImageInfo(oat_index);
1622 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1623 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1624 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001625
1626 // Create the image sections.
1627 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001628 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001629
Mathieu Chartiere401d142015-04-22 13:56:20 -07001630 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001631 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001632 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001633 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001634 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001635 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001636 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001637 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001638 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1639 ++idx;
1640 }
1641 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001642 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1643 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1644 << " Image offset=" << image_info.image_offset_ << std::dec;
1645 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1646 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1647 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1648 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001649 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001650 // Store boot image info for app image so that we can relocate.
1651 uint32_t boot_image_begin = 0;
1652 uint32_t boot_image_end = 0;
1653 uint32_t boot_oat_begin = 0;
1654 uint32_t boot_oat_end = 0;
1655 gc::Heap* const heap = Runtime::Current()->GetHeap();
1656 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001657
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001658 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1659 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001660 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1661 image_end,
1662 sections,
1663 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001664 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001665 PointerToLowMemUInt32(oat_file_begin),
1666 PointerToLowMemUInt32(image_info.oat_data_begin_),
1667 PointerToLowMemUInt32(oat_data_end),
1668 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001669 boot_image_begin,
1670 boot_image_end - boot_image_begin,
1671 boot_oat_begin,
1672 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001673 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001674 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001675 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001676 image_storage_mode_,
1677 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001678}
1679
1680ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001681 auto it = native_object_relocations_.find(method);
1682 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001683 size_t oat_index = GetOatIndex(method->GetDexCache());
1684 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001685 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1686 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001687}
1688
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001689class FixupRootVisitor : public RootVisitor {
1690 public:
1691 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1692 }
1693
1694 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001695 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001696 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001697 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001698 }
1699 }
1700
1701 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1702 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001703 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001704 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001705 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001706 }
1707 }
1708
1709 private:
1710 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001711};
1712
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001713void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
1714 for (size_t i = 0; i < ImTable::kSize; ++i) {
1715 ArtMethod* method = orig->Get(i, target_ptr_size_);
1716 copy->Set(i, NativeLocationInImage(method), target_ptr_size_);
1717 }
1718}
1719
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001720void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
1721 const size_t count = orig->NumEntries(target_ptr_size_);
1722 for (size_t i = 0; i < count; ++i) {
1723 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
1724 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
1725 copy->SetInterfaceMethod(i, target_ptr_size_, NativeLocationInImage(interface_method));
1726 copy->SetImplementationMethod(i,
1727 target_ptr_size_,
1728 NativeLocationInImage(implementation_method));
1729 }
1730}
1731
Vladimir Marko944da602016-02-19 12:27:55 +00001732void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001733 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001734 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001735 for (auto& pair : native_object_relocations_) {
1736 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001737 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001738 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001739 continue;
1740 }
1741 auto* dest = image_info.image_->Begin() + relocation.offset;
1742 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001743 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001744 switch (relocation.type) {
1745 case kNativeObjectRelocationTypeArtField: {
1746 memcpy(dest, pair.first, sizeof(ArtField));
1747 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001748 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass().Ptr()));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001749 break;
1750 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001751 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001752 case kNativeObjectRelocationTypeArtMethodClean:
1753 case kNativeObjectRelocationTypeArtMethodDirty: {
1754 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001755 reinterpret_cast<ArtMethod*>(dest),
1756 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001757 break;
1758 }
1759 // For arrays, copy just the header since the elements will get copied by their corresponding
1760 // relocations.
1761 case kNativeObjectRelocationTypeArtFieldArray: {
1762 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1763 break;
1764 }
1765 case kNativeObjectRelocationTypeArtMethodArrayClean:
1766 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00001767 size_t size = ArtMethod::Size(target_ptr_size_);
1768 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1769 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1770 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1771 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001772 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00001773 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001774 case kNativeObjectRelocationTypeDexCacheArray:
1775 // Nothing to copy here, everything is done in FixupDexCache().
1776 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001777 case kNativeObjectRelocationTypeIMTable: {
1778 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
1779 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
1780 CopyAndFixupImTable(orig_imt, dest_imt);
1781 break;
1782 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001783 case kNativeObjectRelocationTypeIMTConflictTable: {
1784 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
1785 CopyAndFixupImtConflictTable(
1786 orig_table,
1787 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
1788 break;
1789 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001790 }
1791 }
1792 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001793 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001794 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001795 ArtMethod* method = image_methods_[i];
1796 CHECK(method != nullptr);
1797 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001798 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001799 }
1800 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001801 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001802 FixupRootVisitor root_visitor(this);
1803
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001804 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001805 if (image_info.intern_table_bytes_ > 0) {
1806 const ImageSection& intern_table_section = image_header->GetImageSection(
1807 ImageHeader::kSectionInternedStrings);
1808 InternTable* const intern_table = image_info.intern_table_.get();
1809 uint8_t* const intern_table_memory_ptr =
1810 image_info.image_->Begin() + intern_table_section.Offset();
1811 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1812 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1813 // Fixup the pointers in the newly written intern table to contain image addresses.
1814 InternTable temp_intern_table;
1815 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1816 // the VisitRoots() will update the memory directly rather than the copies.
1817 // This also relies on visit roots not doing any verification which could fail after we update
1818 // the roots to be the image addresses.
1819 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1820 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1821 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1822 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001823 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1824 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001825 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001826 const ImageSection& class_table_section = image_header->GetImageSection(
1827 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001828 uint8_t* const class_table_memory_ptr =
1829 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001830 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001831
1832 ClassTable* table = image_info.class_table_.get();
1833 CHECK(table != nullptr);
1834 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1835 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1836 // Fixup the pointers in the newly written class table to contain image addresses. See
1837 // above comment for intern tables.
1838 ClassTable temp_class_table;
1839 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1840 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1841 table->NumZygoteClasses());
1842 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1843 RootInfo(kRootUnknown));
1844 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001845 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001846}
1847
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001848void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001849 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001850 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1851 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001852 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001853 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001854 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1855 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001856 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001857 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001858}
1859
Mathieu Chartier590fee92013-09-13 13:46:47 -07001860void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001861 DCHECK(obj != nullptr);
1862 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001863 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1864}
1865
Mathieu Chartiere401d142015-04-22 13:56:20 -07001866void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1867 mirror::Class* klass, Bin array_type) {
1868 CHECK(klass->IsArrayClass());
1869 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1870 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001871 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001872 dst->SetClass(GetImageAddress(arr->GetClass()));
1873 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001874 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001875 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1876 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001877 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001878 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001879 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001880 auto* method = reinterpret_cast<ArtMethod*>(elem);
1881 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1882 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1883 << PrettyClass(method->GetDeclaringClass());
1884 } else {
1885 CHECK_EQ(array_type, kBinArtField);
1886 auto* field = reinterpret_cast<ArtField*>(elem);
1887 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1888 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1889 << PrettyClass(field->GetDeclaringClass());
1890 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001891 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001892 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001893 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001894 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001895 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001896 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001897 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001898 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001899}
1900
1901void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001902 if (IsInBootImage(obj)) {
1903 return;
1904 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001905 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001906 size_t oat_index = GetOatIndex(obj);
1907 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001908 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1909 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001910 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001911
Jeff Haodcdc85b2015-12-04 14:06:18 -08001912 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001913
1914 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001915 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001916 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001917
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001918 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1919 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001920 const auto it = saved_hashcode_map_.find(obj);
1921 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1922 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001923 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
1924 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
1925 // safe since we mark all of the objects that may reference non immune objects as gray.
1926 CHECK(dst->AtomicSetMarkBit(0, 1));
1927 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001928 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001929}
1930
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001931// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001932class FixupVisitor {
1933 public:
1934 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1935 }
1936
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001937 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1938 // with other logic.
1939 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1940 const {}
1941 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1942
1943
Mathieu Chartier31e88222016-10-14 18:43:19 -07001944 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001945 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07001946 ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001947 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1948 // image.
1949 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001950 offset,
Mathieu Chartier31e88222016-10-14 18:43:19 -07001951 image_writer_->GetImageAddress(ref.Ptr()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001952 }
1953
1954 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001955 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1956 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001957 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001958 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001959 mirror::Reference::ReferentOffset(),
1960 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001961 }
1962
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001963 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001964 ImageWriter* const image_writer_;
1965 mirror::Object* const copy_;
1966};
1967
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001968class FixupClassVisitor FINAL : public FixupVisitor {
1969 public:
1970 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1971 }
1972
Mathieu Chartier31e88222016-10-14 18:43:19 -07001973 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001974 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001975 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001976 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001977 }
1978
Mathieu Chartier31e88222016-10-14 18:43:19 -07001979 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1980 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001981 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001982 LOG(FATAL) << "Reference not expected here.";
1983 }
1984};
1985
Vladimir Marko05792b92015-08-03 11:56:49 +01001986uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1987 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001988 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001989 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001990 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1991 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001992 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001993 return relocation.offset;
1994}
1995
1996template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001997std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001998 std::ostringstream oss;
1999 oss << ptr;
2000 return oss.str();
2001}
2002
2003template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002004std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002005 return PrettyMethod(method);
2006}
2007
2008template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002009T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002010 if (obj == nullptr || IsInBootImage(obj)) {
2011 return obj;
2012 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002013 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002014 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
2015 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002016 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00002017 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002018 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002019 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002020}
2021
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002022template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08002023T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
2024 if (obj == nullptr || IsInBootImage(obj)) {
2025 return obj;
2026 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002027 size_t oat_index = GetOatIndexForDexCache(dex_cache);
2028 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002029 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
2030 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002031}
2032
2033class NativeLocationVisitor {
2034 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002035 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002036
2037 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002038 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002039 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002040 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002041
2042 private:
2043 ImageWriter* const image_writer_;
2044};
2045
2046void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002047 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002048 FixupClassVisitor visitor(this, copy);
Mathieu Chartier31e88222016-10-14 18:43:19 -07002049 ObjPtr<mirror::Object>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002050
2051 // Remove the clinitThreadId. This is required for image determinism.
2052 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002053}
2054
Ian Rogersef7d42f2014-01-06 12:55:46 -08002055void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002056 DCHECK(orig != nullptr);
2057 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002058 if (kUseBakerOrBrooksReadBarrier) {
2059 orig->AssertReadBarrierPointer();
2060 if (kUseBrooksReadBarrier) {
2061 // Note the address 'copy' isn't the same as the image address of 'orig'.
2062 copy->SetReadBarrierPointer(GetImageAddress(orig));
2063 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
2064 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002065 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002066 auto* klass = orig->GetClass();
2067 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002068 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07002069 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
2070 if (it != pointer_arrays_.end()) {
2071 // Should only need to fixup every pointer array exactly once.
2072 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
2073 pointer_arrays_.erase(it);
2074 return;
2075 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002076 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002077 if (orig->IsClass()) {
2078 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002079 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002080 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
2081 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01002082 auto* dest = down_cast<mirror::Executable*>(copy);
2083 auto* src = down_cast<mirror::Executable*>(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002084 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05002085 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01002086 } else if (!klass->IsArrayClass()) {
2087 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2088 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
2089 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002090 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002091 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002092 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2093 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002094 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002095 // Also set allocator to null to be safe. The allocator is created when we create the class
2096 // table. We also never expect to unload things in the image since they are held live as
2097 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002098 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002099 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002100 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002101 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002102 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002103 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002104}
2105
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002106
2107class ImageAddressVisitor {
2108 public:
2109 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
2110
2111 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002112 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002113 return image_writer_->GetImageAddress(ptr);
2114 }
2115
2116 private:
2117 ImageWriter* const image_writer_;
2118};
2119
2120
Vladimir Marko05792b92015-08-03 11:56:49 +01002121void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2122 mirror::DexCache* copy_dex_cache) {
2123 // Though the DexCache array fields are usually treated as native pointers, we set the full
2124 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2125 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2126 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002127 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002128 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002129 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002130 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002131 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002132 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
2133 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002134 }
2135 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
2136 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002137 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002138 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002139 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002140 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
2141 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002142 }
2143 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
2144 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002145 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002146 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002147 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002148 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002149 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
2150 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002151 // NativeLocationInImage also handles runtime methods since these have relocation info.
2152 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002153 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
2154 }
2155 }
2156 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
2157 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002158 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002159 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002160 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002161 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002162 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
2163 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002164 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002165 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
2166 }
2167 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002168
2169 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2170 // compiler pointers in here will make the output non-deterministic.
2171 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002172}
2173
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002174const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2175 DCHECK_LT(type, kOatAddressCount);
2176 // If we are compiling an app image, we need to use the stubs of the boot image.
2177 if (compile_app_image_) {
2178 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002179 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002180 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2181 DCHECK(!image_spaces.empty());
2182 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002183 CHECK(oat_file != nullptr);
2184 const OatHeader& header = oat_file->GetOatHeader();
2185 switch (type) {
2186 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2187 case kOatAddressQuickGenericJNITrampoline:
2188 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2189 case kOatAddressInterpreterToInterpreterBridge:
2190 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2191 case kOatAddressInterpreterToCompiledCodeBridge:
2192 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2193 case kOatAddressJNIDlsymLookup:
2194 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2195 case kOatAddressQuickIMTConflictTrampoline:
2196 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2197 case kOatAddressQuickResolutionTrampoline:
2198 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2199 case kOatAddressQuickToInterpreterBridge:
2200 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2201 default:
2202 UNREACHABLE();
2203 }
2204 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002205 const ImageInfo& primary_image_info = GetImageInfo(0);
2206 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002207}
2208
Jeff Haodcdc85b2015-12-04 14:06:18 -08002209const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2210 const ImageInfo& image_info,
2211 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002212 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
Nicolas Geoffray796d6302016-03-13 22:22:31 +00002213 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002214 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07002215 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002216 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002217
2218 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2219 // trampoline.
2220
2221 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002222 const void* quick_oat_entry_point =
2223 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2224 const uint8_t* quick_code;
2225
2226 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2227 DCHECK(method->IsCopied());
2228 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2229 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2230 } else {
2231 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2232 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2233 }
2234
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002235 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002236 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2237 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002238 // We have code for a non-static or initialized method, just use the code.
2239 } else if (quick_code == nullptr && method->IsNative() &&
2240 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2241 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002242 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002243 } else if (quick_code == nullptr && !method->IsNative()) {
2244 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002245 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002246 *quick_is_interpreted = true;
2247 } else {
2248 CHECK(!method->GetDeclaringClass()->IsInitialized());
2249 // We have code for a static method, but need to go through the resolution stub for class
2250 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002251 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2252 }
2253 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002254 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002255 }
2256 return quick_code;
2257}
2258
Jeff Haodcdc85b2015-12-04 14:06:18 -08002259void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2260 ArtMethod* copy,
2261 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002262 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002263
2264 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002265 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002266 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002267 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002268 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002269
Ian Rogers848871b2013-08-05 10:56:33 -07002270 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2271 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002272
Ian Rogers848871b2013-08-05 10:56:33 -07002273 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002274 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002275 if (orig->IsRuntimeMethod()) {
2276 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2277 if (orig_table != nullptr) {
2278 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2279 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2280 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2281 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2282 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2283 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2284 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2285 } else {
2286 bool found_one = false;
2287 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2288 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2289 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2290 found_one = true;
2291 break;
2292 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002293 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002294 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2295 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002296 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002297 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002298 // We assume all methods have code. If they don't currently then we set them to the use the
2299 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2300 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002301 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002302 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002303 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002304 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002305 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002306 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002307 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002308
Sebastien Hertze1d07812014-05-21 15:44:09 +02002309 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002310 if (orig->IsNative()) {
2311 // The native method's pointer is set to a stub to lookup via dlsym.
2312 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002313 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002314 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002315 }
2316 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002317 }
2318}
2319
Jeff Haodcdc85b2015-12-04 14:06:18 -08002320size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002321 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002322 return std::accumulate(&image_info.bin_slot_sizes_[0],
2323 &image_info.bin_slot_sizes_[up_to],
2324 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002325}
2326
2327ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2328 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002329 static_assert(kBinBits == 3, "wrong number of bin bits");
2330 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002331 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2332
2333 DCHECK_LT(GetBin(), kBinSize);
2334 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2335}
2336
2337ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2338 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2339 DCHECK_EQ(index, GetIndex());
2340}
2341
2342ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2343 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2344}
2345
2346uint32_t ImageWriter::BinSlot::GetIndex() const {
2347 return lockword_ & ~kBinMask;
2348}
2349
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002350ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2351 switch (type) {
2352 case kNativeObjectRelocationTypeArtField:
2353 case kNativeObjectRelocationTypeArtFieldArray:
2354 return kBinArtField;
2355 case kNativeObjectRelocationTypeArtMethodClean:
2356 case kNativeObjectRelocationTypeArtMethodArrayClean:
2357 return kBinArtMethodClean;
2358 case kNativeObjectRelocationTypeArtMethodDirty:
2359 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2360 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002361 case kNativeObjectRelocationTypeDexCacheArray:
2362 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002363 case kNativeObjectRelocationTypeRuntimeMethod:
2364 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002365 case kNativeObjectRelocationTypeIMTable:
2366 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002367 case kNativeObjectRelocationTypeIMTConflictTable:
2368 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002369 }
2370 UNREACHABLE();
2371}
2372
Vladimir Marko944da602016-02-19 12:27:55 +00002373size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002374 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002375 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002376 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002377 auto it = oat_index_map_.find(obj);
2378 DCHECK(it != oat_index_map_.end());
2379 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002380}
2381
Vladimir Marko944da602016-02-19 12:27:55 +00002382size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002383 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002384 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002385 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002386 auto it = dex_file_oat_index_map_.find(dex_file);
2387 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2388 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002389}
2390
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002391size_t ImageWriter::GetOatIndexForDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
2392 return (dex_cache == nullptr)
2393 ? GetDefaultOatIndex()
2394 : GetOatIndexForDexFile(dex_cache->GetDexFile());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002395}
2396
Vladimir Marko944da602016-02-19 12:27:55 +00002397void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2398 size_t oat_loaded_size,
2399 size_t oat_data_offset,
2400 size_t oat_data_size) {
2401 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2402 for (const ImageInfo& info : image_infos_) {
2403 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2404 }
2405 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002406
Vladimir Marko944da602016-02-19 12:27:55 +00002407 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2408 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2409 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2410 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2411 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002412
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002413 if (compile_app_image_) {
2414 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2415 return;
2416 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002417
2418 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002419 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002420 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002421 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002422 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2423 }
2424}
2425
Vladimir Marko944da602016-02-19 12:27:55 +00002426void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2427 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2428 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2429
2430 if (oat_index == GetDefaultOatIndex()) {
2431 // Primary oat file, read the trampolines.
2432 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2433 oat_header.GetInterpreterToInterpreterBridgeOffset();
2434 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2435 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2436 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2437 oat_header.GetJniDlsymLookupOffset();
2438 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2439 oat_header.GetQuickGenericJniTrampolineOffset();
2440 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2441 oat_header.GetQuickImtConflictTrampolineOffset();
2442 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2443 oat_header.GetQuickResolutionTrampolineOffset();
2444 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2445 oat_header.GetQuickToInterpreterBridgeOffset();
2446 }
2447}
2448
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002449ImageWriter::ImageWriter(
2450 const CompilerDriver& compiler_driver,
2451 uintptr_t image_begin,
2452 bool compile_pic,
2453 bool compile_app_image,
2454 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002455 const std::vector<const char*>& oat_filenames,
2456 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002457 : compiler_driver_(compiler_driver),
2458 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2459 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002460 compile_pic_(compile_pic),
2461 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002462 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002463 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002464 dirty_methods_(0u),
2465 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002466 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002467 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002468 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002469 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002470 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002471 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2472 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002473}
2474
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002475ImageWriter::ImageInfo::ImageInfo()
2476 : intern_table_(new InternTable),
2477 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002478
Brian Carlstrom7940e442013-07-12 13:46:57 -07002479} // namespace art