blob: 7560011744583bbf1e84fa01a171e57af06c7173 [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);
Narayan Kamath7fe56582016-10-14 18:49:12 +0100464
465 if (dex_cache->GetResolvedMethodTypes() != nullptr) {
466 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethodTypes(),
467 start + layout.MethodTypesOffset(),
468 dex_cache);
469 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000470 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000471}
472
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700473void ImageWriter::AddDexCacheArrayRelocation(void* array,
474 size_t offset,
475 ObjPtr<mirror::DexCache> dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100476 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800477 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000478 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800479 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000480 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100481 }
482}
483
Mathieu Chartiere401d142015-04-22 13:56:20 -0700484void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
485 DCHECK(arr != nullptr);
486 if (kIsDebugBuild) {
487 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800488 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700489 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800490 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800491 CHECK(klass == nullptr || KeepClass(klass))
492 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700493 }
494 }
495 }
496 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
497 // ArtMethods.
498 pointer_arrays_.emplace(arr, kBinArtMethodClean);
499}
500
Mathieu Chartier496577f2016-09-20 15:33:31 -0700501void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800502 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800503 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800504
505 // The magic happens here. We segregate objects into different bins based
506 // on how likely they are to get dirty at runtime.
507 //
508 // Likely-to-dirty objects get packed together into the same bin so that
509 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
510 // maximized.
511 //
512 // This means more pages will stay either clean or shared dirty (with zygote) and
513 // the app will use less of its own (private) memory.
514 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000515 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800516
517 if (kBinObjects) {
518 //
519 // Changing the bin of an object is purely a memory-use tuning.
520 // It has no change on runtime correctness.
521 //
522 // Memory analysis has determined that the following types of objects get dirtied
523 // the most:
524 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000525 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
526 // a fixed layout which helps improve generated code (using PC-relative addressing),
527 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
528 // Since these arrays are huge, most pages do not overlap other objects and it's not
529 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100530 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800531 // * Class'es which are verified [their clinit runs only at runtime]
532 // - classes in general [because their static fields get overwritten]
533 // - initialized classes with all-final statics are unlikely to be ever dirty,
534 // so bin them separately
535 // * Art Methods that are:
536 // - native [their native entry point is not looked up until runtime]
537 // - have declaring classes that aren't initialized
538 // [their interpreter/quick entry points are trampolines until the class
539 // becomes initialized]
540 //
541 // We also assume the following objects get dirtied either never or extremely rarely:
542 // * Strings (they are immutable)
543 // * Art methods that aren't native and have initialized declared classes
544 //
545 // We assume that "regular" bin objects are highly unlikely to become dirtied,
546 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
547 //
548 if (object->IsClass()) {
549 bin = kBinClassVerified;
550 mirror::Class* klass = object->AsClass();
551
Mathieu Chartiere401d142015-04-22 13:56:20 -0700552 // Add non-embedded vtable to the pointer array table if there is one.
553 auto* vtable = klass->GetVTable();
554 if (vtable != nullptr) {
555 AddMethodPointerArray(vtable);
556 }
557 auto* iftable = klass->GetIfTable();
558 if (iftable != nullptr) {
559 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
560 if (iftable->GetMethodArrayCount(i) > 0) {
561 AddMethodPointerArray(iftable->GetMethodArray(i));
562 }
563 }
564 }
565
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800566 if (klass->GetStatus() == Class::kStatusInitialized) {
567 bin = kBinClassInitialized;
568
569 // If the class's static fields are all final, put it into a separate bin
570 // since it's very likely it will stay clean.
571 uint32_t num_static_fields = klass->NumStaticFields();
572 if (num_static_fields == 0) {
573 bin = kBinClassInitializedFinalStatics;
574 } else {
575 // Maybe all the statics are final?
576 bool all_final = true;
577 for (uint32_t i = 0; i < num_static_fields; ++i) {
578 ArtField* field = klass->GetStaticField(i);
579 if (!field->IsFinal()) {
580 all_final = false;
581 break;
582 }
583 }
584
585 if (all_final) {
586 bin = kBinClassInitializedFinalStatics;
587 }
588 }
589 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800590 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
591 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700592 } else if (object->GetClass<kVerifyNone>() ==
593 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
594 // Instance of java lang object, probably a lock object. This means it will be dirty when we
595 // synchronize on it.
596 bin = kBinMiscDirty;
597 } else if (object->IsDexCache()) {
598 // Dex file field becomes dirty when the image is loaded.
599 bin = kBinMiscDirty;
600 }
601 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800602 }
603
Mathieu Chartier496577f2016-09-20 15:33:31 -0700604 // Assign the oat index too.
605 DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
606 oat_index_map_.emplace(object, oat_index);
607
Vladimir Marko944da602016-02-19 12:27:55 +0000608 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800609
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800610 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800611 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
612 // Move the current bin size up to accommodate the object we just assigned a bin slot.
613 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800614
615 BinSlot new_bin_slot(bin, current_offset);
616 SetImageBinSlot(object, new_bin_slot);
617
Jeff Haodcdc85b2015-12-04 14:06:18 -0800618 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800619
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800620 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800621 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800622}
623
Mathieu Chartiere401d142015-04-22 13:56:20 -0700624bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
625 if (m->IsNative()) {
626 return true;
627 }
628 mirror::Class* declaring_class = m->GetDeclaringClass();
629 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
630 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
631}
632
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800633bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
634 DCHECK(object != nullptr);
635
636 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
637 // If it's in some other state, then we haven't yet assigned an image bin slot.
638 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
639 return false;
640 } else if (kIsDebugBuild) {
641 LockWord lock_word = object->GetLockWord(false);
642 size_t offset = lock_word.ForwardingAddress();
643 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000644 size_t oat_index = GetOatIndex(object);
645 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800646 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800647 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800648 }
649 return true;
650}
651
652ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
653 DCHECK(object != nullptr);
654 DCHECK(IsImageBinSlotAssigned(object));
655
656 LockWord lock_word = object->GetLockWord(false);
657 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
658 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
659
660 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000661 size_t oat_index = GetOatIndex(object);
662 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800663 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800664
665 return bin_slot;
666}
667
Brian Carlstrom7940e442013-07-12 13:46:57 -0700668bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000669 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800670 ImageSection unused_sections[ImageHeader::kSectionCount];
671 const size_t length = RoundUp(
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700672 image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800673
Jeff Haodcdc85b2015-12-04 14:06:18 -0800674 std::string error_msg;
675 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
676 nullptr,
677 length,
678 PROT_READ | PROT_WRITE,
679 false,
680 false,
681 &error_msg));
682 if (UNLIKELY(image_info.image_.get() == nullptr)) {
683 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
684 return false;
685 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700686
Jeff Haodcdc85b2015-12-04 14:06:18 -0800687 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
688 CHECK_LE(image_info.image_end_, length);
689 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
690 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
691 if (image_info.image_bitmap_.get() == nullptr) {
692 LOG(ERROR) << "Failed to allocate memory for image bitmap";
693 return false;
694 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700695 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700696 return true;
697}
698
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700699class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
700 public:
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700701 bool operator()(Class* c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700702 StackHandleScope<1> hs(Thread::Current());
703 mirror::Class::ComputeName(hs.NewHandle(c));
704 return true;
705 }
706};
707
Brian Carlstrom7940e442013-07-12 13:46:57 -0700708void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700709 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700710 ComputeLazyFieldsForClassesVisitor visitor;
711 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700712}
713
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700714static bool IsBootClassLoaderClass(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800715 return klass->GetClassLoader() == nullptr;
716}
717
718bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
719 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
720}
721
Mathieu Chartier901e0702016-02-19 13:42:48 -0800722bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800723 bool early_exit = false;
724 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800725 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800726}
727
Mathieu Chartier901e0702016-02-19 13:42:48 -0800728bool ImageWriter::PruneAppImageClassInternal(
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800729 mirror::Class* klass,
730 bool* early_exit,
731 std::unordered_set<mirror::Class*>* visited) {
732 DCHECK(early_exit != nullptr);
733 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800734 DCHECK(compile_app_image_);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800735 if (klass == nullptr || IsInBootImage(klass)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700736 return false;
737 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800738 auto found = prune_class_memo_.find(klass);
739 if (found != prune_class_memo_.end()) {
740 // Already computed, return the found value.
741 return found->second;
742 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800743 // Circular dependencies, return false but do not store the result in the memoization table.
744 if (visited->find(klass) != visited->end()) {
745 *early_exit = true;
746 return false;
747 }
748 visited->emplace(klass);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800749 bool result = IsBootClassLoaderClass(klass);
750 std::string temp;
751 // Prune if not an image class, this handles any broken sets of image classes such as having a
752 // class in the set but not it's superclass.
753 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800754 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800755 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
756 // app image.
757 if (klass->GetStatus() == mirror::Class::kStatusError) {
758 result = true;
759 } else {
760 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
761 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800762 if (!result) {
763 // Check interfaces since these wont be visited through VisitReferences.)
764 mirror::IfTable* if_table = klass->GetIfTable();
765 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800766 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
767 &my_early_exit,
768 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800769 }
770 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800771 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800772 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
773 &my_early_exit,
774 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800775 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800776 // Check static fields and their classes.
777 size_t num_static_fields = klass->NumReferenceStaticFields();
778 if (num_static_fields != 0 && klass->IsResolved()) {
779 // Presumably GC can happen when we are cross compiling, it should not cause performance
780 // problems to do pointer size logic.
781 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
782 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
783 for (size_t i = 0u; i < num_static_fields; ++i) {
784 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
785 if (ref != nullptr) {
786 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800787 result = result || PruneAppImageClassInternal(ref->AsClass(),
788 &my_early_exit,
789 visited);
790 } else {
791 result = result || PruneAppImageClassInternal(ref->GetClass(),
792 &my_early_exit,
793 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800794 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800795 }
796 field_offset = MemberOffset(field_offset.Uint32Value() +
797 sizeof(mirror::HeapReference<mirror::Object>));
798 }
799 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800800 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
801 &my_early_exit,
802 visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800803 // Erase the element we stored earlier since we are exiting the function.
804 auto it = visited->find(klass);
805 DCHECK(it != visited->end());
806 visited->erase(it);
807 // Only store result if it is true or none of the calls early exited due to circular
808 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
809 // a child call and we can remember the result.
810 if (result == true || !my_early_exit || visited->empty()) {
811 prune_class_memo_[klass] = result;
812 }
813 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800814 return result;
815}
816
817bool ImageWriter::KeepClass(Class* klass) {
818 if (klass == nullptr) {
819 return false;
820 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800821 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
822 // Already in boot image, return true.
823 return true;
824 }
825 std::string temp;
826 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
827 return false;
828 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800829 if (compile_app_image_) {
830 // For app images, we need to prune boot loader classes that are not in the boot image since
831 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800832 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800833 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800834 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800835 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700836}
837
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700838class NonImageClassesVisitor : public ClassVisitor {
839 public:
840 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
841
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700842 bool operator()(Class* klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800843 if (!image_writer_->KeepClass(klass)) {
844 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700845 }
846 return true;
847 }
848
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800849 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700850 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700851};
852
853void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700854 Runtime* runtime = Runtime::Current();
855 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700856 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700857
Mathieu Chartier696632e2016-06-03 17:47:32 -0700858 // Clear class table strong roots so that dex caches can get pruned. We require pruning the class
859 // path dex caches.
860 class_linker->ClearClassTableStrongRoots();
861
Brian Carlstrom7940e442013-07-12 13:46:57 -0700862 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700863 NonImageClassesVisitor visitor(this);
864 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700865
866 // Remove the undesired classes from the class roots.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800867 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800868 for (mirror::Class* klass : visitor.classes_to_prune_) {
869 std::string temp;
870 const char* name = klass->GetDescriptor(&temp);
871 VLOG(compiler) << "Pruning class " << name;
872 if (!compile_app_image_) {
873 DCHECK(IsBootClassLoaderClass(klass));
874 }
875 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800876 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700877 }
878
879 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100880 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700881
Mathieu Chartier268764d2016-09-13 12:09:38 -0700882 ScopedAssertNoThreadSuspension sa(__FUNCTION__);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700883 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
884 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800885 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800886 if (self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700887 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700888 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700889 ObjPtr<mirror::DexCache> dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700890 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
891 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800892 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700893 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700894 }
895 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100896 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
897 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
898 ArtMethod* method =
899 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800900 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
901 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800902 // 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 -0800903 // declaring class which is an image class. Set it to the resolution method to be safe and
904 // prevent dangling pointers.
Alex Light36121492016-02-22 13:43:29 -0800905 if (method->IsCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800906 mirror::DexCache::SetElementPtrSize(resolved_methods,
907 i,
908 resolution_method,
909 target_ptr_size_);
910 } else {
911 // Check that the class is still in the classes table.
912 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
913 << PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700914 }
915 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800916 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700917 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800918 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700919 if (field != nullptr && !KeepClass(field->GetDeclaringClass().Ptr())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700920 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700921 }
922 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700923 // Clean the dex field. It might have been populated during the initialization phase, but
924 // contains data only valid during a real run.
925 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700926 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700927
928 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
929 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800930
931 // Clear to save RAM.
932 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700933}
934
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800935void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700936 if (compiler_driver_.GetImageClasses() != nullptr) {
937 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700938 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700939 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700940}
941
942void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
943 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800944 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700945 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800946 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700947 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700948 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800949 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
950 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700951 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700952 }
953}
954
955void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700956 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700957 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700958 for (const std::string& image_class : *image_classes) {
959 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700960 }
961}
962
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800963mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
964 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +0000965 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800966 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
967 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
968 << string->ToModifiedUtf8();
969 if (found != nullptr) {
970 return found;
971 }
972 }
973 if (compile_app_image_) {
974 Runtime* const runtime = Runtime::Current();
975 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
976 // If we found it in the runtime intern table it could either be in the boot image or interned
977 // during app image compilation. If it was in the boot image return that, otherwise return null
978 // since it belongs to another image space.
979 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
980 return found;
981 }
982 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
983 << string->ToModifiedUtf8();
984 }
985 return nullptr;
986}
987
Brian Carlstrom7940e442013-07-12 13:46:57 -0700988
Vladimir Marko944da602016-02-19 12:27:55 +0000989ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700990 Runtime* runtime = Runtime::Current();
991 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700992 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700993 StackHandleScope<3> hs(self);
994 Handle<Class> object_array_class(hs.NewHandle(
995 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700996
Jeff Haodcdc85b2015-12-04 14:06:18 -0800997 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +0000998 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800999 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +00001000 size_t image_oat_index = pair.second;
1001 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001002 image_dex_files.insert(image_dex_file);
1003 }
1004 }
1005
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001006 // build an Object[] of all the DexCaches used in the source_space_.
1007 // Since we can't hold the dex lock when allocating the dex_caches
1008 // ObjectArray, we lock the dex lock twice, first to get the number
1009 // of dex caches first and then lock it again to copy the dex
1010 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001011 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001012 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001013 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001014 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001015 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001016 ObjPtr<mirror::DexCache> dex_cache =
1017 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001018 if (dex_cache == nullptr) {
1019 continue;
1020 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001021 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001022 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001023 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1024 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001025 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001026 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001027 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001028 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001029 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1030 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001031 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001032 size_t non_image_dex_caches = 0;
1033 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001034 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001035 ObjPtr<mirror::DexCache> dex_cache =
1036 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001037 if (dex_cache == nullptr) {
1038 continue;
1039 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001040 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001041 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001042 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1043 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001044 }
1045 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1046 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001047 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001048 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001049 ObjPtr<mirror::DexCache> dex_cache =
1050 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001051 if (dex_cache == nullptr) {
1052 continue;
1053 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001054 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001055 if (!IsInBootImage(dex_cache.Ptr()) &&
1056 image_dex_files.find(dex_file) != image_dex_files.end()) {
1057 dex_caches->Set<false>(i, dex_cache.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001058 ++i;
1059 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001060 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001061 }
1062
1063 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001064 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001065 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001066 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001067 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001068 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001069 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001070 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001071 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001072}
1073
Mathieu Chartier496577f2016-09-20 15:33:31 -07001074mirror::Object* ImageWriter::TryAssignBinSlot(WorkStack& work_stack,
1075 mirror::Object* obj,
1076 size_t oat_index) {
1077 if (obj == nullptr || IsInBootImage(obj)) {
1078 // Object is null or already in the image, there is no work to do.
1079 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001080 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001081 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001082 // We want to intern all strings but also assign offsets for the source string. Since the
1083 // pruning phase has already happened, if we intern a string to one in the image we still
1084 // end up copying an unreachable string.
1085 if (obj->IsString()) {
1086 // Need to check if the string is already interned in another image info so that we don't have
1087 // the intern tables of two different images contain the same string.
1088 mirror::String* interned = FindInternedString(obj->AsString());
1089 if (interned == nullptr) {
1090 // Not in another image space, insert to our table.
1091 interned = GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString());
1092 DCHECK_EQ(interned, obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001093 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001094 } else if (obj->IsDexCache()) {
1095 oat_index = GetOatIndexForDexCache(obj->AsDexCache());
1096 } else if (obj->IsClass()) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001097 // Visit and assign offsets for fields and field arrays.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001098 mirror::Class* as_klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001099 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001100 DCHECK_NE(as_klass->GetStatus(), mirror::Class::kStatusError);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001101 if (compile_app_image_) {
1102 // Extra sanity, no boot loader classes should be left!
1103 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1104 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001105 LengthPrefixedArray<ArtField>* fields[] = {
1106 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1107 };
Mathieu Chartier496577f2016-09-20 15:33:31 -07001108 // Overwrite the oat index value since the class' dex cache is more accurate of where it
1109 // belongs.
1110 oat_index = GetOatIndexForDexCache(dex_cache);
Vladimir Marko944da602016-02-19 12:27:55 +00001111 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001112 {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001113 // Note: This table is only accessed from the image writer, avoid locking to prevent lock
1114 // order violations from root visiting.
1115 image_info.class_table_->InsertWithoutLocks(as_klass);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001116 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001117 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1118 // Total array length including header.
1119 if (cur_fields != nullptr) {
1120 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1121 // Forward the entire array at once.
1122 auto it = native_object_relocations_.find(cur_fields);
1123 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1124 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001125 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001126 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001127 native_object_relocations_.emplace(
1128 cur_fields,
1129 NativeObjectRelocation {
1130 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1131 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001132 offset += header_size;
1133 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001134 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001135 // Need to forward arrays separate of fields.
1136 ArtField* field = &cur_fields->At(i);
1137 auto it2 = native_object_relocations_.find(field);
1138 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1139 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001140 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001141 native_object_relocations_.emplace(
1142 field,
1143 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001144 offset += sizeof(ArtField);
1145 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001146 }
1147 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001148 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001149 size_t num_methods = as_klass->NumMethods();
1150 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001151 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001152 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1153 if (WillMethodBeDirty(&m)) {
1154 any_dirty = true;
1155 break;
1156 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001157 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001158 NativeObjectRelocationType type = any_dirty
1159 ? kNativeObjectRelocationTypeArtMethodDirty
1160 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001161 Bin bin_type = BinTypeForNativeRelocationType(type);
1162 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001163 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1164 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001165 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1166 method_size,
1167 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001168 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001169 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001170 CHECK(it == native_object_relocations_.end())
1171 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001172 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001173 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001174 native_object_relocations_.emplace(array,
1175 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001176 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001177 offset,
1178 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1179 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001180 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001181 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001182 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001183 }
Alex Lighte64300b2015-12-15 15:02:47 -08001184 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001185 }
1186 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1187 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001188 if (as_klass->ShouldHaveImt()) {
1189 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1190 for (size_t i = 0; i < ImTable::kSize; ++i) {
1191 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001192 DCHECK(imt_method != nullptr);
1193 if (imt_method->IsRuntimeMethod() &&
1194 !IsInBootImage(imt_method) &&
1195 !NativeRelocationAssigned(imt_method)) {
1196 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001197 }
1198 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001199 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001200
1201 if (as_klass->ShouldHaveImt()) {
1202 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1203 TryAssignImTableOffset(imt, oat_index);
1204 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001205 } else if (obj->IsClassLoader()) {
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001206 // Register the class loader if it has a class table.
1207 // The fake boot class loader should not get registered and we should end up with only one
1208 // class loader.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001209 mirror::ClassLoader* class_loader = obj->AsClassLoader();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001210 if (class_loader->GetClassTable() != nullptr) {
1211 class_loaders_.insert(class_loader);
1212 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001213 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001214 AssignImageBinSlot(obj, oat_index);
1215 work_stack.emplace(obj, oat_index);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001216 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001217 if (obj->IsString()) {
1218 // Always return the interned string if there exists one.
1219 mirror::String* interned = FindInternedString(obj->AsString());
1220 if (interned != nullptr) {
1221 return interned;
1222 }
1223 }
1224 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001225}
1226
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001227bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1228 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1229}
1230
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001231void ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
1232 // No offset, or already assigned.
1233 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
1234 return;
1235 }
1236 // If the method is a conflict method we also want to assign the conflict table offset.
1237 ImageInfo& image_info = GetImageInfo(oat_index);
1238 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1239 native_object_relocations_.emplace(
1240 imt,
1241 NativeObjectRelocation {
1242 oat_index,
1243 image_info.bin_slot_sizes_[kBinImTable],
1244 kNativeObjectRelocationTypeIMTable});
1245 image_info.bin_slot_sizes_[kBinImTable] += size;
1246}
1247
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001248void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1249 // No offset, or already assigned.
1250 if (table == nullptr || NativeRelocationAssigned(table)) {
1251 return;
1252 }
1253 CHECK(!IsInBootImage(table));
1254 // If the method is a conflict method we also want to assign the conflict table offset.
1255 ImageInfo& image_info = GetImageInfo(oat_index);
1256 const size_t size = table->ComputeSize(target_ptr_size_);
1257 native_object_relocations_.emplace(
1258 table,
1259 NativeObjectRelocation {
1260 oat_index,
1261 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1262 kNativeObjectRelocationTypeIMTConflictTable});
1263 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1264}
1265
Jeff Haodcdc85b2015-12-04 14:06:18 -08001266void ImageWriter::AssignMethodOffset(ArtMethod* method,
1267 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001268 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001269 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001270 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001271 << PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001272 if (method->IsRuntimeMethod()) {
1273 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1274 }
Vladimir Marko944da602016-02-19 12:27:55 +00001275 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001276 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001277 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001278 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001279}
1280
Mathieu Chartier496577f2016-09-20 15:33:31 -07001281void ImageWriter::EnsureBinSlotAssignedCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001282 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1283 DCHECK(writer != nullptr);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001284 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) {
1285 CHECK(writer->IsImageBinSlotAssigned(obj)) << PrettyTypeOf(obj) << " " << obj;
1286 }
1287}
1288
1289void ImageWriter::DeflateMonitorCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED) {
1290 Monitor::Deflate(Thread::Current(), obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001291}
1292
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001293void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1294 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1295 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001296 if (!writer->IsInBootImage(obj)) {
1297 writer->UnbinObjectsIntoOffset(obj);
1298 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001299}
1300
1301void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001302 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001303 CHECK(obj != nullptr);
1304
1305 // We know the bin slot, and the total bin sizes for all objects by now,
1306 // so calculate the object's final image offset.
1307
1308 DCHECK(IsImageBinSlotAssigned(obj));
1309 BinSlot bin_slot = GetImageBinSlot(obj);
1310 // Change the lockword from a bin slot into an offset
1311 AssignImageOffset(obj, bin_slot);
1312}
1313
Mathieu Chartier496577f2016-09-20 15:33:31 -07001314class ImageWriter::VisitReferencesVisitor {
1315 public:
1316 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index)
1317 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {}
1318
1319 // Fix up separately since we also need to fix up method entrypoints.
1320 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1321 REQUIRES_SHARED(Locks::mutator_lock_) {
1322 if (!root->IsNull()) {
1323 VisitRoot(root);
1324 }
1325 }
1326
1327 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1328 REQUIRES_SHARED(Locks::mutator_lock_) {
1329 root->Assign(VisitReference(root->AsMirrorPtr()));
1330 }
1331
1332 ALWAYS_INLINE void operator() (mirror::Object* obj,
1333 MemberOffset offset,
1334 bool is_static ATTRIBUTE_UNUSED) const
1335 REQUIRES_SHARED(Locks::mutator_lock_) {
1336 mirror::Object* ref =
1337 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1338 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1339 }
1340
1341 ALWAYS_INLINE void operator() (mirror::Class* klass ATTRIBUTE_UNUSED,
1342 mirror::Reference* ref) const
1343 REQUIRES_SHARED(Locks::mutator_lock_) {
1344 ref->SetReferent</*kTransactionActive*/false>(
1345 VisitReference(ref->GetReferent<kWithoutReadBarrier>()));
1346 }
1347
1348 private:
1349 mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1350 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_);
1351 }
1352
1353 ImageWriter* const image_writer_;
1354 WorkStack* const work_stack_;
1355 const size_t oat_index_;
1356};
1357
1358class ImageWriter::GetRootsVisitor : public RootVisitor {
1359 public:
1360 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {}
1361
1362 void VisitRoots(mirror::Object*** roots,
1363 size_t count,
1364 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1365 REQUIRES_SHARED(Locks::mutator_lock_) {
1366 for (size_t i = 0; i < count; ++i) {
1367 roots_->push_back(*roots[i]);
1368 }
1369 }
1370
1371 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1372 size_t count,
1373 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1374 REQUIRES_SHARED(Locks::mutator_lock_) {
1375 for (size_t i = 0; i < count; ++i) {
1376 roots_->push_back(roots[i]->AsMirrorPtr());
1377 }
1378 }
1379
1380 private:
1381 std::vector<mirror::Object*>* const roots_;
1382};
1383
1384void ImageWriter::ProcessWorkStack(WorkStack* work_stack) {
1385 while (!work_stack->empty()) {
1386 std::pair<mirror::Object*, size_t> pair(work_stack->top());
1387 work_stack->pop();
1388 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second);
1389 // Walk references and assign bin slots for them.
1390 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1391 visitor,
1392 visitor);
1393 }
1394}
1395
Vladimir Markof4da6752014-08-01 19:04:18 +01001396void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001397 Thread* const self = Thread::Current();
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07001398 VariableSizedHandleScope handles(self);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001399 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001400 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1401 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001402 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001403
Mathieu Chartier496577f2016-09-20 15:33:31 -07001404 Runtime* const runtime = Runtime::Current();
1405 gc::Heap* const heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001406
Mathieu Chartier31e89252013-08-28 11:29:12 -07001407 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001408 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001409 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001410
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001411 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001412 // Write the image runtime methods.
1413 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1414 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1415 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001416 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
1417 runtime->GetCalleeSaveMethod(Runtime::kSaveAllCalleeSaves);
1418 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
1419 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsOnly);
1420 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
1421 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001422 image_methods_[ImageHeader::kSaveEverythingMethod] =
1423 runtime->GetCalleeSaveMethod(Runtime::kSaveEverything);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001424 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001425 for (auto* m : image_methods_) {
1426 CHECK(m != nullptr);
1427 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001428 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1429 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001430 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001431 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001432 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001433
Mathieu Chartier496577f2016-09-20 15:33:31 -07001434 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
1435 // this lock while holding other locks may cause lock order violations.
1436 heap->VisitObjects(DeflateMonitorCallback, this);
1437
1438 // Work list of <object, oat_index> for objects. Everything on the stack must already be
1439 // assigned a bin slot.
1440 WorkStack work_stack;
1441
1442 // Special case interned strings to put them in the image they are likely to be resolved from.
1443 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
1444 auto it = dex_file_oat_index_map_.find(dex_file);
1445 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1446 const size_t oat_index = it->second;
1447 InternTable* const intern_table = runtime->GetInternTable();
1448 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
1449 uint32_t utf16_length;
1450 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(i, &utf16_length);
1451 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data);
1452 TryAssignBinSlot(work_stack, string, oat_index);
1453 }
1454 }
1455
1456 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor
1457 // visits roots while holding various locks.
1458 {
1459 std::vector<mirror::Object*> roots;
1460 GetRootsVisitor root_visitor(&roots);
1461 runtime->VisitRoots(&root_visitor);
1462 for (mirror::Object* obj : roots) {
1463 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex());
1464 }
1465 }
1466 ProcessWorkStack(&work_stack);
1467
1468 // For app images, there may be objects that are only held live by the by the boot image. One
1469 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback
1470 // does not fail any checks. TODO: We should probably avoid copying these objects.
1471 if (compile_app_image_) {
1472 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) {
1473 DCHECK(space->IsImageSpace());
1474 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1475 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1476 reinterpret_cast<uintptr_t>(space->Limit()),
1477 [this, &work_stack](mirror::Object* obj)
1478 REQUIRES_SHARED(Locks::mutator_lock_) {
1479 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex());
1480 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot).
1481 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1482 visitor,
1483 visitor);
1484 });
1485 }
1486 // Process the work stack in case anything was added by TryAssignBinSlot.
1487 ProcessWorkStack(&work_stack);
1488 }
1489
1490 // Verify that all objects have assigned image bin slots.
1491 heap->VisitObjects(EnsureBinSlotAssignedCallback, this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001492
Vladimir Marko05792b92015-08-03 11:56:49 +01001493 // Calculate size of the dex cache arrays slot and prepare offsets.
1494 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001495
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001496 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001497 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001498 // Calculate how big the intern table will be after being serialized.
1499 InternTable* const intern_table = image_info.intern_table_.get();
1500 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1501 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001502 // Calculate the size of the class table.
1503 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1504 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001505 }
1506
Vladimir Markocf36d492015-08-12 19:27:26 +01001507 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001508 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001509 size_t bin_offset = image_objects_offset_begin_;
1510 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001511 switch (i) {
1512 case kBinArtMethodClean:
1513 case kBinArtMethodDirty: {
1514 bin_offset = RoundUp(bin_offset, method_alignment);
1515 break;
1516 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001517 case kBinDexCacheArray:
1518 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment());
1519 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001520 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001521 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001522 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001523 break;
1524 }
1525 default: {
1526 // Normal alignment.
1527 }
1528 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001529 image_info.bin_slot_offsets_[i] = bin_offset;
1530 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001531 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001532 // NOTE: There may be additional padding between the bin slots and the intern table.
1533 DCHECK_EQ(image_info.image_end_,
1534 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001535 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001536
Jeff Haodcdc85b2015-12-04 14:06:18 -08001537 // Calculate image offsets.
1538 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001539 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001540 image_info.image_begin_ = global_image_begin_ + image_offset;
1541 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001542 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001543 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001544 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001545 image_offset += image_info.image_size_;
1546 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001547
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001548 // Transform each object's bin slot into an offset which will be used to do the final copy.
1549 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001550
Jeff Haodcdc85b2015-12-04 14:06:18 -08001551 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001552
Jeff Haodcdc85b2015-12-04 14:06:18 -08001553 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001554 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001555 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1556 i++;
1557 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001558
Mathieu Chartiere401d142015-04-22 13:56:20 -07001559 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001560 for (auto& pair : native_object_relocations_) {
1561 NativeObjectRelocation& relocation = pair.second;
1562 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001563 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001564 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001565 }
1566
Jeff Haodcdc85b2015-12-04 14:06:18 -08001567 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001568}
1569
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001570size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001571 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001572
1573 // Do not round up any sections here that are represented by the bins since it will break
1574 // offsets.
1575
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001576 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001577 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001578 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001579
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001580 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001581 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1582 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001583 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001584
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001585 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001586 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1587 *methods_section = ImageSection(
1588 bin_slot_offsets_[kBinArtMethodClean],
1589 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1590
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001591 // IMT section.
1592 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1593 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1594
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001595 // Conflict tables section.
1596 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1597 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1598 bin_slot_sizes_[kBinIMTConflictTable]);
1599
1600 // Runtime methods section.
1601 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1602 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1603 bin_slot_sizes_[kBinRuntimeMethod]);
1604
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001605 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001606 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1607 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1608 bin_slot_sizes_[kBinDexCacheArray]);
1609
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001610 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001611 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001612 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001613 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001614 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1615 cur_pos = interned_strings_section->End();
1616 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1617 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1618 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001619 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001620 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001621 cur_pos = class_table_section->End();
1622 // Image end goes right before the start of the image bitmap.
1623 return cur_pos;
1624}
1625
Vladimir Marko944da602016-02-19 12:27:55 +00001626void ImageWriter::CreateHeader(size_t oat_index) {
1627 ImageInfo& image_info = GetImageInfo(oat_index);
1628 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1629 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1630 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001631
1632 // Create the image sections.
1633 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001634 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001635
Mathieu Chartiere401d142015-04-22 13:56:20 -07001636 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001637 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001638 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001639 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001640 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001641 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001642 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001643 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001644 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1645 ++idx;
1646 }
1647 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001648 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1649 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1650 << " Image offset=" << image_info.image_offset_ << std::dec;
1651 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1652 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1653 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1654 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001655 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001656 // Store boot image info for app image so that we can relocate.
1657 uint32_t boot_image_begin = 0;
1658 uint32_t boot_image_end = 0;
1659 uint32_t boot_oat_begin = 0;
1660 uint32_t boot_oat_end = 0;
1661 gc::Heap* const heap = Runtime::Current()->GetHeap();
1662 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001663
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001664 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1665 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001666 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1667 image_end,
1668 sections,
1669 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001670 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001671 PointerToLowMemUInt32(oat_file_begin),
1672 PointerToLowMemUInt32(image_info.oat_data_begin_),
1673 PointerToLowMemUInt32(oat_data_end),
1674 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001675 boot_image_begin,
1676 boot_image_end - boot_image_begin,
1677 boot_oat_begin,
1678 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001679 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001680 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001681 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001682 image_storage_mode_,
1683 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001684}
1685
1686ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001687 auto it = native_object_relocations_.find(method);
1688 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001689 size_t oat_index = GetOatIndex(method->GetDexCache());
1690 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001691 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1692 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001693}
1694
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001695class FixupRootVisitor : public RootVisitor {
1696 public:
1697 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1698 }
1699
1700 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001701 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001702 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001703 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001704 }
1705 }
1706
1707 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1708 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001709 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001710 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001711 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001712 }
1713 }
1714
1715 private:
1716 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001717};
1718
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001719void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
1720 for (size_t i = 0; i < ImTable::kSize; ++i) {
1721 ArtMethod* method = orig->Get(i, target_ptr_size_);
1722 copy->Set(i, NativeLocationInImage(method), target_ptr_size_);
1723 }
1724}
1725
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001726void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
1727 const size_t count = orig->NumEntries(target_ptr_size_);
1728 for (size_t i = 0; i < count; ++i) {
1729 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
1730 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
1731 copy->SetInterfaceMethod(i, target_ptr_size_, NativeLocationInImage(interface_method));
1732 copy->SetImplementationMethod(i,
1733 target_ptr_size_,
1734 NativeLocationInImage(implementation_method));
1735 }
1736}
1737
Vladimir Marko944da602016-02-19 12:27:55 +00001738void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001739 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001740 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001741 for (auto& pair : native_object_relocations_) {
1742 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001743 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001744 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001745 continue;
1746 }
1747 auto* dest = image_info.image_->Begin() + relocation.offset;
1748 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001749 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001750 switch (relocation.type) {
1751 case kNativeObjectRelocationTypeArtField: {
1752 memcpy(dest, pair.first, sizeof(ArtField));
1753 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001754 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass().Ptr()));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001755 break;
1756 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001757 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001758 case kNativeObjectRelocationTypeArtMethodClean:
1759 case kNativeObjectRelocationTypeArtMethodDirty: {
1760 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001761 reinterpret_cast<ArtMethod*>(dest),
1762 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001763 break;
1764 }
1765 // For arrays, copy just the header since the elements will get copied by their corresponding
1766 // relocations.
1767 case kNativeObjectRelocationTypeArtFieldArray: {
1768 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1769 break;
1770 }
1771 case kNativeObjectRelocationTypeArtMethodArrayClean:
1772 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00001773 size_t size = ArtMethod::Size(target_ptr_size_);
1774 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1775 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1776 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1777 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001778 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00001779 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001780 case kNativeObjectRelocationTypeDexCacheArray:
1781 // Nothing to copy here, everything is done in FixupDexCache().
1782 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001783 case kNativeObjectRelocationTypeIMTable: {
1784 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
1785 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
1786 CopyAndFixupImTable(orig_imt, dest_imt);
1787 break;
1788 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001789 case kNativeObjectRelocationTypeIMTConflictTable: {
1790 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
1791 CopyAndFixupImtConflictTable(
1792 orig_table,
1793 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
1794 break;
1795 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001796 }
1797 }
1798 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001799 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001800 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001801 ArtMethod* method = image_methods_[i];
1802 CHECK(method != nullptr);
1803 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001804 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001805 }
1806 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001807 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001808 FixupRootVisitor root_visitor(this);
1809
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001810 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001811 if (image_info.intern_table_bytes_ > 0) {
1812 const ImageSection& intern_table_section = image_header->GetImageSection(
1813 ImageHeader::kSectionInternedStrings);
1814 InternTable* const intern_table = image_info.intern_table_.get();
1815 uint8_t* const intern_table_memory_ptr =
1816 image_info.image_->Begin() + intern_table_section.Offset();
1817 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1818 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1819 // Fixup the pointers in the newly written intern table to contain image addresses.
1820 InternTable temp_intern_table;
1821 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1822 // the VisitRoots() will update the memory directly rather than the copies.
1823 // This also relies on visit roots not doing any verification which could fail after we update
1824 // the roots to be the image addresses.
1825 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1826 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1827 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1828 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001829 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1830 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001831 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001832 const ImageSection& class_table_section = image_header->GetImageSection(
1833 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001834 uint8_t* const class_table_memory_ptr =
1835 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001836 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001837
1838 ClassTable* table = image_info.class_table_.get();
1839 CHECK(table != nullptr);
1840 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1841 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1842 // Fixup the pointers in the newly written class table to contain image addresses. See
1843 // above comment for intern tables.
1844 ClassTable temp_class_table;
1845 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1846 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1847 table->NumZygoteClasses());
1848 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1849 RootInfo(kRootUnknown));
1850 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001851 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001852}
1853
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001854void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001855 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001856 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1857 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001858 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001859 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001860 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1861 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001862 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001863 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001864}
1865
Mathieu Chartier590fee92013-09-13 13:46:47 -07001866void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001867 DCHECK(obj != nullptr);
1868 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001869 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1870}
1871
Mathieu Chartiere401d142015-04-22 13:56:20 -07001872void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1873 mirror::Class* klass, Bin array_type) {
1874 CHECK(klass->IsArrayClass());
1875 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1876 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001877 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001878 dst->SetClass(GetImageAddress(arr->GetClass()));
1879 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001880 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001881 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1882 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001883 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001884 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001885 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001886 auto* method = reinterpret_cast<ArtMethod*>(elem);
1887 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1888 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1889 << PrettyClass(method->GetDeclaringClass());
1890 } else {
1891 CHECK_EQ(array_type, kBinArtField);
1892 auto* field = reinterpret_cast<ArtField*>(elem);
1893 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1894 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1895 << PrettyClass(field->GetDeclaringClass());
1896 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001897 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001898 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001899 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001900 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001901 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001902 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001903 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001904 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001905}
1906
1907void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001908 if (IsInBootImage(obj)) {
1909 return;
1910 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001911 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001912 size_t oat_index = GetOatIndex(obj);
1913 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001914 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1915 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001916 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001917
Jeff Haodcdc85b2015-12-04 14:06:18 -08001918 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001919
1920 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001921 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001922 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001923
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001924 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1925 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001926 const auto it = saved_hashcode_map_.find(obj);
1927 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1928 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001929 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
1930 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
1931 // safe since we mark all of the objects that may reference non immune objects as gray.
1932 CHECK(dst->AtomicSetMarkBit(0, 1));
1933 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001934 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001935}
1936
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001937// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001938class FixupVisitor {
1939 public:
1940 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1941 }
1942
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001943 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1944 // with other logic.
1945 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1946 const {}
1947 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1948
1949
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001950 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001951 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001952 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001953 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1954 // image.
1955 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001956 offset,
1957 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001958 }
1959
1960 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001961 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001962 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001963 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001964 mirror::Reference::ReferentOffset(),
1965 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001966 }
1967
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001968 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001969 ImageWriter* const image_writer_;
1970 mirror::Object* const copy_;
1971};
1972
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001973class FixupClassVisitor FINAL : public FixupVisitor {
1974 public:
1975 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1976 }
1977
Mathieu Chartierc7853442015-03-27 14:35:38 -07001978 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001979 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001980 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001981 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001982 }
1983
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001984 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1985 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001986 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001987 LOG(FATAL) << "Reference not expected here.";
1988 }
1989};
1990
Vladimir Marko05792b92015-08-03 11:56:49 +01001991uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1992 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001993 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001994 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001995 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1996 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001997 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001998 return relocation.offset;
1999}
2000
2001template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002002std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002003 std::ostringstream oss;
2004 oss << ptr;
2005 return oss.str();
2006}
2007
2008template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002009std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002010 return PrettyMethod(method);
2011}
2012
2013template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002014T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002015 if (obj == nullptr || IsInBootImage(obj)) {
2016 return obj;
2017 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002018 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002019 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
2020 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002021 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00002022 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002023 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002024 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002025}
2026
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002027template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08002028T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
2029 if (obj == nullptr || IsInBootImage(obj)) {
2030 return obj;
2031 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002032 size_t oat_index = GetOatIndexForDexCache(dex_cache);
2033 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002034 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
2035 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002036}
2037
2038class NativeLocationVisitor {
2039 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002040 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002041
2042 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002043 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002044 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002045 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002046
2047 private:
2048 ImageWriter* const image_writer_;
2049};
2050
2051void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002052 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002053 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002054 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002055
2056 // Remove the clinitThreadId. This is required for image determinism.
2057 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002058}
2059
Ian Rogersef7d42f2014-01-06 12:55:46 -08002060void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002061 DCHECK(orig != nullptr);
2062 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002063 if (kUseBakerOrBrooksReadBarrier) {
2064 orig->AssertReadBarrierPointer();
2065 if (kUseBrooksReadBarrier) {
2066 // Note the address 'copy' isn't the same as the image address of 'orig'.
2067 copy->SetReadBarrierPointer(GetImageAddress(orig));
2068 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
2069 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002070 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002071 auto* klass = orig->GetClass();
2072 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002073 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07002074 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
2075 if (it != pointer_arrays_.end()) {
2076 // Should only need to fixup every pointer array exactly once.
2077 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
2078 pointer_arrays_.erase(it);
2079 return;
2080 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002081 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002082 if (orig->IsClass()) {
2083 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002084 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002085 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
2086 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01002087 auto* dest = down_cast<mirror::Executable*>(copy);
2088 auto* src = down_cast<mirror::Executable*>(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002089 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05002090 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01002091 } else if (!klass->IsArrayClass()) {
2092 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2093 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
2094 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002095 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002096 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002097 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2098 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002099 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002100 // Also set allocator to null to be safe. The allocator is created when we create the class
2101 // table. We also never expect to unload things in the image since they are held live as
2102 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002103 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002104 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002105 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002106 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002107 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002108 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002109}
2110
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002111
2112class ImageAddressVisitor {
2113 public:
2114 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
2115
2116 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002117 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002118 return image_writer_->GetImageAddress(ptr);
2119 }
2120
2121 private:
2122 ImageWriter* const image_writer_;
2123};
2124
2125
Vladimir Marko05792b92015-08-03 11:56:49 +01002126void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2127 mirror::DexCache* copy_dex_cache) {
2128 // Though the DexCache array fields are usually treated as native pointers, we set the full
2129 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2130 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2131 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002132 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002133 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002134 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002135 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002136 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002137 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
2138 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002139 }
2140 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
2141 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002142 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002143 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002144 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002145 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
2146 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002147 }
2148 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
2149 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002150 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002151 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002152 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002153 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002154 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
2155 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002156 // NativeLocationInImage also handles runtime methods since these have relocation info.
2157 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002158 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
2159 }
2160 }
2161 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
2162 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002163 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002164 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002165 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002166 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002167 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
2168 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002169 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002170 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
2171 }
2172 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01002173 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
2174 if (orig_method_types != nullptr) {
2175 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodTypesOffset(),
2176 NativeLocationInImage(orig_method_types),
2177 PointerSize::k64);
2178 orig_dex_cache->FixupResolvedMethodTypes(NativeCopyLocation(orig_method_types, orig_dex_cache),
2179 ImageAddressVisitor(this));
2180 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002181
2182 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2183 // compiler pointers in here will make the output non-deterministic.
2184 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002185}
2186
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002187const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2188 DCHECK_LT(type, kOatAddressCount);
2189 // If we are compiling an app image, we need to use the stubs of the boot image.
2190 if (compile_app_image_) {
2191 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002192 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002193 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2194 DCHECK(!image_spaces.empty());
2195 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002196 CHECK(oat_file != nullptr);
2197 const OatHeader& header = oat_file->GetOatHeader();
2198 switch (type) {
2199 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2200 case kOatAddressQuickGenericJNITrampoline:
2201 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2202 case kOatAddressInterpreterToInterpreterBridge:
2203 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2204 case kOatAddressInterpreterToCompiledCodeBridge:
2205 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2206 case kOatAddressJNIDlsymLookup:
2207 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2208 case kOatAddressQuickIMTConflictTrampoline:
2209 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2210 case kOatAddressQuickResolutionTrampoline:
2211 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2212 case kOatAddressQuickToInterpreterBridge:
2213 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2214 default:
2215 UNREACHABLE();
2216 }
2217 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002218 const ImageInfo& primary_image_info = GetImageInfo(0);
2219 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002220}
2221
Jeff Haodcdc85b2015-12-04 14:06:18 -08002222const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2223 const ImageInfo& image_info,
2224 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002225 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
Nicolas Geoffray796d6302016-03-13 22:22:31 +00002226 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002227 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07002228 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002229 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002230
2231 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2232 // trampoline.
2233
2234 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002235 const void* quick_oat_entry_point =
2236 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2237 const uint8_t* quick_code;
2238
2239 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2240 DCHECK(method->IsCopied());
2241 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2242 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2243 } else {
2244 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2245 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2246 }
2247
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002248 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002249 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2250 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002251 // We have code for a non-static or initialized method, just use the code.
2252 } else if (quick_code == nullptr && method->IsNative() &&
2253 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2254 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002255 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002256 } else if (quick_code == nullptr && !method->IsNative()) {
2257 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002258 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002259 *quick_is_interpreted = true;
2260 } else {
2261 CHECK(!method->GetDeclaringClass()->IsInitialized());
2262 // We have code for a static method, but need to go through the resolution stub for class
2263 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002264 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2265 }
2266 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002267 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002268 }
2269 return quick_code;
2270}
2271
Jeff Haodcdc85b2015-12-04 14:06:18 -08002272void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2273 ArtMethod* copy,
2274 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002275 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002276
2277 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002278 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002279 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002280 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002281 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002282
Ian Rogers848871b2013-08-05 10:56:33 -07002283 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2284 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002285
Ian Rogers848871b2013-08-05 10:56:33 -07002286 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002287 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002288 if (orig->IsRuntimeMethod()) {
2289 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2290 if (orig_table != nullptr) {
2291 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2292 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2293 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2294 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2295 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2296 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2297 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2298 } else {
2299 bool found_one = false;
2300 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2301 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2302 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2303 found_one = true;
2304 break;
2305 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002306 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002307 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2308 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002309 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002310 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002311 // We assume all methods have code. If they don't currently then we set them to the use the
2312 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2313 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002314 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002315 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002316 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002317 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002318 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002319 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002320 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002321
Sebastien Hertze1d07812014-05-21 15:44:09 +02002322 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002323 if (orig->IsNative()) {
2324 // The native method's pointer is set to a stub to lookup via dlsym.
2325 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002326 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002327 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002328 }
2329 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002330 }
2331}
2332
Jeff Haodcdc85b2015-12-04 14:06:18 -08002333size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002334 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002335 return std::accumulate(&image_info.bin_slot_sizes_[0],
2336 &image_info.bin_slot_sizes_[up_to],
2337 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002338}
2339
2340ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2341 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002342 static_assert(kBinBits == 3, "wrong number of bin bits");
2343 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002344 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2345
2346 DCHECK_LT(GetBin(), kBinSize);
2347 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2348}
2349
2350ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2351 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2352 DCHECK_EQ(index, GetIndex());
2353}
2354
2355ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2356 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2357}
2358
2359uint32_t ImageWriter::BinSlot::GetIndex() const {
2360 return lockword_ & ~kBinMask;
2361}
2362
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002363ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2364 switch (type) {
2365 case kNativeObjectRelocationTypeArtField:
2366 case kNativeObjectRelocationTypeArtFieldArray:
2367 return kBinArtField;
2368 case kNativeObjectRelocationTypeArtMethodClean:
2369 case kNativeObjectRelocationTypeArtMethodArrayClean:
2370 return kBinArtMethodClean;
2371 case kNativeObjectRelocationTypeArtMethodDirty:
2372 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2373 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002374 case kNativeObjectRelocationTypeDexCacheArray:
2375 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002376 case kNativeObjectRelocationTypeRuntimeMethod:
2377 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002378 case kNativeObjectRelocationTypeIMTable:
2379 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002380 case kNativeObjectRelocationTypeIMTConflictTable:
2381 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002382 }
2383 UNREACHABLE();
2384}
2385
Vladimir Marko944da602016-02-19 12:27:55 +00002386size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002387 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002388 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002389 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002390 auto it = oat_index_map_.find(obj);
2391 DCHECK(it != oat_index_map_.end());
2392 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002393}
2394
Vladimir Marko944da602016-02-19 12:27:55 +00002395size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002396 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002397 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002398 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002399 auto it = dex_file_oat_index_map_.find(dex_file);
2400 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2401 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002402}
2403
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002404size_t ImageWriter::GetOatIndexForDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
2405 return (dex_cache == nullptr)
2406 ? GetDefaultOatIndex()
2407 : GetOatIndexForDexFile(dex_cache->GetDexFile());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002408}
2409
Vladimir Marko944da602016-02-19 12:27:55 +00002410void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2411 size_t oat_loaded_size,
2412 size_t oat_data_offset,
2413 size_t oat_data_size) {
2414 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2415 for (const ImageInfo& info : image_infos_) {
2416 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2417 }
2418 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002419
Vladimir Marko944da602016-02-19 12:27:55 +00002420 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2421 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2422 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2423 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2424 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002425
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002426 if (compile_app_image_) {
2427 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2428 return;
2429 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002430
2431 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002432 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002433 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002434 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002435 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2436 }
2437}
2438
Vladimir Marko944da602016-02-19 12:27:55 +00002439void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2440 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2441 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2442
2443 if (oat_index == GetDefaultOatIndex()) {
2444 // Primary oat file, read the trampolines.
2445 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2446 oat_header.GetInterpreterToInterpreterBridgeOffset();
2447 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2448 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2449 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2450 oat_header.GetJniDlsymLookupOffset();
2451 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2452 oat_header.GetQuickGenericJniTrampolineOffset();
2453 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2454 oat_header.GetQuickImtConflictTrampolineOffset();
2455 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2456 oat_header.GetQuickResolutionTrampolineOffset();
2457 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2458 oat_header.GetQuickToInterpreterBridgeOffset();
2459 }
2460}
2461
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002462ImageWriter::ImageWriter(
2463 const CompilerDriver& compiler_driver,
2464 uintptr_t image_begin,
2465 bool compile_pic,
2466 bool compile_app_image,
2467 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002468 const std::vector<const char*>& oat_filenames,
2469 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002470 : compiler_driver_(compiler_driver),
2471 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2472 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002473 compile_pic_(compile_pic),
2474 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002475 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002476 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002477 dirty_methods_(0u),
2478 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002479 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002480 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002481 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002482 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002483 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002484 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2485 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002486}
2487
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002488ImageWriter::ImageInfo::ImageInfo()
2489 : intern_table_(new InternTable),
2490 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002491
Brian Carlstrom7940e442013-07-12 13:46:57 -07002492} // namespace art