blob: 59f339a9a2dd242c53dcf0780bfa33139d9eb367 [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();
David Sehr709b0702016-10-13 09:12:37 -0700117 CHECK_NE(Class::PrettyClass(klass), "com.android.dex.Dex");
Andreas Gampedd9d0552015-03-09 12:57:41 -0700118}
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))
David Sehr709b0702016-10-13 09:12:37 -0700492 << Class::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:
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700701 bool operator()(ObjPtr<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 {
David Sehr709b0702016-10-13 09:12:37 -0700760 CHECK(klass->GetVerifyError() == nullptr) << klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800761 }
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
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700842 bool operator()(ObjPtr<Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
843 if (!image_writer_->KeepClass(klass.Ptr())) {
844 classes_to_prune_.insert(klass.Ptr());
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 "
David Sehr709b0702016-10-13 09:12:37 -0700913 << Class::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)
David Sehr709b0702016-10-13 09:12:37 -0700950 << " " << klass->PrettyDescriptor();
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 Chartier9e868092016-10-31 14:58:04 -0700966 ObjPtr<mirror::String> const found = image_info.intern_table_->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800967 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
968 << string->ToModifiedUtf8();
969 if (found != nullptr) {
Mathieu Chartier9e868092016-10-31 14:58:04 -0700970 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800971 }
972 }
973 if (compile_app_image_) {
974 Runtime* const runtime = Runtime::Current();
Mathieu Chartier9e868092016-10-31 14:58:04 -0700975 ObjPtr<mirror::String> found = runtime->GetInternTable()->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800976 // 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.
Mathieu Chartier9e868092016-10-31 14:58:04 -0700979 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found.Ptr())) {
980 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800981 }
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.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001091 interned =
1092 GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString()).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001093 DCHECK_EQ(interned, obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001094 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001095 } else if (obj->IsDexCache()) {
1096 oat_index = GetOatIndexForDexCache(obj->AsDexCache());
1097 } else if (obj->IsClass()) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001098 // Visit and assign offsets for fields and field arrays.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001099 mirror::Class* as_klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001100 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001101 DCHECK_NE(as_klass->GetStatus(), mirror::Class::kStatusError);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001102 if (compile_app_image_) {
1103 // Extra sanity, no boot loader classes should be left!
David Sehr709b0702016-10-13 09:12:37 -07001104 CHECK(!IsBootClassLoaderClass(as_klass)) << as_klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001105 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001106 LengthPrefixedArray<ArtField>* fields[] = {
1107 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1108 };
Mathieu Chartier496577f2016-09-20 15:33:31 -07001109 // Overwrite the oat index value since the class' dex cache is more accurate of where it
1110 // belongs.
1111 oat_index = GetOatIndexForDexCache(dex_cache);
Vladimir Marko944da602016-02-19 12:27:55 +00001112 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001113 {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001114 // Note: This table is only accessed from the image writer, avoid locking to prevent lock
1115 // order violations from root visiting.
1116 image_info.class_table_->InsertWithoutLocks(as_klass);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001117 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001118 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1119 // Total array length including header.
1120 if (cur_fields != nullptr) {
1121 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1122 // Forward the entire array at once.
1123 auto it = native_object_relocations_.find(cur_fields);
1124 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1125 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001126 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001127 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001128 native_object_relocations_.emplace(
1129 cur_fields,
1130 NativeObjectRelocation {
1131 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1132 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001133 offset += header_size;
1134 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001135 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001136 // Need to forward arrays separate of fields.
1137 ArtField* field = &cur_fields->At(i);
1138 auto it2 = native_object_relocations_.find(field);
1139 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
David Sehr709b0702016-10-13 09:12:37 -07001140 << " already assigned " << field->PrettyField() << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001141 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001142 native_object_relocations_.emplace(
1143 field,
1144 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001145 offset += sizeof(ArtField);
1146 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001147 }
1148 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001149 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001150 size_t num_methods = as_klass->NumMethods();
1151 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001152 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001153 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1154 if (WillMethodBeDirty(&m)) {
1155 any_dirty = true;
1156 break;
1157 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001158 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001159 NativeObjectRelocationType type = any_dirty
1160 ? kNativeObjectRelocationTypeArtMethodDirty
1161 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001162 Bin bin_type = BinTypeForNativeRelocationType(type);
1163 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001164 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1165 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001166 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1167 method_size,
1168 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001169 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001170 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001171 CHECK(it == native_object_relocations_.end())
1172 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001173 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001174 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001175 native_object_relocations_.emplace(array,
1176 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001177 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001178 offset,
1179 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1180 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001181 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001182 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001183 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001184 }
Alex Lighte64300b2015-12-15 15:02:47 -08001185 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001186 }
1187 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1188 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001189 if (as_klass->ShouldHaveImt()) {
1190 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1191 for (size_t i = 0; i < ImTable::kSize; ++i) {
1192 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001193 DCHECK(imt_method != nullptr);
1194 if (imt_method->IsRuntimeMethod() &&
1195 !IsInBootImage(imt_method) &&
1196 !NativeRelocationAssigned(imt_method)) {
1197 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001198 }
1199 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001200 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001201
1202 if (as_klass->ShouldHaveImt()) {
1203 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1204 TryAssignImTableOffset(imt, oat_index);
1205 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001206 } else if (obj->IsClassLoader()) {
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001207 // Register the class loader if it has a class table.
1208 // The fake boot class loader should not get registered and we should end up with only one
1209 // class loader.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001210 mirror::ClassLoader* class_loader = obj->AsClassLoader();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001211 if (class_loader->GetClassTable() != nullptr) {
1212 class_loaders_.insert(class_loader);
1213 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001214 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001215 AssignImageBinSlot(obj, oat_index);
1216 work_stack.emplace(obj, oat_index);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001217 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001218 if (obj->IsString()) {
1219 // Always return the interned string if there exists one.
1220 mirror::String* interned = FindInternedString(obj->AsString());
1221 if (interned != nullptr) {
1222 return interned;
1223 }
1224 }
1225 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001226}
1227
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001228bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1229 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1230}
1231
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001232void ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
1233 // No offset, or already assigned.
1234 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
1235 return;
1236 }
1237 // If the method is a conflict method we also want to assign the conflict table offset.
1238 ImageInfo& image_info = GetImageInfo(oat_index);
1239 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1240 native_object_relocations_.emplace(
1241 imt,
1242 NativeObjectRelocation {
1243 oat_index,
1244 image_info.bin_slot_sizes_[kBinImTable],
1245 kNativeObjectRelocationTypeIMTable});
1246 image_info.bin_slot_sizes_[kBinImTable] += size;
1247}
1248
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001249void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1250 // No offset, or already assigned.
1251 if (table == nullptr || NativeRelocationAssigned(table)) {
1252 return;
1253 }
1254 CHECK(!IsInBootImage(table));
1255 // If the method is a conflict method we also want to assign the conflict table offset.
1256 ImageInfo& image_info = GetImageInfo(oat_index);
1257 const size_t size = table->ComputeSize(target_ptr_size_);
1258 native_object_relocations_.emplace(
1259 table,
1260 NativeObjectRelocation {
1261 oat_index,
1262 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1263 kNativeObjectRelocationTypeIMTConflictTable});
1264 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1265}
1266
Jeff Haodcdc85b2015-12-04 14:06:18 -08001267void ImageWriter::AssignMethodOffset(ArtMethod* method,
1268 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001269 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001270 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001271 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
David Sehr709b0702016-10-13 09:12:37 -07001272 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001273 if (method->IsRuntimeMethod()) {
1274 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1275 }
Vladimir Marko944da602016-02-19 12:27:55 +00001276 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001277 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001278 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001279 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001280}
1281
Mathieu Chartier496577f2016-09-20 15:33:31 -07001282void ImageWriter::EnsureBinSlotAssignedCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001283 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1284 DCHECK(writer != nullptr);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001285 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) {
David Sehr709b0702016-10-13 09:12:37 -07001286 CHECK(writer->IsImageBinSlotAssigned(obj)) << mirror::Object::PrettyTypeOf(obj) << " " << obj;
Mathieu Chartier496577f2016-09-20 15:33:31 -07001287 }
1288}
1289
1290void ImageWriter::DeflateMonitorCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED) {
1291 Monitor::Deflate(Thread::Current(), obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001292}
1293
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001294void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1295 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1296 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001297 if (!writer->IsInBootImage(obj)) {
1298 writer->UnbinObjectsIntoOffset(obj);
1299 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001300}
1301
1302void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001303 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001304 CHECK(obj != nullptr);
1305
1306 // We know the bin slot, and the total bin sizes for all objects by now,
1307 // so calculate the object's final image offset.
1308
1309 DCHECK(IsImageBinSlotAssigned(obj));
1310 BinSlot bin_slot = GetImageBinSlot(obj);
1311 // Change the lockword from a bin slot into an offset
1312 AssignImageOffset(obj, bin_slot);
1313}
1314
Mathieu Chartier496577f2016-09-20 15:33:31 -07001315class ImageWriter::VisitReferencesVisitor {
1316 public:
1317 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index)
1318 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {}
1319
1320 // Fix up separately since we also need to fix up method entrypoints.
1321 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1322 REQUIRES_SHARED(Locks::mutator_lock_) {
1323 if (!root->IsNull()) {
1324 VisitRoot(root);
1325 }
1326 }
1327
1328 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1329 REQUIRES_SHARED(Locks::mutator_lock_) {
1330 root->Assign(VisitReference(root->AsMirrorPtr()));
1331 }
1332
Mathieu Chartier31e88222016-10-14 18:43:19 -07001333 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
Mathieu Chartier496577f2016-09-20 15:33:31 -07001334 MemberOffset offset,
1335 bool is_static ATTRIBUTE_UNUSED) const
1336 REQUIRES_SHARED(Locks::mutator_lock_) {
1337 mirror::Object* ref =
1338 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1339 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1340 }
1341
Mathieu Chartier31e88222016-10-14 18:43:19 -07001342 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1343 ObjPtr<mirror::Reference> ref) const
Mathieu Chartier496577f2016-09-20 15:33:31 -07001344 REQUIRES_SHARED(Locks::mutator_lock_) {
1345 ref->SetReferent</*kTransactionActive*/false>(
1346 VisitReference(ref->GetReferent<kWithoutReadBarrier>()));
1347 }
1348
1349 private:
1350 mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1351 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_);
1352 }
1353
1354 ImageWriter* const image_writer_;
1355 WorkStack* const work_stack_;
1356 const size_t oat_index_;
1357};
1358
1359class ImageWriter::GetRootsVisitor : public RootVisitor {
1360 public:
1361 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {}
1362
1363 void VisitRoots(mirror::Object*** roots,
1364 size_t count,
1365 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1366 REQUIRES_SHARED(Locks::mutator_lock_) {
1367 for (size_t i = 0; i < count; ++i) {
1368 roots_->push_back(*roots[i]);
1369 }
1370 }
1371
1372 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1373 size_t count,
1374 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1375 REQUIRES_SHARED(Locks::mutator_lock_) {
1376 for (size_t i = 0; i < count; ++i) {
1377 roots_->push_back(roots[i]->AsMirrorPtr());
1378 }
1379 }
1380
1381 private:
1382 std::vector<mirror::Object*>* const roots_;
1383};
1384
1385void ImageWriter::ProcessWorkStack(WorkStack* work_stack) {
1386 while (!work_stack->empty()) {
1387 std::pair<mirror::Object*, size_t> pair(work_stack->top());
1388 work_stack->pop();
1389 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second);
1390 // Walk references and assign bin slots for them.
1391 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1392 visitor,
1393 visitor);
1394 }
1395}
1396
Vladimir Markof4da6752014-08-01 19:04:18 +01001397void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001398 Thread* const self = Thread::Current();
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07001399 VariableSizedHandleScope handles(self);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001400 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001401 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1402 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001403 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001404
Mathieu Chartier496577f2016-09-20 15:33:31 -07001405 Runtime* const runtime = Runtime::Current();
1406 gc::Heap* const heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001407
Mathieu Chartier31e89252013-08-28 11:29:12 -07001408 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001409 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001410 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001411
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001412 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001413 // Write the image runtime methods.
1414 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1415 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1416 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001417 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
1418 runtime->GetCalleeSaveMethod(Runtime::kSaveAllCalleeSaves);
1419 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
1420 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsOnly);
1421 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
1422 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001423 image_methods_[ImageHeader::kSaveEverythingMethod] =
1424 runtime->GetCalleeSaveMethod(Runtime::kSaveEverything);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001425 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001426 for (auto* m : image_methods_) {
1427 CHECK(m != nullptr);
1428 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001429 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1430 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001431 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001432 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001433 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001434
Mathieu Chartier496577f2016-09-20 15:33:31 -07001435 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
1436 // this lock while holding other locks may cause lock order violations.
1437 heap->VisitObjects(DeflateMonitorCallback, this);
1438
1439 // Work list of <object, oat_index> for objects. Everything on the stack must already be
1440 // assigned a bin slot.
1441 WorkStack work_stack;
1442
1443 // Special case interned strings to put them in the image they are likely to be resolved from.
1444 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
1445 auto it = dex_file_oat_index_map_.find(dex_file);
1446 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1447 const size_t oat_index = it->second;
1448 InternTable* const intern_table = runtime->GetInternTable();
1449 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
1450 uint32_t utf16_length;
1451 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(i, &utf16_length);
Mathieu Chartier9e868092016-10-31 14:58:04 -07001452 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001453 TryAssignBinSlot(work_stack, string, oat_index);
1454 }
1455 }
1456
1457 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor
1458 // visits roots while holding various locks.
1459 {
1460 std::vector<mirror::Object*> roots;
1461 GetRootsVisitor root_visitor(&roots);
1462 runtime->VisitRoots(&root_visitor);
1463 for (mirror::Object* obj : roots) {
1464 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex());
1465 }
1466 }
1467 ProcessWorkStack(&work_stack);
1468
1469 // For app images, there may be objects that are only held live by the by the boot image. One
1470 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback
1471 // does not fail any checks. TODO: We should probably avoid copying these objects.
1472 if (compile_app_image_) {
1473 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) {
1474 DCHECK(space->IsImageSpace());
1475 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1476 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1477 reinterpret_cast<uintptr_t>(space->Limit()),
1478 [this, &work_stack](mirror::Object* obj)
1479 REQUIRES_SHARED(Locks::mutator_lock_) {
1480 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex());
1481 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot).
1482 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1483 visitor,
1484 visitor);
1485 });
1486 }
1487 // Process the work stack in case anything was added by TryAssignBinSlot.
1488 ProcessWorkStack(&work_stack);
1489 }
1490
1491 // Verify that all objects have assigned image bin slots.
1492 heap->VisitObjects(EnsureBinSlotAssignedCallback, this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001493
Vladimir Marko05792b92015-08-03 11:56:49 +01001494 // Calculate size of the dex cache arrays slot and prepare offsets.
1495 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001496
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001497 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001498 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001499 // Calculate how big the intern table will be after being serialized.
1500 InternTable* const intern_table = image_info.intern_table_.get();
1501 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
Vladimir Marko1a1de672016-10-13 12:53:15 +01001502 if (intern_table->StrongSize() != 0u) {
1503 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1504 }
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001505 // Calculate the size of the class table.
1506 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko1a1de672016-10-13 12:53:15 +01001507 DCHECK_EQ(image_info.class_table_->NumZygoteClasses(), 0u);
1508 if (image_info.class_table_->NumNonZygoteClasses() != 0u) {
1509 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
1510 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001511 }
1512
Vladimir Markocf36d492015-08-12 19:27:26 +01001513 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001514 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001515 size_t bin_offset = image_objects_offset_begin_;
1516 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001517 switch (i) {
1518 case kBinArtMethodClean:
1519 case kBinArtMethodDirty: {
1520 bin_offset = RoundUp(bin_offset, method_alignment);
1521 break;
1522 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001523 case kBinDexCacheArray:
1524 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment());
1525 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001526 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001527 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001528 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001529 break;
1530 }
1531 default: {
1532 // Normal alignment.
1533 }
1534 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001535 image_info.bin_slot_offsets_[i] = bin_offset;
1536 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001537 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001538 // NOTE: There may be additional padding between the bin slots and the intern table.
1539 DCHECK_EQ(image_info.image_end_,
1540 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001541 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001542
Jeff Haodcdc85b2015-12-04 14:06:18 -08001543 // Calculate image offsets.
1544 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001545 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001546 image_info.image_begin_ = global_image_begin_ + image_offset;
1547 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001548 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001549 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001550 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001551 image_offset += image_info.image_size_;
1552 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001553
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001554 // Transform each object's bin slot into an offset which will be used to do the final copy.
1555 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001556
Jeff Haodcdc85b2015-12-04 14:06:18 -08001557 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001558
Jeff Haodcdc85b2015-12-04 14:06:18 -08001559 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001560 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001561 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1562 i++;
1563 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001564
Mathieu Chartiere401d142015-04-22 13:56:20 -07001565 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001566 for (auto& pair : native_object_relocations_) {
1567 NativeObjectRelocation& relocation = pair.second;
1568 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001569 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001570 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001571 }
1572
Jeff Haodcdc85b2015-12-04 14:06:18 -08001573 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001574}
1575
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001576size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001577 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001578
1579 // Do not round up any sections here that are represented by the bins since it will break
1580 // offsets.
1581
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001582 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001583 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001584 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001585
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001586 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001587 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1588 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001589 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001590
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001591 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001592 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1593 *methods_section = ImageSection(
1594 bin_slot_offsets_[kBinArtMethodClean],
1595 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1596
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001597 // IMT section.
1598 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1599 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1600
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001601 // Conflict tables section.
1602 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1603 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1604 bin_slot_sizes_[kBinIMTConflictTable]);
1605
1606 // Runtime methods section.
1607 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1608 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1609 bin_slot_sizes_[kBinRuntimeMethod]);
1610
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001611 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001612 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1613 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1614 bin_slot_sizes_[kBinDexCacheArray]);
1615
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001616 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001617 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001618 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001619 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001620 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1621 cur_pos = interned_strings_section->End();
1622 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1623 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1624 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001625 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001626 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001627 cur_pos = class_table_section->End();
1628 // Image end goes right before the start of the image bitmap.
1629 return cur_pos;
1630}
1631
Vladimir Marko944da602016-02-19 12:27:55 +00001632void ImageWriter::CreateHeader(size_t oat_index) {
1633 ImageInfo& image_info = GetImageInfo(oat_index);
1634 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1635 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1636 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001637
1638 // Create the image sections.
1639 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001640 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001641
Mathieu Chartiere401d142015-04-22 13:56:20 -07001642 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001643 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001644 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001645 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001646 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001647 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001648 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001649 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001650 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1651 ++idx;
1652 }
1653 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001654 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1655 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1656 << " Image offset=" << image_info.image_offset_ << std::dec;
1657 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1658 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1659 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1660 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001661 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001662 // Store boot image info for app image so that we can relocate.
1663 uint32_t boot_image_begin = 0;
1664 uint32_t boot_image_end = 0;
1665 uint32_t boot_oat_begin = 0;
1666 uint32_t boot_oat_end = 0;
1667 gc::Heap* const heap = Runtime::Current()->GetHeap();
1668 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001669
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001670 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1671 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001672 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1673 image_end,
1674 sections,
1675 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001676 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001677 PointerToLowMemUInt32(oat_file_begin),
1678 PointerToLowMemUInt32(image_info.oat_data_begin_),
1679 PointerToLowMemUInt32(oat_data_end),
1680 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001681 boot_image_begin,
1682 boot_image_end - boot_image_begin,
1683 boot_oat_begin,
1684 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001685 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001686 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001687 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001688 image_storage_mode_,
1689 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001690}
1691
1692ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001693 auto it = native_object_relocations_.find(method);
David Sehr709b0702016-10-13 09:12:37 -07001694 CHECK(it != native_object_relocations_.end()) << ArtMethod::PrettyMethod(method) << " @ "
1695 << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001696 size_t oat_index = GetOatIndex(method->GetDexCache());
1697 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001698 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1699 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001700}
1701
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001702class FixupRootVisitor : public RootVisitor {
1703 public:
1704 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1705 }
1706
1707 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001708 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001709 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001710 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001711 }
1712 }
1713
1714 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1715 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001716 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001717 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001718 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001719 }
1720 }
1721
1722 private:
1723 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001724};
1725
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001726void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
1727 for (size_t i = 0; i < ImTable::kSize; ++i) {
1728 ArtMethod* method = orig->Get(i, target_ptr_size_);
1729 copy->Set(i, NativeLocationInImage(method), target_ptr_size_);
1730 }
1731}
1732
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001733void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
1734 const size_t count = orig->NumEntries(target_ptr_size_);
1735 for (size_t i = 0; i < count; ++i) {
1736 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
1737 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
1738 copy->SetInterfaceMethod(i, target_ptr_size_, NativeLocationInImage(interface_method));
1739 copy->SetImplementationMethod(i,
1740 target_ptr_size_,
1741 NativeLocationInImage(implementation_method));
1742 }
1743}
1744
Vladimir Marko944da602016-02-19 12:27:55 +00001745void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001746 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001747 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001748 for (auto& pair : native_object_relocations_) {
1749 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001750 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001751 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001752 continue;
1753 }
1754 auto* dest = image_info.image_->Begin() + relocation.offset;
1755 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001756 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001757 switch (relocation.type) {
1758 case kNativeObjectRelocationTypeArtField: {
1759 memcpy(dest, pair.first, sizeof(ArtField));
1760 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001761 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass().Ptr()));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001762 break;
1763 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001764 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001765 case kNativeObjectRelocationTypeArtMethodClean:
1766 case kNativeObjectRelocationTypeArtMethodDirty: {
1767 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001768 reinterpret_cast<ArtMethod*>(dest),
1769 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001770 break;
1771 }
1772 // For arrays, copy just the header since the elements will get copied by their corresponding
1773 // relocations.
1774 case kNativeObjectRelocationTypeArtFieldArray: {
1775 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1776 break;
1777 }
1778 case kNativeObjectRelocationTypeArtMethodArrayClean:
1779 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00001780 size_t size = ArtMethod::Size(target_ptr_size_);
1781 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1782 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1783 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1784 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001785 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00001786 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001787 case kNativeObjectRelocationTypeDexCacheArray:
1788 // Nothing to copy here, everything is done in FixupDexCache().
1789 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001790 case kNativeObjectRelocationTypeIMTable: {
1791 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
1792 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
1793 CopyAndFixupImTable(orig_imt, dest_imt);
1794 break;
1795 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001796 case kNativeObjectRelocationTypeIMTConflictTable: {
1797 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
1798 CopyAndFixupImtConflictTable(
1799 orig_table,
1800 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
1801 break;
1802 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001803 }
1804 }
1805 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001806 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001807 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001808 ArtMethod* method = image_methods_[i];
1809 CHECK(method != nullptr);
1810 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001811 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001812 }
1813 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001814 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001815 FixupRootVisitor root_visitor(this);
1816
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001817 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001818 if (image_info.intern_table_bytes_ > 0) {
1819 const ImageSection& intern_table_section = image_header->GetImageSection(
1820 ImageHeader::kSectionInternedStrings);
1821 InternTable* const intern_table = image_info.intern_table_.get();
1822 uint8_t* const intern_table_memory_ptr =
1823 image_info.image_->Begin() + intern_table_section.Offset();
1824 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1825 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1826 // Fixup the pointers in the newly written intern table to contain image addresses.
1827 InternTable temp_intern_table;
1828 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1829 // the VisitRoots() will update the memory directly rather than the copies.
1830 // This also relies on visit roots not doing any verification which could fail after we update
1831 // the roots to be the image addresses.
1832 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1833 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1834 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1835 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001836 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1837 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001838 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001839 const ImageSection& class_table_section = image_header->GetImageSection(
1840 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001841 uint8_t* const class_table_memory_ptr =
1842 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001843 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001844
1845 ClassTable* table = image_info.class_table_.get();
1846 CHECK(table != nullptr);
1847 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1848 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1849 // Fixup the pointers in the newly written class table to contain image addresses. See
1850 // above comment for intern tables.
1851 ClassTable temp_class_table;
1852 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1853 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1854 table->NumZygoteClasses());
1855 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1856 RootInfo(kRootUnknown));
1857 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001858 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001859}
1860
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001861void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001862 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001863 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1864 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001865 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001866 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001867 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1868 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001869 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001870 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001871}
1872
Mathieu Chartier590fee92013-09-13 13:46:47 -07001873void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001874 DCHECK(obj != nullptr);
1875 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001876 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1877}
1878
Mathieu Chartiere401d142015-04-22 13:56:20 -07001879void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1880 mirror::Class* klass, Bin array_type) {
1881 CHECK(klass->IsArrayClass());
David Sehr709b0702016-10-13 09:12:37 -07001882 CHECK(arr->IsIntArray() || arr->IsLongArray()) << klass->PrettyClass() << " " << arr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001883 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001884 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001885 dst->SetClass(GetImageAddress(arr->GetClass()));
1886 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001887 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001888 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1889 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001890 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001891 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001892 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001893 auto* method = reinterpret_cast<ArtMethod*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07001894 LOG(FATAL) << "No relocation entry for ArtMethod " << method->PrettyMethod() << " @ "
1895 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1896 << Class::PrettyClass(method->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001897 } else {
1898 CHECK_EQ(array_type, kBinArtField);
1899 auto* field = reinterpret_cast<ArtField*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07001900 LOG(FATAL) << "No relocation entry for ArtField " << field->PrettyField() << " @ "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001901 << field << " idx=" << i << "/" << num_elements << " with declaring class "
David Sehr709b0702016-10-13 09:12:37 -07001902 << Class::PrettyClass(field->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001903 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001904 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001905 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001906 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001907 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001908 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001909 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001910 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001911 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001912}
1913
1914void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001915 if (IsInBootImage(obj)) {
1916 return;
1917 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001918 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001919 size_t oat_index = GetOatIndex(obj);
1920 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001921 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1922 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001923 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001924
Jeff Haodcdc85b2015-12-04 14:06:18 -08001925 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001926
1927 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001928 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001929 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001930
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001931 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1932 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001933 const auto it = saved_hashcode_map_.find(obj);
1934 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1935 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001936 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
1937 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
1938 // safe since we mark all of the objects that may reference non immune objects as gray.
1939 CHECK(dst->AtomicSetMarkBit(0, 1));
1940 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001941 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001942}
1943
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001944// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001945class FixupVisitor {
1946 public:
1947 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1948 }
1949
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001950 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1951 // with other logic.
1952 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1953 const {}
1954 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1955
1956
Mathieu Chartier31e88222016-10-14 18:43:19 -07001957 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001958 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07001959 ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001960 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1961 // image.
1962 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001963 offset,
Mathieu Chartier31e88222016-10-14 18:43:19 -07001964 image_writer_->GetImageAddress(ref.Ptr()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001965 }
1966
1967 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001968 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1969 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001970 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001971 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001972 mirror::Reference::ReferentOffset(),
1973 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001974 }
1975
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001976 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001977 ImageWriter* const image_writer_;
1978 mirror::Object* const copy_;
1979};
1980
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001981class FixupClassVisitor FINAL : public FixupVisitor {
1982 public:
1983 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1984 }
1985
Mathieu Chartier31e88222016-10-14 18:43:19 -07001986 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001987 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001988 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001989 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001990 }
1991
Mathieu Chartier31e88222016-10-14 18:43:19 -07001992 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1993 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001994 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001995 LOG(FATAL) << "Reference not expected here.";
1996 }
1997};
1998
Vladimir Marko05792b92015-08-03 11:56:49 +01001999uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
2000 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002001 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002002 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002003 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
2004 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002005 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01002006 return relocation.offset;
2007}
2008
2009template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002010std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002011 std::ostringstream oss;
2012 oss << ptr;
2013 return oss.str();
2014}
2015
2016template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002017std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07002018 return ArtMethod::PrettyMethod(method);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002019}
2020
2021template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002022T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002023 if (obj == nullptr || IsInBootImage(obj)) {
2024 return obj;
2025 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002026 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002027 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
2028 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002029 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00002030 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002031 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002032 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002033}
2034
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002035template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08002036T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
2037 if (obj == nullptr || IsInBootImage(obj)) {
2038 return obj;
2039 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002040 size_t oat_index = GetOatIndexForDexCache(dex_cache);
2041 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002042 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
2043 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002044}
2045
2046class NativeLocationVisitor {
2047 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002048 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002049
2050 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002051 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002052 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002053 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002054
2055 private:
2056 ImageWriter* const image_writer_;
2057};
2058
2059void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002060 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002061 FixupClassVisitor visitor(this, copy);
Mathieu Chartier31e88222016-10-14 18:43:19 -07002062 ObjPtr<mirror::Object>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002063
2064 // Remove the clinitThreadId. This is required for image determinism.
2065 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002066}
2067
Ian Rogersef7d42f2014-01-06 12:55:46 -08002068void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002069 DCHECK(orig != nullptr);
2070 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002071 if (kUseBakerOrBrooksReadBarrier) {
2072 orig->AssertReadBarrierPointer();
2073 if (kUseBrooksReadBarrier) {
2074 // Note the address 'copy' isn't the same as the image address of 'orig'.
2075 copy->SetReadBarrierPointer(GetImageAddress(orig));
2076 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
2077 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002078 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002079 auto* klass = orig->GetClass();
2080 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002081 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07002082 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
2083 if (it != pointer_arrays_.end()) {
2084 // Should only need to fixup every pointer array exactly once.
2085 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
2086 pointer_arrays_.erase(it);
2087 return;
2088 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002089 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002090 if (orig->IsClass()) {
2091 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002092 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002093 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
2094 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01002095 auto* dest = down_cast<mirror::Executable*>(copy);
2096 auto* src = down_cast<mirror::Executable*>(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002097 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05002098 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01002099 } else if (!klass->IsArrayClass()) {
2100 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2101 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
2102 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002103 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002104 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002105 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2106 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002107 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002108 // Also set allocator to null to be safe. The allocator is created when we create the class
2109 // table. We also never expect to unload things in the image since they are held live as
2110 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002111 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002112 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002113 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002114 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002115 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002116 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002117}
2118
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002119
2120class ImageAddressVisitor {
2121 public:
2122 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
2123
2124 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002125 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002126 return image_writer_->GetImageAddress(ptr);
2127 }
2128
2129 private:
2130 ImageWriter* const image_writer_;
2131};
2132
2133
Vladimir Marko05792b92015-08-03 11:56:49 +01002134void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2135 mirror::DexCache* copy_dex_cache) {
2136 // Though the DexCache array fields are usually treated as native pointers, we set the full
2137 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2138 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2139 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002140 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002141 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002142 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002143 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002144 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002145 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
2146 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002147 }
2148 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
2149 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002150 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002151 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002152 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002153 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
2154 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002155 }
2156 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
2157 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002158 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002159 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002160 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002161 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002162 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
2163 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002164 // NativeLocationInImage also handles runtime methods since these have relocation info.
2165 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002166 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
2167 }
2168 }
2169 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
2170 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002171 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002172 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002173 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002174 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002175 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
2176 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002177 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002178 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
2179 }
2180 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01002181 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
2182 if (orig_method_types != nullptr) {
2183 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodTypesOffset(),
2184 NativeLocationInImage(orig_method_types),
2185 PointerSize::k64);
2186 orig_dex_cache->FixupResolvedMethodTypes(NativeCopyLocation(orig_method_types, orig_dex_cache),
2187 ImageAddressVisitor(this));
2188 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002189
2190 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2191 // compiler pointers in here will make the output non-deterministic.
2192 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002193}
2194
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002195const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2196 DCHECK_LT(type, kOatAddressCount);
2197 // If we are compiling an app image, we need to use the stubs of the boot image.
2198 if (compile_app_image_) {
2199 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002200 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002201 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2202 DCHECK(!image_spaces.empty());
2203 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002204 CHECK(oat_file != nullptr);
2205 const OatHeader& header = oat_file->GetOatHeader();
2206 switch (type) {
2207 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2208 case kOatAddressQuickGenericJNITrampoline:
2209 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2210 case kOatAddressInterpreterToInterpreterBridge:
2211 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2212 case kOatAddressInterpreterToCompiledCodeBridge:
2213 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2214 case kOatAddressJNIDlsymLookup:
2215 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2216 case kOatAddressQuickIMTConflictTrampoline:
2217 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2218 case kOatAddressQuickResolutionTrampoline:
2219 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2220 case kOatAddressQuickToInterpreterBridge:
2221 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2222 default:
2223 UNREACHABLE();
2224 }
2225 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002226 const ImageInfo& primary_image_info = GetImageInfo(0);
2227 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002228}
2229
Jeff Haodcdc85b2015-12-04 14:06:18 -08002230const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2231 const ImageInfo& image_info,
2232 bool* quick_is_interpreted) {
David Sehr709b0702016-10-13 09:12:37 -07002233 DCHECK(!method->IsResolutionMethod()) << method->PrettyMethod();
2234 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << method->PrettyMethod();
2235 DCHECK(!method->IsImtUnimplementedMethod()) << method->PrettyMethod();
2236 DCHECK(method->IsInvokable()) << method->PrettyMethod();
2237 DCHECK(!IsInBootImage(method)) << method->PrettyMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002238
2239 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2240 // trampoline.
2241
2242 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002243 const void* quick_oat_entry_point =
2244 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2245 const uint8_t* quick_code;
2246
2247 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2248 DCHECK(method->IsCopied());
2249 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2250 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2251 } else {
2252 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2253 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2254 }
2255
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002256 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002257 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2258 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002259 // We have code for a non-static or initialized method, just use the code.
2260 } else if (quick_code == nullptr && method->IsNative() &&
2261 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2262 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002263 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002264 } else if (quick_code == nullptr && !method->IsNative()) {
2265 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002266 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002267 *quick_is_interpreted = true;
2268 } else {
2269 CHECK(!method->GetDeclaringClass()->IsInitialized());
2270 // We have code for a static method, but need to go through the resolution stub for class
2271 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002272 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2273 }
2274 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002275 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002276 }
2277 return quick_code;
2278}
2279
Jeff Haodcdc85b2015-12-04 14:06:18 -08002280void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2281 ArtMethod* copy,
2282 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002283 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002284
2285 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002286 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002287 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002288 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002289 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002290
Ian Rogers848871b2013-08-05 10:56:33 -07002291 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2292 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002293
Ian Rogers848871b2013-08-05 10:56:33 -07002294 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002295 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002296 if (orig->IsRuntimeMethod()) {
2297 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2298 if (orig_table != nullptr) {
2299 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2300 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2301 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2302 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2303 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2304 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2305 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2306 } else {
2307 bool found_one = false;
2308 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2309 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2310 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2311 found_one = true;
2312 break;
2313 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002314 }
David Sehr709b0702016-10-13 09:12:37 -07002315 CHECK(found_one) << "Expected to find callee save method but got " << orig->PrettyMethod();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002316 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002317 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002318 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002319 // We assume all methods have code. If they don't currently then we set them to the use the
2320 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2321 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002322 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002323 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002324 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002325 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002326 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002327 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002328 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002329
Sebastien Hertze1d07812014-05-21 15:44:09 +02002330 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002331 if (orig->IsNative()) {
2332 // The native method's pointer is set to a stub to lookup via dlsym.
2333 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002334 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002335 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002336 }
2337 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002338 }
2339}
2340
Jeff Haodcdc85b2015-12-04 14:06:18 -08002341size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002342 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002343 return std::accumulate(&image_info.bin_slot_sizes_[0],
2344 &image_info.bin_slot_sizes_[up_to],
2345 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002346}
2347
2348ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2349 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002350 static_assert(kBinBits == 3, "wrong number of bin bits");
2351 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002352 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2353
2354 DCHECK_LT(GetBin(), kBinSize);
2355 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2356}
2357
2358ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2359 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2360 DCHECK_EQ(index, GetIndex());
2361}
2362
2363ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2364 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2365}
2366
2367uint32_t ImageWriter::BinSlot::GetIndex() const {
2368 return lockword_ & ~kBinMask;
2369}
2370
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002371ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2372 switch (type) {
2373 case kNativeObjectRelocationTypeArtField:
2374 case kNativeObjectRelocationTypeArtFieldArray:
2375 return kBinArtField;
2376 case kNativeObjectRelocationTypeArtMethodClean:
2377 case kNativeObjectRelocationTypeArtMethodArrayClean:
2378 return kBinArtMethodClean;
2379 case kNativeObjectRelocationTypeArtMethodDirty:
2380 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2381 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002382 case kNativeObjectRelocationTypeDexCacheArray:
2383 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002384 case kNativeObjectRelocationTypeRuntimeMethod:
2385 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002386 case kNativeObjectRelocationTypeIMTable:
2387 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002388 case kNativeObjectRelocationTypeIMTConflictTable:
2389 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002390 }
2391 UNREACHABLE();
2392}
2393
Vladimir Marko944da602016-02-19 12:27:55 +00002394size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002395 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002396 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002397 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002398 auto it = oat_index_map_.find(obj);
2399 DCHECK(it != oat_index_map_.end());
2400 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002401}
2402
Vladimir Marko944da602016-02-19 12:27:55 +00002403size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002404 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002405 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002406 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002407 auto it = dex_file_oat_index_map_.find(dex_file);
2408 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2409 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002410}
2411
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002412size_t ImageWriter::GetOatIndexForDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
2413 return (dex_cache == nullptr)
2414 ? GetDefaultOatIndex()
2415 : GetOatIndexForDexFile(dex_cache->GetDexFile());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002416}
2417
Vladimir Marko944da602016-02-19 12:27:55 +00002418void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2419 size_t oat_loaded_size,
2420 size_t oat_data_offset,
2421 size_t oat_data_size) {
2422 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2423 for (const ImageInfo& info : image_infos_) {
2424 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2425 }
2426 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002427
Vladimir Marko944da602016-02-19 12:27:55 +00002428 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2429 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2430 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2431 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2432 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002433
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002434 if (compile_app_image_) {
2435 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2436 return;
2437 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002438
2439 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002440 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002441 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002442 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002443 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2444 }
2445}
2446
Vladimir Marko944da602016-02-19 12:27:55 +00002447void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2448 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2449 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2450
2451 if (oat_index == GetDefaultOatIndex()) {
2452 // Primary oat file, read the trampolines.
2453 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2454 oat_header.GetInterpreterToInterpreterBridgeOffset();
2455 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2456 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2457 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2458 oat_header.GetJniDlsymLookupOffset();
2459 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2460 oat_header.GetQuickGenericJniTrampolineOffset();
2461 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2462 oat_header.GetQuickImtConflictTrampolineOffset();
2463 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2464 oat_header.GetQuickResolutionTrampolineOffset();
2465 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2466 oat_header.GetQuickToInterpreterBridgeOffset();
2467 }
2468}
2469
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002470ImageWriter::ImageWriter(
2471 const CompilerDriver& compiler_driver,
2472 uintptr_t image_begin,
2473 bool compile_pic,
2474 bool compile_app_image,
2475 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002476 const std::vector<const char*>& oat_filenames,
2477 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002478 : compiler_driver_(compiler_driver),
2479 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2480 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002481 compile_pic_(compile_pic),
2482 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002483 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002484 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002485 dirty_methods_(0u),
2486 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002487 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002488 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002489 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002490 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002491 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002492 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2493 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002494}
2495
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002496ImageWriter::ImageInfo::ImageInfo()
2497 : intern_table_(new InternTable),
2498 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002499
Brian Carlstrom7940e442013-07-12 13:46:57 -07002500} // namespace art