blob: a37bf4b9fe485f05bf50957ea59cbd108023e735 [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"
Alex Lightd6251582016-10-31 11:12:30 -070054#include "mirror/class_ext.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "mirror/class_loader.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070056#include "mirror/dex_cache.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070057#include "mirror/dex_cache-inl.h"
Neil Fuller0e844392016-09-08 13:43:31 +010058#include "mirror/executable.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070059#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "mirror/object-inl.h"
61#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070062#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063#include "oat.h"
64#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070065#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070067#include "scoped_thread_state_change-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070068#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000069#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070070
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070071using ::art::mirror::Class;
72using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070073using ::art::mirror::Object;
74using ::art::mirror::ObjectArray;
75using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070076
77namespace art {
78
Igor Murashkinf5b4c502014-11-14 15:01:59 -080079// Separate objects into multiple bins to optimize dirty memory use.
80static constexpr bool kBinObjects = true;
81
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080082// Return true if an object is already in an image space.
83bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080084 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080085 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080086 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080087 return false;
88 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080089 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
90 const uint8_t* image_begin = boot_image_space->Begin();
91 // Real image end including ArtMethods and ArtField sections.
92 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
93 if (image_begin <= obj && obj < image_end) {
94 return true;
95 }
96 }
97 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080098}
99
100bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800101 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800102 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800103 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800104 return false;
105 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800106 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
107 const ImageHeader& image_header = boot_image_space->GetImageHeader();
108 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
109 return true;
110 }
111 }
112 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800113}
114
Andreas Gampedd9d0552015-03-09 12:57:41 -0700115static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700116 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700117 Class* klass = obj->GetClass();
David Sehr709b0702016-10-13 09:12:37 -0700118 CHECK_NE(Class::PrettyClass(klass), "com.android.dex.Dex");
Andreas Gampedd9d0552015-03-09 12:57:41 -0700119}
120
121static void CheckNoDexObjects() {
122 ScopedObjectAccess soa(Thread::Current());
123 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
124}
125
Vladimir Markof4da6752014-08-01 19:04:18 +0100126bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800127 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800128 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100129 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700130 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100131 PruneNonImageClasses(); // Remove junk
Mathieu Chartier901e0702016-02-19 13:42:48 -0800132 if (!compile_app_image_) {
133 // Avoid for app image since this may increase RAM and image size.
134 ComputeLazyFieldsForImageClasses(); // Add useful information
135 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100136 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100137 heap->CollectGarbage(false); // Remove garbage.
138
Andreas Gampedd9d0552015-03-09 12:57:41 -0700139 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
140 // dex files.
141 //
142 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
143 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
144 // true.
145 if (kIsDebugBuild) {
146 CheckNoDexObjects();
147 }
148
Vladimir Markof4da6752014-08-01 19:04:18 +0100149 if (kIsDebugBuild) {
150 ScopedObjectAccess soa(Thread::Current());
151 CheckNonImageClassesRemoved();
152 }
153
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700154 {
155 ScopedObjectAccess soa(Thread::Current());
156 CalculateNewObjectOffsets();
157 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100158
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700159 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
160 // bin size sums being calculated.
161 if (!AllocMemory()) {
162 return false;
163 }
164
Vladimir Markof4da6752014-08-01 19:04:18 +0100165 return true;
166}
167
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700168bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800169 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000170 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800171 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
172 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800173 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800174 if (image_fd != kInvalidFd) {
175 CHECK_EQ(image_filenames.size(), 1u);
176 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800177 CHECK(!oat_filenames.empty());
178 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179
Vladimir Marko944da602016-02-19 12:27:55 +0000180 {
181 ScopedObjectAccess soa(Thread::Current());
182 for (size_t i = 0; i < oat_filenames.size(); ++i) {
183 CreateHeader(i);
184 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800185 }
186 }
Alex Light53cb16b2014-06-12 11:26:29 -0700187
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700188 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700189 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800190 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700191 Runtime::Current()->GetHeap()->DisableObjectValidation();
192 CopyAndFixupObjects();
193 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700194
Jeff Haodcdc85b2015-12-04 14:06:18 -0800195 for (size_t i = 0; i < image_filenames.size(); ++i) {
196 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000197 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800198 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800199 if (image_fd != kInvalidFd) {
200 if (strlen(image_filename) == 0u) {
201 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800202 // Empty the file in case it already exists.
203 if (image_file != nullptr) {
204 TEMP_FAILURE_RETRY(image_file->SetLength(0));
205 TEMP_FAILURE_RETRY(image_file->Flush());
206 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800207 } else {
208 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
209 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800210 } else {
211 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800212 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800213
Jeff Haodcdc85b2015-12-04 14:06:18 -0800214 if (image_file == nullptr) {
215 LOG(ERROR) << "Failed to open image file " << image_filename;
216 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800217 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800218
219 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800220 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
221 image_file->Erase();
222 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800223 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800224
Jeff Haodcdc85b2015-12-04 14:06:18 -0800225 std::unique_ptr<char[]> compressed_data;
226 // Image data size excludes the bitmap and the header.
227 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
228 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
229 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
230 size_t data_size;
231 const char* image_data_to_write;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800232 const uint64_t compress_start_time = NanoTime();
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000233
Jeff Haodcdc85b2015-12-04 14:06:18 -0800234 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
235 switch (image_storage_mode_) {
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700236 case ImageHeader::kStorageModeLZ4HC: // Fall-through.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800237 case ImageHeader::kStorageModeLZ4: {
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800238 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800239 compressed_data.reset(new char[compressed_max_size]);
240 data_size = LZ4_compress(
241 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
242 &compressed_data[0],
243 image_data_size);
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800244
245 break;
246 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700247 /*
248 * Disabled due to image_test64 flakyness. Both use same decompression. b/27560444
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800249 case ImageHeader::kStorageModeLZ4HC: {
250 // Bound is same as non HC.
251 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
252 compressed_data.reset(new char[compressed_max_size]);
253 data_size = LZ4_compressHC(
254 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
255 &compressed_data[0],
256 image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800257 break;
258 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700259 */
Jeff Haodcdc85b2015-12-04 14:06:18 -0800260 case ImageHeader::kStorageModeUncompressed: {
261 data_size = image_data_size;
262 image_data_to_write = image_data;
263 break;
264 }
265 default: {
266 LOG(FATAL) << "Unsupported";
267 UNREACHABLE();
268 }
269 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800270
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800271 if (compressed_data != nullptr) {
272 image_data_to_write = &compressed_data[0];
273 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
274 << PrettyDuration(NanoTime() - compress_start_time);
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700275 if (kIsDebugBuild) {
276 std::unique_ptr<uint8_t[]> temp(new uint8_t[image_data_size]);
277 const size_t decompressed_size = LZ4_decompress_safe(
278 reinterpret_cast<char*>(&compressed_data[0]),
279 reinterpret_cast<char*>(&temp[0]),
280 data_size,
281 image_data_size);
282 CHECK_EQ(decompressed_size, image_data_size);
283 CHECK_EQ(memcmp(image_data, &temp[0], image_data_size), 0) << image_storage_mode_;
284 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800285 }
286
Jeff Haodcdc85b2015-12-04 14:06:18 -0800287 // Write out the image + fields + methods.
288 const bool is_compressed = compressed_data != nullptr;
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800289 if (!image_file->PwriteFully(image_data_to_write, data_size, sizeof(ImageHeader))) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800290 PLOG(ERROR) << "Failed to write image file data " << image_filename;
291 image_file->Erase();
292 return false;
293 }
294
295 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
296 // convenience.
297 const ImageSection& bitmap_section = image_header->GetImageSection(
298 ImageHeader::kSectionImageBitmap);
299 // Align up since data size may be unaligned if the image is compressed.
300 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
301 if (!is_compressed) {
302 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
303 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800304 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
305 bitmap_section.Size(),
306 bitmap_position_in_file)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800307 PLOG(ERROR) << "Failed to write image file " << image_filename;
308 image_file->Erase();
309 return false;
310 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800311
312 int err = image_file->Flush();
313 if (err < 0) {
314 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
315 image_file->Erase();
316 return false;
317 }
318
319 // Write header last in case the compiler gets killed in the middle of image writing.
320 // We do not want to have a corrupted image with a valid header.
321 // The header is uncompressed since it contains whether the image is compressed or not.
322 image_header->data_size_ = data_size;
323 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
324 sizeof(ImageHeader),
325 0)) {
326 PLOG(ERROR) << "Failed to write image file header " << image_filename;
327 image_file->Erase();
328 return false;
329 }
330
Jeff Haodcdc85b2015-12-04 14:06:18 -0800331 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
332 static_cast<size_t>(image_file->GetLength()));
333 if (image_file->FlushCloseOrErase() != 0) {
334 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
335 return false;
336 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800337 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700338 return true;
339}
340
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700341void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700342 DCHECK(object != nullptr);
343 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800344
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800345 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700346 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700347 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700348 DCHECK(IsImageOffsetAssigned(object));
349}
350
Mathieu Chartiere401d142015-04-22 13:56:20 -0700351void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
352 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
353 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
354 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
355}
356
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800357void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700358 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800359 DCHECK_NE(image_objects_offset_begin_, 0u);
360
Vladimir Marko944da602016-02-19 12:27:55 +0000361 size_t oat_index = GetOatIndex(object);
362 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800363 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100364 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800365 DCHECK_ALIGNED(new_offset, kObjectAlignment);
366
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700367 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800368 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700369}
370
Ian Rogersef7d42f2014-01-06 12:55:46 -0800371bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800372 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700373 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700374 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700375}
376
Ian Rogersef7d42f2014-01-06 12:55:46 -0800377size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700378 DCHECK(object != nullptr);
379 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700380 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700381 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000382 size_t oat_index = GetOatIndex(object);
383 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800384 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700385 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700386}
387
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800388void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
389 DCHECK(object != nullptr);
390 DCHECK(!IsImageOffsetAssigned(object));
391 DCHECK(!IsImageBinSlotAssigned(object));
392
393 // Before we stomp over the lock word, save the hash code for later.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800394 LockWord lw(object->GetLockWord(false));
395 switch (lw.GetState()) {
396 case LockWord::kFatLocked: {
397 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
398 break;
399 }
400 case LockWord::kThinLocked: {
401 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
402 break;
403 }
404 case LockWord::kUnlocked:
405 // No hash, don't need to save it.
406 break;
407 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700408 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
409 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800410 break;
411 default:
412 LOG(FATAL) << "Unreachable.";
413 UNREACHABLE();
414 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700415 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700416 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800417 DCHECK(IsImageBinSlotAssigned(object));
418}
419
Vladimir Marko20f85592015-03-19 10:07:02 +0000420void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000421 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000422 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
423 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800424 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000425 auto it = dex_file_oat_index_map_.find(dex_file);
426 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800427 ImageInfo& image_info = GetImageInfo(it->second);
428 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
429 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
430 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
431 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000432
Vladimir Marko20f85592015-03-19 10:07:02 +0000433 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700434 Thread* const self = Thread::Current();
435 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800436 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700437 ObjPtr<mirror::DexCache> dex_cache =
438 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
439 if (dex_cache == nullptr || IsInBootImage(dex_cache.Ptr())) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700440 continue;
441 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000442 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartier0b490842016-05-25 15:05:59 -0700443 CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
444 << "Dex cache should have been pruned " << dex_file->GetLocation()
445 << "; possibly in class path";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700446 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000447 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000448 size_t oat_index = GetOatIndexForDexCache(dex_cache);
449 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800450 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100451 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800452 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
453 start + layout.TypesOffset(),
454 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100455 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800456 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
457 start + layout.MethodsOffset(),
458 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100459 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800460 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
461 start + layout.FieldsOffset(),
462 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100463 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800464 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Narayan Kamath7fe56582016-10-14 18:49:12 +0100465
466 if (dex_cache->GetResolvedMethodTypes() != nullptr) {
467 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethodTypes(),
468 start + layout.MethodTypesOffset(),
469 dex_cache);
470 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000471 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000472}
473
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700474void ImageWriter::AddDexCacheArrayRelocation(void* array,
475 size_t offset,
476 ObjPtr<mirror::DexCache> dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100477 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800478 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000479 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800480 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000481 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100482 }
483}
484
Mathieu Chartiere401d142015-04-22 13:56:20 -0700485void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
486 DCHECK(arr != nullptr);
487 if (kIsDebugBuild) {
488 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800489 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700490 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800491 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800492 CHECK(klass == nullptr || KeepClass(klass))
David Sehr709b0702016-10-13 09:12:37 -0700493 << Class::PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700494 }
495 }
496 }
497 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
498 // ArtMethods.
499 pointer_arrays_.emplace(arr, kBinArtMethodClean);
500}
501
Mathieu Chartier496577f2016-09-20 15:33:31 -0700502void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800503 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800504 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800505
506 // The magic happens here. We segregate objects into different bins based
507 // on how likely they are to get dirty at runtime.
508 //
509 // Likely-to-dirty objects get packed together into the same bin so that
510 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
511 // maximized.
512 //
513 // This means more pages will stay either clean or shared dirty (with zygote) and
514 // the app will use less of its own (private) memory.
515 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000516 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800517
518 if (kBinObjects) {
519 //
520 // Changing the bin of an object is purely a memory-use tuning.
521 // It has no change on runtime correctness.
522 //
523 // Memory analysis has determined that the following types of objects get dirtied
524 // the most:
525 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000526 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
527 // a fixed layout which helps improve generated code (using PC-relative addressing),
528 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
529 // Since these arrays are huge, most pages do not overlap other objects and it's not
530 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100531 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800532 // * Class'es which are verified [their clinit runs only at runtime]
533 // - classes in general [because their static fields get overwritten]
534 // - initialized classes with all-final statics are unlikely to be ever dirty,
535 // so bin them separately
536 // * Art Methods that are:
537 // - native [their native entry point is not looked up until runtime]
538 // - have declaring classes that aren't initialized
539 // [their interpreter/quick entry points are trampolines until the class
540 // becomes initialized]
541 //
542 // We also assume the following objects get dirtied either never or extremely rarely:
543 // * Strings (they are immutable)
544 // * Art methods that aren't native and have initialized declared classes
545 //
546 // We assume that "regular" bin objects are highly unlikely to become dirtied,
547 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
548 //
549 if (object->IsClass()) {
550 bin = kBinClassVerified;
551 mirror::Class* klass = object->AsClass();
552
Mathieu Chartiere401d142015-04-22 13:56:20 -0700553 // Add non-embedded vtable to the pointer array table if there is one.
554 auto* vtable = klass->GetVTable();
555 if (vtable != nullptr) {
556 AddMethodPointerArray(vtable);
557 }
558 auto* iftable = klass->GetIfTable();
559 if (iftable != nullptr) {
560 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
561 if (iftable->GetMethodArrayCount(i) > 0) {
562 AddMethodPointerArray(iftable->GetMethodArray(i));
563 }
564 }
565 }
566
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800567 if (klass->GetStatus() == Class::kStatusInitialized) {
568 bin = kBinClassInitialized;
569
570 // If the class's static fields are all final, put it into a separate bin
571 // since it's very likely it will stay clean.
572 uint32_t num_static_fields = klass->NumStaticFields();
573 if (num_static_fields == 0) {
574 bin = kBinClassInitializedFinalStatics;
575 } else {
576 // Maybe all the statics are final?
577 bool all_final = true;
578 for (uint32_t i = 0; i < num_static_fields; ++i) {
579 ArtField* field = klass->GetStaticField(i);
580 if (!field->IsFinal()) {
581 all_final = false;
582 break;
583 }
584 }
585
586 if (all_final) {
587 bin = kBinClassInitializedFinalStatics;
588 }
589 }
590 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800591 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
592 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700593 } else if (object->GetClass<kVerifyNone>() ==
594 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
595 // Instance of java lang object, probably a lock object. This means it will be dirty when we
596 // synchronize on it.
597 bin = kBinMiscDirty;
598 } else if (object->IsDexCache()) {
599 // Dex file field becomes dirty when the image is loaded.
600 bin = kBinMiscDirty;
601 }
602 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800603 }
604
Mathieu Chartier496577f2016-09-20 15:33:31 -0700605 // Assign the oat index too.
606 DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
607 oat_index_map_.emplace(object, oat_index);
608
Vladimir Marko944da602016-02-19 12:27:55 +0000609 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800610
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800611 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800612 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
613 // Move the current bin size up to accommodate the object we just assigned a bin slot.
614 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800615
616 BinSlot new_bin_slot(bin, current_offset);
617 SetImageBinSlot(object, new_bin_slot);
618
Jeff Haodcdc85b2015-12-04 14:06:18 -0800619 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800620
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800621 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800622 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800623}
624
Mathieu Chartiere401d142015-04-22 13:56:20 -0700625bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
626 if (m->IsNative()) {
627 return true;
628 }
629 mirror::Class* declaring_class = m->GetDeclaringClass();
630 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
631 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
632}
633
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800634bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
635 DCHECK(object != nullptr);
636
637 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
638 // If it's in some other state, then we haven't yet assigned an image bin slot.
639 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
640 return false;
641 } else if (kIsDebugBuild) {
642 LockWord lock_word = object->GetLockWord(false);
643 size_t offset = lock_word.ForwardingAddress();
644 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000645 size_t oat_index = GetOatIndex(object);
646 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800647 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800648 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800649 }
650 return true;
651}
652
653ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
654 DCHECK(object != nullptr);
655 DCHECK(IsImageBinSlotAssigned(object));
656
657 LockWord lock_word = object->GetLockWord(false);
658 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
659 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
660
661 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000662 size_t oat_index = GetOatIndex(object);
663 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800664 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800665
666 return bin_slot;
667}
668
Brian Carlstrom7940e442013-07-12 13:46:57 -0700669bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000670 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800671 ImageSection unused_sections[ImageHeader::kSectionCount];
672 const size_t length = RoundUp(
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700673 image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800674
Jeff Haodcdc85b2015-12-04 14:06:18 -0800675 std::string error_msg;
676 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
677 nullptr,
678 length,
679 PROT_READ | PROT_WRITE,
680 false,
681 false,
682 &error_msg));
683 if (UNLIKELY(image_info.image_.get() == nullptr)) {
684 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
685 return false;
686 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700687
Jeff Haodcdc85b2015-12-04 14:06:18 -0800688 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
689 CHECK_LE(image_info.image_end_, length);
690 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
691 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
692 if (image_info.image_bitmap_.get() == nullptr) {
693 LOG(ERROR) << "Failed to allocate memory for image bitmap";
694 return false;
695 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700696 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700697 return true;
698}
699
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700700class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
701 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700702 bool operator()(ObjPtr<Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700703 StackHandleScope<1> hs(Thread::Current());
704 mirror::Class::ComputeName(hs.NewHandle(c));
705 return true;
706 }
707};
708
Brian Carlstrom7940e442013-07-12 13:46:57 -0700709void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700710 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700711 ComputeLazyFieldsForClassesVisitor visitor;
712 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700713}
714
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700715static bool IsBootClassLoaderClass(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800716 return klass->GetClassLoader() == nullptr;
717}
718
719bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
720 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
721}
722
Mathieu Chartier901e0702016-02-19 13:42:48 -0800723bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800724 bool early_exit = false;
725 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800726 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800727}
728
Mathieu Chartier901e0702016-02-19 13:42:48 -0800729bool ImageWriter::PruneAppImageClassInternal(
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800730 mirror::Class* klass,
731 bool* early_exit,
732 std::unordered_set<mirror::Class*>* visited) {
733 DCHECK(early_exit != nullptr);
734 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800735 DCHECK(compile_app_image_);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800736 if (klass == nullptr || IsInBootImage(klass)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700737 return false;
738 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800739 auto found = prune_class_memo_.find(klass);
740 if (found != prune_class_memo_.end()) {
741 // Already computed, return the found value.
742 return found->second;
743 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800744 // Circular dependencies, return false but do not store the result in the memoization table.
745 if (visited->find(klass) != visited->end()) {
746 *early_exit = true;
747 return false;
748 }
749 visited->emplace(klass);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800750 bool result = IsBootClassLoaderClass(klass);
751 std::string temp;
752 // Prune if not an image class, this handles any broken sets of image classes such as having a
753 // class in the set but not it's superclass.
754 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800755 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800756 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
757 // app image.
758 if (klass->GetStatus() == mirror::Class::kStatusError) {
759 result = true;
760 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700761 ObjPtr<mirror::ClassExt> ext(klass->GetExtData());
762 CHECK(ext.IsNull() || ext->GetVerifyError() == nullptr) << klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800763 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800764 if (!result) {
765 // Check interfaces since these wont be visited through VisitReferences.)
766 mirror::IfTable* if_table = klass->GetIfTable();
767 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800768 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
769 &my_early_exit,
770 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800771 }
772 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800773 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800774 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
775 &my_early_exit,
776 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800777 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800778 // Check static fields and their classes.
779 size_t num_static_fields = klass->NumReferenceStaticFields();
780 if (num_static_fields != 0 && klass->IsResolved()) {
781 // Presumably GC can happen when we are cross compiling, it should not cause performance
782 // problems to do pointer size logic.
783 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
784 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
785 for (size_t i = 0u; i < num_static_fields; ++i) {
786 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
787 if (ref != nullptr) {
788 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800789 result = result || PruneAppImageClassInternal(ref->AsClass(),
790 &my_early_exit,
791 visited);
792 } else {
793 result = result || PruneAppImageClassInternal(ref->GetClass(),
794 &my_early_exit,
795 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800796 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800797 }
798 field_offset = MemberOffset(field_offset.Uint32Value() +
799 sizeof(mirror::HeapReference<mirror::Object>));
800 }
801 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800802 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
803 &my_early_exit,
804 visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800805 // Erase the element we stored earlier since we are exiting the function.
806 auto it = visited->find(klass);
807 DCHECK(it != visited->end());
808 visited->erase(it);
809 // Only store result if it is true or none of the calls early exited due to circular
810 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
811 // a child call and we can remember the result.
812 if (result == true || !my_early_exit || visited->empty()) {
813 prune_class_memo_[klass] = result;
814 }
815 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800816 return result;
817}
818
819bool ImageWriter::KeepClass(Class* klass) {
820 if (klass == nullptr) {
821 return false;
822 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800823 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
824 // Already in boot image, return true.
825 return true;
826 }
827 std::string temp;
828 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
829 return false;
830 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800831 if (compile_app_image_) {
832 // For app images, we need to prune boot loader classes that are not in the boot image since
833 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800834 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800835 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800836 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800837 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700838}
839
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700840class NonImageClassesVisitor : public ClassVisitor {
841 public:
842 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
843
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700844 bool operator()(ObjPtr<Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
845 if (!image_writer_->KeepClass(klass.Ptr())) {
846 classes_to_prune_.insert(klass.Ptr());
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700847 }
848 return true;
849 }
850
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800851 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700852 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700853};
854
855void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700856 Runtime* runtime = Runtime::Current();
857 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700858 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700859
Mathieu Chartier696632e2016-06-03 17:47:32 -0700860 // Clear class table strong roots so that dex caches can get pruned. We require pruning the class
861 // path dex caches.
862 class_linker->ClearClassTableStrongRoots();
863
Brian Carlstrom7940e442013-07-12 13:46:57 -0700864 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700865 NonImageClassesVisitor visitor(this);
866 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700867
868 // Remove the undesired classes from the class roots.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800869 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800870 for (mirror::Class* klass : visitor.classes_to_prune_) {
871 std::string temp;
872 const char* name = klass->GetDescriptor(&temp);
873 VLOG(compiler) << "Pruning class " << name;
874 if (!compile_app_image_) {
875 DCHECK(IsBootClassLoaderClass(klass));
876 }
877 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800878 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700879 }
880
881 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100882 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700883
Mathieu Chartier268764d2016-09-13 12:09:38 -0700884 ScopedAssertNoThreadSuspension sa(__FUNCTION__);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700885 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
886 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800887 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800888 if (self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700889 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700890 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700891 ObjPtr<mirror::DexCache> dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700892 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
893 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800894 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700895 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700896 }
897 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100898 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
899 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
900 ArtMethod* method =
901 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800902 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
903 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800904 // 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 -0800905 // declaring class which is an image class. Set it to the resolution method to be safe and
906 // prevent dangling pointers.
Alex Light36121492016-02-22 13:43:29 -0800907 if (method->IsCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800908 mirror::DexCache::SetElementPtrSize(resolved_methods,
909 i,
910 resolution_method,
911 target_ptr_size_);
912 } else {
913 // Check that the class is still in the classes table.
914 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
David Sehr709b0702016-10-13 09:12:37 -0700915 << Class::PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700916 }
917 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800918 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700919 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800920 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700921 if (field != nullptr && !KeepClass(field->GetDeclaringClass().Ptr())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700922 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700923 }
924 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700925 // Clean the dex field. It might have been populated during the initialization phase, but
926 // contains data only valid during a real run.
927 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700928 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700929
930 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
931 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800932
933 // Clear to save RAM.
934 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700935}
936
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800937void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700938 if (compiler_driver_.GetImageClasses() != nullptr) {
939 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700940 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700941 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700942}
943
944void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
945 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800946 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700947 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800948 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700949 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700950 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800951 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
David Sehr709b0702016-10-13 09:12:37 -0700952 << " " << klass->PrettyDescriptor();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700953 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700954 }
955}
956
957void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700958 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700959 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700960 for (const std::string& image_class : *image_classes) {
961 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700962 }
963}
964
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800965mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
966 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +0000967 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartier9e868092016-10-31 14:58:04 -0700968 ObjPtr<mirror::String> const found = image_info.intern_table_->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800969 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
970 << string->ToModifiedUtf8();
971 if (found != nullptr) {
Mathieu Chartier9e868092016-10-31 14:58:04 -0700972 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800973 }
974 }
975 if (compile_app_image_) {
976 Runtime* const runtime = Runtime::Current();
Mathieu Chartier9e868092016-10-31 14:58:04 -0700977 ObjPtr<mirror::String> found = runtime->GetInternTable()->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800978 // If we found it in the runtime intern table it could either be in the boot image or interned
979 // during app image compilation. If it was in the boot image return that, otherwise return null
980 // since it belongs to another image space.
Mathieu Chartier9e868092016-10-31 14:58:04 -0700981 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found.Ptr())) {
982 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800983 }
984 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
985 << string->ToModifiedUtf8();
986 }
987 return nullptr;
988}
989
Brian Carlstrom7940e442013-07-12 13:46:57 -0700990
Vladimir Marko944da602016-02-19 12:27:55 +0000991ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700992 Runtime* runtime = Runtime::Current();
993 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700994 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700995 StackHandleScope<3> hs(self);
996 Handle<Class> object_array_class(hs.NewHandle(
997 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700998
Jeff Haodcdc85b2015-12-04 14:06:18 -0800999 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +00001000 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001001 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +00001002 size_t image_oat_index = pair.second;
1003 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001004 image_dex_files.insert(image_dex_file);
1005 }
1006 }
1007
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001008 // build an Object[] of all the DexCaches used in the source_space_.
1009 // Since we can't hold the dex lock when allocating the dex_caches
1010 // ObjectArray, we lock the dex lock twice, first to get the number
1011 // of dex caches first and then lock it again to copy the dex
1012 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001013 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001014 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001015 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001016 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001017 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001018 ObjPtr<mirror::DexCache> dex_cache =
1019 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001020 if (dex_cache == nullptr) {
1021 continue;
1022 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001023 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001024 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001025 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1026 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001027 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001028 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001029 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001030 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001031 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1032 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001033 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001034 size_t non_image_dex_caches = 0;
1035 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001036 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001037 ObjPtr<mirror::DexCache> dex_cache =
1038 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001039 if (dex_cache == nullptr) {
1040 continue;
1041 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001042 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001043 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001044 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1045 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001046 }
1047 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1048 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001049 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001050 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001051 ObjPtr<mirror::DexCache> dex_cache =
1052 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001053 if (dex_cache == nullptr) {
1054 continue;
1055 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001056 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001057 if (!IsInBootImage(dex_cache.Ptr()) &&
1058 image_dex_files.find(dex_file) != image_dex_files.end()) {
1059 dex_caches->Set<false>(i, dex_cache.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001060 ++i;
1061 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001062 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001063 }
1064
1065 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001066 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001067 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001068 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001069 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001070 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001071 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001072 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001073 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001074}
1075
Mathieu Chartier496577f2016-09-20 15:33:31 -07001076mirror::Object* ImageWriter::TryAssignBinSlot(WorkStack& work_stack,
1077 mirror::Object* obj,
1078 size_t oat_index) {
1079 if (obj == nullptr || IsInBootImage(obj)) {
1080 // Object is null or already in the image, there is no work to do.
1081 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001082 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001083 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001084 // We want to intern all strings but also assign offsets for the source string. Since the
1085 // pruning phase has already happened, if we intern a string to one in the image we still
1086 // end up copying an unreachable string.
1087 if (obj->IsString()) {
1088 // Need to check if the string is already interned in another image info so that we don't have
1089 // the intern tables of two different images contain the same string.
1090 mirror::String* interned = FindInternedString(obj->AsString());
1091 if (interned == nullptr) {
1092 // Not in another image space, insert to our table.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001093 interned =
1094 GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString()).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001095 DCHECK_EQ(interned, obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001096 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001097 } else if (obj->IsDexCache()) {
1098 oat_index = GetOatIndexForDexCache(obj->AsDexCache());
1099 } else if (obj->IsClass()) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001100 // Visit and assign offsets for fields and field arrays.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001101 mirror::Class* as_klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001102 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001103 DCHECK_NE(as_klass->GetStatus(), mirror::Class::kStatusError);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001104 if (compile_app_image_) {
1105 // Extra sanity, no boot loader classes should be left!
David Sehr709b0702016-10-13 09:12:37 -07001106 CHECK(!IsBootClassLoaderClass(as_klass)) << as_klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001107 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001108 LengthPrefixedArray<ArtField>* fields[] = {
1109 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1110 };
Mathieu Chartier496577f2016-09-20 15:33:31 -07001111 // Overwrite the oat index value since the class' dex cache is more accurate of where it
1112 // belongs.
1113 oat_index = GetOatIndexForDexCache(dex_cache);
Vladimir Marko944da602016-02-19 12:27:55 +00001114 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001115 {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001116 // Note: This table is only accessed from the image writer, avoid locking to prevent lock
1117 // order violations from root visiting.
1118 image_info.class_table_->InsertWithoutLocks(as_klass);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001119 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001120 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1121 // Total array length including header.
1122 if (cur_fields != nullptr) {
1123 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1124 // Forward the entire array at once.
1125 auto it = native_object_relocations_.find(cur_fields);
1126 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1127 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001128 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001129 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001130 native_object_relocations_.emplace(
1131 cur_fields,
1132 NativeObjectRelocation {
1133 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1134 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001135 offset += header_size;
1136 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001137 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001138 // Need to forward arrays separate of fields.
1139 ArtField* field = &cur_fields->At(i);
1140 auto it2 = native_object_relocations_.find(field);
1141 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
David Sehr709b0702016-10-13 09:12:37 -07001142 << " already assigned " << field->PrettyField() << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001143 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001144 native_object_relocations_.emplace(
1145 field,
1146 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001147 offset += sizeof(ArtField);
1148 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001149 }
1150 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001151 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001152 size_t num_methods = as_klass->NumMethods();
1153 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001154 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001155 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1156 if (WillMethodBeDirty(&m)) {
1157 any_dirty = true;
1158 break;
1159 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001160 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001161 NativeObjectRelocationType type = any_dirty
1162 ? kNativeObjectRelocationTypeArtMethodDirty
1163 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001164 Bin bin_type = BinTypeForNativeRelocationType(type);
1165 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001166 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1167 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001168 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1169 method_size,
1170 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001171 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001172 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001173 CHECK(it == native_object_relocations_.end())
1174 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001175 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001176 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001177 native_object_relocations_.emplace(array,
1178 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001179 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001180 offset,
1181 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1182 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001183 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001184 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001185 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001186 }
Alex Lighte64300b2015-12-15 15:02:47 -08001187 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001188 }
1189 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1190 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001191 if (as_klass->ShouldHaveImt()) {
1192 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1193 for (size_t i = 0; i < ImTable::kSize; ++i) {
1194 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001195 DCHECK(imt_method != nullptr);
1196 if (imt_method->IsRuntimeMethod() &&
1197 !IsInBootImage(imt_method) &&
1198 !NativeRelocationAssigned(imt_method)) {
1199 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001200 }
1201 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001202 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001203
1204 if (as_klass->ShouldHaveImt()) {
1205 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1206 TryAssignImTableOffset(imt, oat_index);
1207 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001208 } else if (obj->IsClassLoader()) {
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001209 // Register the class loader if it has a class table.
1210 // The fake boot class loader should not get registered and we should end up with only one
1211 // class loader.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001212 mirror::ClassLoader* class_loader = obj->AsClassLoader();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001213 if (class_loader->GetClassTable() != nullptr) {
1214 class_loaders_.insert(class_loader);
1215 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001216 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001217 AssignImageBinSlot(obj, oat_index);
1218 work_stack.emplace(obj, oat_index);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001219 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001220 if (obj->IsString()) {
1221 // Always return the interned string if there exists one.
1222 mirror::String* interned = FindInternedString(obj->AsString());
1223 if (interned != nullptr) {
1224 return interned;
1225 }
1226 }
1227 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001228}
1229
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001230bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1231 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1232}
1233
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001234void ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
1235 // No offset, or already assigned.
1236 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
1237 return;
1238 }
1239 // If the method is a conflict method we also want to assign the conflict table offset.
1240 ImageInfo& image_info = GetImageInfo(oat_index);
1241 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1242 native_object_relocations_.emplace(
1243 imt,
1244 NativeObjectRelocation {
1245 oat_index,
1246 image_info.bin_slot_sizes_[kBinImTable],
1247 kNativeObjectRelocationTypeIMTable});
1248 image_info.bin_slot_sizes_[kBinImTable] += size;
1249}
1250
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001251void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1252 // No offset, or already assigned.
1253 if (table == nullptr || NativeRelocationAssigned(table)) {
1254 return;
1255 }
1256 CHECK(!IsInBootImage(table));
1257 // If the method is a conflict method we also want to assign the conflict table offset.
1258 ImageInfo& image_info = GetImageInfo(oat_index);
1259 const size_t size = table->ComputeSize(target_ptr_size_);
1260 native_object_relocations_.emplace(
1261 table,
1262 NativeObjectRelocation {
1263 oat_index,
1264 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1265 kNativeObjectRelocationTypeIMTConflictTable});
1266 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1267}
1268
Jeff Haodcdc85b2015-12-04 14:06:18 -08001269void ImageWriter::AssignMethodOffset(ArtMethod* method,
1270 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001271 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001272 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001273 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
David Sehr709b0702016-10-13 09:12:37 -07001274 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001275 if (method->IsRuntimeMethod()) {
1276 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1277 }
Vladimir Marko944da602016-02-19 12:27:55 +00001278 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001279 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001280 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001281 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001282}
1283
Mathieu Chartier496577f2016-09-20 15:33:31 -07001284void ImageWriter::EnsureBinSlotAssignedCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001285 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1286 DCHECK(writer != nullptr);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001287 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) {
David Sehr709b0702016-10-13 09:12:37 -07001288 CHECK(writer->IsImageBinSlotAssigned(obj)) << mirror::Object::PrettyTypeOf(obj) << " " << obj;
Mathieu Chartier496577f2016-09-20 15:33:31 -07001289 }
1290}
1291
1292void ImageWriter::DeflateMonitorCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED) {
1293 Monitor::Deflate(Thread::Current(), obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001294}
1295
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001296void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1297 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1298 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001299 if (!writer->IsInBootImage(obj)) {
1300 writer->UnbinObjectsIntoOffset(obj);
1301 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001302}
1303
1304void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001305 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001306 CHECK(obj != nullptr);
1307
1308 // We know the bin slot, and the total bin sizes for all objects by now,
1309 // so calculate the object's final image offset.
1310
1311 DCHECK(IsImageBinSlotAssigned(obj));
1312 BinSlot bin_slot = GetImageBinSlot(obj);
1313 // Change the lockword from a bin slot into an offset
1314 AssignImageOffset(obj, bin_slot);
1315}
1316
Mathieu Chartier496577f2016-09-20 15:33:31 -07001317class ImageWriter::VisitReferencesVisitor {
1318 public:
1319 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index)
1320 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {}
1321
1322 // Fix up separately since we also need to fix up method entrypoints.
1323 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1324 REQUIRES_SHARED(Locks::mutator_lock_) {
1325 if (!root->IsNull()) {
1326 VisitRoot(root);
1327 }
1328 }
1329
1330 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1331 REQUIRES_SHARED(Locks::mutator_lock_) {
1332 root->Assign(VisitReference(root->AsMirrorPtr()));
1333 }
1334
Mathieu Chartier31e88222016-10-14 18:43:19 -07001335 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
Mathieu Chartier496577f2016-09-20 15:33:31 -07001336 MemberOffset offset,
1337 bool is_static ATTRIBUTE_UNUSED) const
1338 REQUIRES_SHARED(Locks::mutator_lock_) {
1339 mirror::Object* ref =
1340 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1341 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1342 }
1343
Mathieu Chartier31e88222016-10-14 18:43:19 -07001344 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1345 ObjPtr<mirror::Reference> ref) const
Mathieu Chartier496577f2016-09-20 15:33:31 -07001346 REQUIRES_SHARED(Locks::mutator_lock_) {
1347 ref->SetReferent</*kTransactionActive*/false>(
1348 VisitReference(ref->GetReferent<kWithoutReadBarrier>()));
1349 }
1350
1351 private:
1352 mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1353 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_);
1354 }
1355
1356 ImageWriter* const image_writer_;
1357 WorkStack* const work_stack_;
1358 const size_t oat_index_;
1359};
1360
1361class ImageWriter::GetRootsVisitor : public RootVisitor {
1362 public:
1363 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {}
1364
1365 void VisitRoots(mirror::Object*** roots,
1366 size_t count,
1367 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1368 REQUIRES_SHARED(Locks::mutator_lock_) {
1369 for (size_t i = 0; i < count; ++i) {
1370 roots_->push_back(*roots[i]);
1371 }
1372 }
1373
1374 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1375 size_t count,
1376 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1377 REQUIRES_SHARED(Locks::mutator_lock_) {
1378 for (size_t i = 0; i < count; ++i) {
1379 roots_->push_back(roots[i]->AsMirrorPtr());
1380 }
1381 }
1382
1383 private:
1384 std::vector<mirror::Object*>* const roots_;
1385};
1386
1387void ImageWriter::ProcessWorkStack(WorkStack* work_stack) {
1388 while (!work_stack->empty()) {
1389 std::pair<mirror::Object*, size_t> pair(work_stack->top());
1390 work_stack->pop();
1391 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second);
1392 // Walk references and assign bin slots for them.
1393 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1394 visitor,
1395 visitor);
1396 }
1397}
1398
Vladimir Markof4da6752014-08-01 19:04:18 +01001399void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001400 Thread* const self = Thread::Current();
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07001401 VariableSizedHandleScope handles(self);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001402 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001403 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1404 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001405 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001406
Mathieu Chartier496577f2016-09-20 15:33:31 -07001407 Runtime* const runtime = Runtime::Current();
1408 gc::Heap* const heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001409
Mathieu Chartier31e89252013-08-28 11:29:12 -07001410 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001411 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001412 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001413
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001414 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001415 // Write the image runtime methods.
1416 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1417 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1418 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001419 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
1420 runtime->GetCalleeSaveMethod(Runtime::kSaveAllCalleeSaves);
1421 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
1422 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsOnly);
1423 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
1424 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001425 image_methods_[ImageHeader::kSaveEverythingMethod] =
1426 runtime->GetCalleeSaveMethod(Runtime::kSaveEverything);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001427 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001428 for (auto* m : image_methods_) {
1429 CHECK(m != nullptr);
1430 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001431 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1432 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001433 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001434 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001435 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001436
Mathieu Chartier496577f2016-09-20 15:33:31 -07001437 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
1438 // this lock while holding other locks may cause lock order violations.
1439 heap->VisitObjects(DeflateMonitorCallback, this);
1440
1441 // Work list of <object, oat_index> for objects. Everything on the stack must already be
1442 // assigned a bin slot.
1443 WorkStack work_stack;
1444
1445 // Special case interned strings to put them in the image they are likely to be resolved from.
1446 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
1447 auto it = dex_file_oat_index_map_.find(dex_file);
1448 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1449 const size_t oat_index = it->second;
1450 InternTable* const intern_table = runtime->GetInternTable();
1451 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
1452 uint32_t utf16_length;
1453 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(i, &utf16_length);
Mathieu Chartier9e868092016-10-31 14:58:04 -07001454 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001455 TryAssignBinSlot(work_stack, string, oat_index);
1456 }
1457 }
1458
1459 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor
1460 // visits roots while holding various locks.
1461 {
1462 std::vector<mirror::Object*> roots;
1463 GetRootsVisitor root_visitor(&roots);
1464 runtime->VisitRoots(&root_visitor);
1465 for (mirror::Object* obj : roots) {
1466 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex());
1467 }
1468 }
1469 ProcessWorkStack(&work_stack);
1470
1471 // For app images, there may be objects that are only held live by the by the boot image. One
1472 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback
1473 // does not fail any checks. TODO: We should probably avoid copying these objects.
1474 if (compile_app_image_) {
1475 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) {
1476 DCHECK(space->IsImageSpace());
1477 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1478 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1479 reinterpret_cast<uintptr_t>(space->Limit()),
1480 [this, &work_stack](mirror::Object* obj)
1481 REQUIRES_SHARED(Locks::mutator_lock_) {
1482 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex());
1483 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot).
1484 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1485 visitor,
1486 visitor);
1487 });
1488 }
1489 // Process the work stack in case anything was added by TryAssignBinSlot.
1490 ProcessWorkStack(&work_stack);
1491 }
1492
1493 // Verify that all objects have assigned image bin slots.
1494 heap->VisitObjects(EnsureBinSlotAssignedCallback, this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001495
Vladimir Marko05792b92015-08-03 11:56:49 +01001496 // Calculate size of the dex cache arrays slot and prepare offsets.
1497 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001498
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001499 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001500 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001501 // Calculate how big the intern table will be after being serialized.
1502 InternTable* const intern_table = image_info.intern_table_.get();
1503 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
Vladimir Marko1a1de672016-10-13 12:53:15 +01001504 if (intern_table->StrongSize() != 0u) {
1505 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1506 }
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001507 // Calculate the size of the class table.
1508 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko1a1de672016-10-13 12:53:15 +01001509 DCHECK_EQ(image_info.class_table_->NumZygoteClasses(), 0u);
1510 if (image_info.class_table_->NumNonZygoteClasses() != 0u) {
1511 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
1512 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001513 }
1514
Vladimir Markocf36d492015-08-12 19:27:26 +01001515 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001516 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001517 size_t bin_offset = image_objects_offset_begin_;
1518 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001519 switch (i) {
1520 case kBinArtMethodClean:
1521 case kBinArtMethodDirty: {
1522 bin_offset = RoundUp(bin_offset, method_alignment);
1523 break;
1524 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001525 case kBinDexCacheArray:
1526 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment());
1527 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001528 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001529 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001530 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001531 break;
1532 }
1533 default: {
1534 // Normal alignment.
1535 }
1536 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001537 image_info.bin_slot_offsets_[i] = bin_offset;
1538 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001539 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001540 // NOTE: There may be additional padding between the bin slots and the intern table.
1541 DCHECK_EQ(image_info.image_end_,
1542 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001543 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001544
Jeff Haodcdc85b2015-12-04 14:06:18 -08001545 // Calculate image offsets.
1546 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001547 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001548 image_info.image_begin_ = global_image_begin_ + image_offset;
1549 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001550 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001551 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001552 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001553 image_offset += image_info.image_size_;
1554 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001555
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001556 // Transform each object's bin slot into an offset which will be used to do the final copy.
1557 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001558
Jeff Haodcdc85b2015-12-04 14:06:18 -08001559 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001560
Jeff Haodcdc85b2015-12-04 14:06:18 -08001561 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001562 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001563 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1564 i++;
1565 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001566
Mathieu Chartiere401d142015-04-22 13:56:20 -07001567 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001568 for (auto& pair : native_object_relocations_) {
1569 NativeObjectRelocation& relocation = pair.second;
1570 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001571 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001572 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001573 }
1574
Jeff Haodcdc85b2015-12-04 14:06:18 -08001575 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001576}
1577
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001578size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001579 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001580
1581 // Do not round up any sections here that are represented by the bins since it will break
1582 // offsets.
1583
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001584 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001585 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001586 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001587
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001588 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001589 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1590 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001591 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001592
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001593 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001594 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1595 *methods_section = ImageSection(
1596 bin_slot_offsets_[kBinArtMethodClean],
1597 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1598
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001599 // IMT section.
1600 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1601 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1602
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001603 // Conflict tables section.
1604 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1605 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1606 bin_slot_sizes_[kBinIMTConflictTable]);
1607
1608 // Runtime methods section.
1609 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1610 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1611 bin_slot_sizes_[kBinRuntimeMethod]);
1612
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001613 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001614 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1615 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1616 bin_slot_sizes_[kBinDexCacheArray]);
1617
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001618 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001619 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001620 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001621 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001622 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1623 cur_pos = interned_strings_section->End();
1624 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1625 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1626 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001627 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001628 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001629 cur_pos = class_table_section->End();
1630 // Image end goes right before the start of the image bitmap.
1631 return cur_pos;
1632}
1633
Vladimir Marko944da602016-02-19 12:27:55 +00001634void ImageWriter::CreateHeader(size_t oat_index) {
1635 ImageInfo& image_info = GetImageInfo(oat_index);
1636 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1637 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1638 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001639
1640 // Create the image sections.
1641 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001642 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001643
Mathieu Chartiere401d142015-04-22 13:56:20 -07001644 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001645 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001646 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001647 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001648 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001649 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001650 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001651 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001652 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1653 ++idx;
1654 }
1655 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001656 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1657 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1658 << " Image offset=" << image_info.image_offset_ << std::dec;
1659 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1660 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1661 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1662 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001663 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001664 // Store boot image info for app image so that we can relocate.
1665 uint32_t boot_image_begin = 0;
1666 uint32_t boot_image_end = 0;
1667 uint32_t boot_oat_begin = 0;
1668 uint32_t boot_oat_end = 0;
1669 gc::Heap* const heap = Runtime::Current()->GetHeap();
1670 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001671
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001672 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1673 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001674 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1675 image_end,
1676 sections,
1677 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001678 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001679 PointerToLowMemUInt32(oat_file_begin),
1680 PointerToLowMemUInt32(image_info.oat_data_begin_),
1681 PointerToLowMemUInt32(oat_data_end),
1682 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001683 boot_image_begin,
1684 boot_image_end - boot_image_begin,
1685 boot_oat_begin,
1686 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001687 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001688 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001689 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001690 image_storage_mode_,
1691 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001692}
1693
1694ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001695 auto it = native_object_relocations_.find(method);
David Sehr709b0702016-10-13 09:12:37 -07001696 CHECK(it != native_object_relocations_.end()) << ArtMethod::PrettyMethod(method) << " @ "
1697 << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001698 size_t oat_index = GetOatIndex(method->GetDexCache());
1699 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001700 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1701 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001702}
1703
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001704class FixupRootVisitor : public RootVisitor {
1705 public:
1706 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1707 }
1708
1709 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001710 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001711 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001712 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001713 }
1714 }
1715
1716 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1717 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001718 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001719 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001720 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001721 }
1722 }
1723
1724 private:
1725 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001726};
1727
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001728void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
1729 for (size_t i = 0; i < ImTable::kSize; ++i) {
1730 ArtMethod* method = orig->Get(i, target_ptr_size_);
1731 copy->Set(i, NativeLocationInImage(method), target_ptr_size_);
1732 }
1733}
1734
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001735void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
1736 const size_t count = orig->NumEntries(target_ptr_size_);
1737 for (size_t i = 0; i < count; ++i) {
1738 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
1739 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
1740 copy->SetInterfaceMethod(i, target_ptr_size_, NativeLocationInImage(interface_method));
1741 copy->SetImplementationMethod(i,
1742 target_ptr_size_,
1743 NativeLocationInImage(implementation_method));
1744 }
1745}
1746
Vladimir Marko944da602016-02-19 12:27:55 +00001747void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001748 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001749 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001750 for (auto& pair : native_object_relocations_) {
1751 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001752 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001753 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001754 continue;
1755 }
1756 auto* dest = image_info.image_->Begin() + relocation.offset;
1757 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001758 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001759 switch (relocation.type) {
1760 case kNativeObjectRelocationTypeArtField: {
1761 memcpy(dest, pair.first, sizeof(ArtField));
1762 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001763 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass().Ptr()));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001764 break;
1765 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001766 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001767 case kNativeObjectRelocationTypeArtMethodClean:
1768 case kNativeObjectRelocationTypeArtMethodDirty: {
1769 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001770 reinterpret_cast<ArtMethod*>(dest),
1771 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001772 break;
1773 }
1774 // For arrays, copy just the header since the elements will get copied by their corresponding
1775 // relocations.
1776 case kNativeObjectRelocationTypeArtFieldArray: {
1777 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1778 break;
1779 }
1780 case kNativeObjectRelocationTypeArtMethodArrayClean:
1781 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00001782 size_t size = ArtMethod::Size(target_ptr_size_);
1783 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1784 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1785 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1786 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001787 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00001788 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001789 case kNativeObjectRelocationTypeDexCacheArray:
1790 // Nothing to copy here, everything is done in FixupDexCache().
1791 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001792 case kNativeObjectRelocationTypeIMTable: {
1793 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
1794 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
1795 CopyAndFixupImTable(orig_imt, dest_imt);
1796 break;
1797 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001798 case kNativeObjectRelocationTypeIMTConflictTable: {
1799 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
1800 CopyAndFixupImtConflictTable(
1801 orig_table,
1802 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
1803 break;
1804 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001805 }
1806 }
1807 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001808 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001809 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001810 ArtMethod* method = image_methods_[i];
1811 CHECK(method != nullptr);
1812 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001813 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001814 }
1815 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001816 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001817 FixupRootVisitor root_visitor(this);
1818
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001819 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001820 if (image_info.intern_table_bytes_ > 0) {
1821 const ImageSection& intern_table_section = image_header->GetImageSection(
1822 ImageHeader::kSectionInternedStrings);
1823 InternTable* const intern_table = image_info.intern_table_.get();
1824 uint8_t* const intern_table_memory_ptr =
1825 image_info.image_->Begin() + intern_table_section.Offset();
1826 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1827 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1828 // Fixup the pointers in the newly written intern table to contain image addresses.
1829 InternTable temp_intern_table;
1830 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1831 // the VisitRoots() will update the memory directly rather than the copies.
1832 // This also relies on visit roots not doing any verification which could fail after we update
1833 // the roots to be the image addresses.
1834 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1835 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1836 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1837 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001838 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1839 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001840 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001841 const ImageSection& class_table_section = image_header->GetImageSection(
1842 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001843 uint8_t* const class_table_memory_ptr =
1844 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001845 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001846
1847 ClassTable* table = image_info.class_table_.get();
1848 CHECK(table != nullptr);
1849 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1850 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1851 // Fixup the pointers in the newly written class table to contain image addresses. See
1852 // above comment for intern tables.
1853 ClassTable temp_class_table;
1854 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1855 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1856 table->NumZygoteClasses());
1857 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1858 RootInfo(kRootUnknown));
1859 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001860 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001861}
1862
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001863void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001864 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001865 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1866 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001867 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001868 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001869 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1870 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001871 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001872 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001873}
1874
Mathieu Chartier590fee92013-09-13 13:46:47 -07001875void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001876 DCHECK(obj != nullptr);
1877 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001878 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1879}
1880
Mathieu Chartiere401d142015-04-22 13:56:20 -07001881void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1882 mirror::Class* klass, Bin array_type) {
1883 CHECK(klass->IsArrayClass());
David Sehr709b0702016-10-13 09:12:37 -07001884 CHECK(arr->IsIntArray() || arr->IsLongArray()) << klass->PrettyClass() << " " << arr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001885 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001886 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001887 dst->SetClass(GetImageAddress(arr->GetClass()));
1888 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001889 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001890 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1891 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001892 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001893 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001894 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001895 auto* method = reinterpret_cast<ArtMethod*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07001896 LOG(FATAL) << "No relocation entry for ArtMethod " << method->PrettyMethod() << " @ "
1897 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1898 << Class::PrettyClass(method->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001899 } else {
1900 CHECK_EQ(array_type, kBinArtField);
1901 auto* field = reinterpret_cast<ArtField*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07001902 LOG(FATAL) << "No relocation entry for ArtField " << field->PrettyField() << " @ "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001903 << field << " idx=" << i << "/" << num_elements << " with declaring class "
David Sehr709b0702016-10-13 09:12:37 -07001904 << Class::PrettyClass(field->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001905 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001906 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001907 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001908 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001909 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001910 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001911 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001912 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001913 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001914}
1915
1916void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001917 if (IsInBootImage(obj)) {
1918 return;
1919 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001920 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001921 size_t oat_index = GetOatIndex(obj);
1922 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001923 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1924 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001925 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001926
Jeff Haodcdc85b2015-12-04 14:06:18 -08001927 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001928
1929 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001930 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001931 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001932
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001933 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1934 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001935 const auto it = saved_hashcode_map_.find(obj);
1936 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1937 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07001938 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
1939 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
1940 // safe since we mark all of the objects that may reference non immune objects as gray.
1941 CHECK(dst->AtomicSetMarkBit(0, 1));
1942 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001943 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001944}
1945
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001946// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001947class FixupVisitor {
1948 public:
1949 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1950 }
1951
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001952 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1953 // with other logic.
1954 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1955 const {}
1956 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1957
1958
Mathieu Chartier31e88222016-10-14 18:43:19 -07001959 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001960 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07001961 ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001962 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1963 // image.
1964 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001965 offset,
Mathieu Chartier31e88222016-10-14 18:43:19 -07001966 image_writer_->GetImageAddress(ref.Ptr()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001967 }
1968
1969 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001970 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1971 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001972 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001973 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001974 mirror::Reference::ReferentOffset(),
1975 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001976 }
1977
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001978 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001979 ImageWriter* const image_writer_;
1980 mirror::Object* const copy_;
1981};
1982
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001983class FixupClassVisitor FINAL : public FixupVisitor {
1984 public:
1985 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1986 }
1987
Mathieu Chartier31e88222016-10-14 18:43:19 -07001988 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001989 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001990 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001991 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001992 }
1993
Mathieu Chartier31e88222016-10-14 18:43:19 -07001994 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1995 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001996 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001997 LOG(FATAL) << "Reference not expected here.";
1998 }
1999};
2000
Vladimir Marko05792b92015-08-03 11:56:49 +01002001uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
2002 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002003 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002004 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002005 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
2006 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002007 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01002008 return relocation.offset;
2009}
2010
2011template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002012std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002013 std::ostringstream oss;
2014 oss << ptr;
2015 return oss.str();
2016}
2017
2018template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002019std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07002020 return ArtMethod::PrettyMethod(method);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002021}
2022
2023template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002024T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002025 if (obj == nullptr || IsInBootImage(obj)) {
2026 return obj;
2027 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002028 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002029 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
2030 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002031 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00002032 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002033 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002034 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002035}
2036
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002037template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08002038T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
2039 if (obj == nullptr || IsInBootImage(obj)) {
2040 return obj;
2041 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002042 size_t oat_index = GetOatIndexForDexCache(dex_cache);
2043 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002044 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
2045 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002046}
2047
2048class NativeLocationVisitor {
2049 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002050 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002051
2052 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002053 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002054 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002055 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002056
2057 private:
2058 ImageWriter* const image_writer_;
2059};
2060
2061void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002062 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002063 FixupClassVisitor visitor(this, copy);
Mathieu Chartier31e88222016-10-14 18:43:19 -07002064 ObjPtr<mirror::Object>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002065
2066 // Remove the clinitThreadId. This is required for image determinism.
2067 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002068}
2069
Ian Rogersef7d42f2014-01-06 12:55:46 -08002070void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002071 DCHECK(orig != nullptr);
2072 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07002073 if (kUseBakerOrBrooksReadBarrier) {
2074 orig->AssertReadBarrierPointer();
2075 if (kUseBrooksReadBarrier) {
2076 // Note the address 'copy' isn't the same as the image address of 'orig'.
2077 copy->SetReadBarrierPointer(GetImageAddress(orig));
2078 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
2079 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002080 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002081 auto* klass = orig->GetClass();
2082 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002083 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07002084 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
2085 if (it != pointer_arrays_.end()) {
2086 // Should only need to fixup every pointer array exactly once.
2087 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
2088 pointer_arrays_.erase(it);
2089 return;
2090 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002091 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002092 if (orig->IsClass()) {
2093 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002094 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002095 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
2096 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01002097 auto* dest = down_cast<mirror::Executable*>(copy);
2098 auto* src = down_cast<mirror::Executable*>(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002099 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05002100 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01002101 } else if (!klass->IsArrayClass()) {
2102 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2103 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
2104 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002105 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002106 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002107 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2108 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002109 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002110 // Also set allocator to null to be safe. The allocator is created when we create the class
2111 // table. We also never expect to unload things in the image since they are held live as
2112 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002113 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002114 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002115 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002116 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002117 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002118 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002119}
2120
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002121
2122class ImageAddressVisitor {
2123 public:
2124 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
2125
2126 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002127 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002128 return image_writer_->GetImageAddress(ptr);
2129 }
2130
2131 private:
2132 ImageWriter* const image_writer_;
2133};
2134
2135
Vladimir Marko05792b92015-08-03 11:56:49 +01002136void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2137 mirror::DexCache* copy_dex_cache) {
2138 // Though the DexCache array fields are usually treated as native pointers, we set the full
2139 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2140 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2141 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002142 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002143 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002144 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002145 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002146 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002147 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
2148 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002149 }
2150 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
2151 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002152 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002153 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002154 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002155 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
2156 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002157 }
2158 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
2159 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002160 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002161 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002162 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002163 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002164 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
2165 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002166 // NativeLocationInImage also handles runtime methods since these have relocation info.
2167 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002168 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
2169 }
2170 }
2171 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
2172 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002173 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002174 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002175 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002176 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002177 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
2178 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002179 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002180 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
2181 }
2182 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01002183 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
2184 if (orig_method_types != nullptr) {
2185 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodTypesOffset(),
2186 NativeLocationInImage(orig_method_types),
2187 PointerSize::k64);
2188 orig_dex_cache->FixupResolvedMethodTypes(NativeCopyLocation(orig_method_types, orig_dex_cache),
2189 ImageAddressVisitor(this));
2190 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002191
2192 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2193 // compiler pointers in here will make the output non-deterministic.
2194 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002195}
2196
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002197const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2198 DCHECK_LT(type, kOatAddressCount);
2199 // If we are compiling an app image, we need to use the stubs of the boot image.
2200 if (compile_app_image_) {
2201 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002202 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002203 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2204 DCHECK(!image_spaces.empty());
2205 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002206 CHECK(oat_file != nullptr);
2207 const OatHeader& header = oat_file->GetOatHeader();
2208 switch (type) {
2209 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2210 case kOatAddressQuickGenericJNITrampoline:
2211 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2212 case kOatAddressInterpreterToInterpreterBridge:
2213 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2214 case kOatAddressInterpreterToCompiledCodeBridge:
2215 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2216 case kOatAddressJNIDlsymLookup:
2217 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2218 case kOatAddressQuickIMTConflictTrampoline:
2219 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2220 case kOatAddressQuickResolutionTrampoline:
2221 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2222 case kOatAddressQuickToInterpreterBridge:
2223 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2224 default:
2225 UNREACHABLE();
2226 }
2227 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002228 const ImageInfo& primary_image_info = GetImageInfo(0);
2229 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002230}
2231
Jeff Haodcdc85b2015-12-04 14:06:18 -08002232const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2233 const ImageInfo& image_info,
2234 bool* quick_is_interpreted) {
David Sehr709b0702016-10-13 09:12:37 -07002235 DCHECK(!method->IsResolutionMethod()) << method->PrettyMethod();
2236 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << method->PrettyMethod();
2237 DCHECK(!method->IsImtUnimplementedMethod()) << method->PrettyMethod();
2238 DCHECK(method->IsInvokable()) << method->PrettyMethod();
2239 DCHECK(!IsInBootImage(method)) << method->PrettyMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002240
2241 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2242 // trampoline.
2243
2244 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002245 const void* quick_oat_entry_point =
2246 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2247 const uint8_t* quick_code;
2248
2249 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2250 DCHECK(method->IsCopied());
2251 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2252 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2253 } else {
2254 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2255 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2256 }
2257
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002258 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002259 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2260 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002261 // We have code for a non-static or initialized method, just use the code.
2262 } else if (quick_code == nullptr && method->IsNative() &&
2263 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2264 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002265 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002266 } else if (quick_code == nullptr && !method->IsNative()) {
2267 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002268 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002269 *quick_is_interpreted = true;
2270 } else {
2271 CHECK(!method->GetDeclaringClass()->IsInitialized());
2272 // We have code for a static method, but need to go through the resolution stub for class
2273 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002274 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2275 }
2276 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002277 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002278 }
2279 return quick_code;
2280}
2281
Jeff Haodcdc85b2015-12-04 14:06:18 -08002282void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2283 ArtMethod* copy,
2284 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002285 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002286
2287 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002288 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002289 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002290 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002291 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002292
Ian Rogers848871b2013-08-05 10:56:33 -07002293 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2294 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002295
Ian Rogers848871b2013-08-05 10:56:33 -07002296 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002297 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002298 if (orig->IsRuntimeMethod()) {
2299 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2300 if (orig_table != nullptr) {
2301 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2302 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2303 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2304 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2305 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2306 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2307 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2308 } else {
2309 bool found_one = false;
2310 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2311 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2312 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2313 found_one = true;
2314 break;
2315 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002316 }
David Sehr709b0702016-10-13 09:12:37 -07002317 CHECK(found_one) << "Expected to find callee save method but got " << orig->PrettyMethod();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002318 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002319 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002320 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002321 // We assume all methods have code. If they don't currently then we set them to the use the
2322 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2323 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002324 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002325 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002326 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002327 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002328 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002329 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002330 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002331
Sebastien Hertze1d07812014-05-21 15:44:09 +02002332 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002333 if (orig->IsNative()) {
2334 // The native method's pointer is set to a stub to lookup via dlsym.
2335 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002336 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002337 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002338 }
2339 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002340 }
2341}
2342
Jeff Haodcdc85b2015-12-04 14:06:18 -08002343size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002344 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002345 return std::accumulate(&image_info.bin_slot_sizes_[0],
2346 &image_info.bin_slot_sizes_[up_to],
2347 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002348}
2349
2350ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2351 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002352 static_assert(kBinBits == 3, "wrong number of bin bits");
2353 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002354 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2355
2356 DCHECK_LT(GetBin(), kBinSize);
2357 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2358}
2359
2360ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2361 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2362 DCHECK_EQ(index, GetIndex());
2363}
2364
2365ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2366 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2367}
2368
2369uint32_t ImageWriter::BinSlot::GetIndex() const {
2370 return lockword_ & ~kBinMask;
2371}
2372
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002373ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2374 switch (type) {
2375 case kNativeObjectRelocationTypeArtField:
2376 case kNativeObjectRelocationTypeArtFieldArray:
2377 return kBinArtField;
2378 case kNativeObjectRelocationTypeArtMethodClean:
2379 case kNativeObjectRelocationTypeArtMethodArrayClean:
2380 return kBinArtMethodClean;
2381 case kNativeObjectRelocationTypeArtMethodDirty:
2382 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2383 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002384 case kNativeObjectRelocationTypeDexCacheArray:
2385 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002386 case kNativeObjectRelocationTypeRuntimeMethod:
2387 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002388 case kNativeObjectRelocationTypeIMTable:
2389 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002390 case kNativeObjectRelocationTypeIMTConflictTable:
2391 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002392 }
2393 UNREACHABLE();
2394}
2395
Vladimir Marko944da602016-02-19 12:27:55 +00002396size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002397 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002398 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002399 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002400 auto it = oat_index_map_.find(obj);
2401 DCHECK(it != oat_index_map_.end());
2402 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002403}
2404
Vladimir Marko944da602016-02-19 12:27:55 +00002405size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002406 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002407 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002408 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002409 auto it = dex_file_oat_index_map_.find(dex_file);
2410 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2411 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002412}
2413
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002414size_t ImageWriter::GetOatIndexForDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
2415 return (dex_cache == nullptr)
2416 ? GetDefaultOatIndex()
2417 : GetOatIndexForDexFile(dex_cache->GetDexFile());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002418}
2419
Vladimir Marko944da602016-02-19 12:27:55 +00002420void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2421 size_t oat_loaded_size,
2422 size_t oat_data_offset,
2423 size_t oat_data_size) {
2424 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2425 for (const ImageInfo& info : image_infos_) {
2426 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2427 }
2428 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002429
Vladimir Marko944da602016-02-19 12:27:55 +00002430 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2431 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2432 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2433 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2434 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002435
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002436 if (compile_app_image_) {
2437 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2438 return;
2439 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002440
2441 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002442 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002443 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002444 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002445 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2446 }
2447}
2448
Vladimir Marko944da602016-02-19 12:27:55 +00002449void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2450 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2451 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2452
2453 if (oat_index == GetDefaultOatIndex()) {
2454 // Primary oat file, read the trampolines.
2455 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2456 oat_header.GetInterpreterToInterpreterBridgeOffset();
2457 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2458 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2459 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2460 oat_header.GetJniDlsymLookupOffset();
2461 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2462 oat_header.GetQuickGenericJniTrampolineOffset();
2463 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2464 oat_header.GetQuickImtConflictTrampolineOffset();
2465 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2466 oat_header.GetQuickResolutionTrampolineOffset();
2467 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2468 oat_header.GetQuickToInterpreterBridgeOffset();
2469 }
2470}
2471
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002472ImageWriter::ImageWriter(
2473 const CompilerDriver& compiler_driver,
2474 uintptr_t image_begin,
2475 bool compile_pic,
2476 bool compile_app_image,
2477 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002478 const std::vector<const char*>& oat_filenames,
2479 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002480 : compiler_driver_(compiler_driver),
2481 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2482 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002483 compile_pic_(compile_pic),
2484 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002485 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002486 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002487 dirty_methods_(0u),
2488 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002489 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002490 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002491 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002492 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002493 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002494 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2495 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002496}
2497
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002498ImageWriter::ImageInfo::ImageInfo()
2499 : intern_table_(new InternTable),
2500 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002501
Brian Carlstrom7940e442013-07-12 13:46:57 -07002502} // namespace art