blob: 952a7c637a19eff4684cb2f25f45488260e87cb9 [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"
Andreas Gampea5b09a62016-11-17 15:21:22 -080035#include "dex_file_types.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070036#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070037#include "elf_file.h"
38#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070039#include "elf_writer.h"
40#include "gc/accounting/card_table-inl.h"
41#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070042#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier36a270a2016-07-28 18:08:51 -070043#include "gc/collector/concurrent_copying.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070044#include "gc/heap.h"
45#include "gc/space/large_object_space.h"
46#include "gc/space/space-inl.h"
47#include "globals.h"
48#include "image.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070049#include "imt_conflict_table.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070051#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070052#include "lock_word.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070053#include "mirror/array-inl.h"
54#include "mirror/class-inl.h"
Alex Lightd6251582016-10-31 11:12:30 -070055#include "mirror/class_ext.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "mirror/class_loader.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070057#include "mirror/dex_cache.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "mirror/dex_cache-inl.h"
Neil Fuller0e844392016-09-08 13:43:31 +010059#include "mirror/executable.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070060#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080062#include "mirror/object-refvisitor-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070064#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "oat.h"
66#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070067#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070069#include "scoped_thread_state_change-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070070#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000071#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070072
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070073using ::art::mirror::Class;
74using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070075using ::art::mirror::Object;
76using ::art::mirror::ObjectArray;
77using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070078
79namespace art {
80
Igor Murashkinf5b4c502014-11-14 15:01:59 -080081// Separate objects into multiple bins to optimize dirty memory use.
82static constexpr bool kBinObjects = true;
83
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080084// Return true if an object is already in an image space.
85bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080086 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080087 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080088 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080089 return false;
90 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080091 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
92 const uint8_t* image_begin = boot_image_space->Begin();
93 // Real image end including ArtMethods and ArtField sections.
94 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
95 if (image_begin <= obj && obj < image_end) {
96 return true;
97 }
98 }
99 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800100}
101
102bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800103 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800104 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800105 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800106 return false;
107 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800108 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
109 const ImageHeader& image_header = boot_image_space->GetImageHeader();
110 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
111 return true;
112 }
113 }
114 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800115}
116
Andreas Gampedd9d0552015-03-09 12:57:41 -0700117static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700118 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700119 Class* klass = obj->GetClass();
David Sehr709b0702016-10-13 09:12:37 -0700120 CHECK_NE(Class::PrettyClass(klass), "com.android.dex.Dex");
Andreas Gampedd9d0552015-03-09 12:57:41 -0700121}
122
123static void CheckNoDexObjects() {
124 ScopedObjectAccess soa(Thread::Current());
125 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
126}
127
Vladimir Markof4da6752014-08-01 19:04:18 +0100128bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800129 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800130 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100131 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700132 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100133 PruneNonImageClasses(); // Remove junk
Mathieu Chartier901e0702016-02-19 13:42:48 -0800134 if (!compile_app_image_) {
135 // Avoid for app image since this may increase RAM and image size.
136 ComputeLazyFieldsForImageClasses(); // Add useful information
137 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100138 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100139 heap->CollectGarbage(false); // Remove garbage.
140
Andreas Gampedd9d0552015-03-09 12:57:41 -0700141 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
142 // dex files.
143 //
144 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
145 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
146 // true.
147 if (kIsDebugBuild) {
148 CheckNoDexObjects();
149 }
150
Vladimir Markof4da6752014-08-01 19:04:18 +0100151 if (kIsDebugBuild) {
152 ScopedObjectAccess soa(Thread::Current());
153 CheckNonImageClassesRemoved();
154 }
155
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700156 {
157 ScopedObjectAccess soa(Thread::Current());
158 CalculateNewObjectOffsets();
159 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100160
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700161 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
162 // bin size sums being calculated.
163 if (!AllocMemory()) {
164 return false;
165 }
166
Vladimir Markof4da6752014-08-01 19:04:18 +0100167 return true;
168}
169
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700170bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800171 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000172 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800173 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
174 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800175 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800176 if (image_fd != kInvalidFd) {
177 CHECK_EQ(image_filenames.size(), 1u);
178 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800179 CHECK(!oat_filenames.empty());
180 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700181
Vladimir Marko944da602016-02-19 12:27:55 +0000182 {
183 ScopedObjectAccess soa(Thread::Current());
184 for (size_t i = 0; i < oat_filenames.size(); ++i) {
185 CreateHeader(i);
186 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800187 }
188 }
Alex Light53cb16b2014-06-12 11:26:29 -0700189
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700190 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700191 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800192 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700193 Runtime::Current()->GetHeap()->DisableObjectValidation();
194 CopyAndFixupObjects();
195 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700196
Jeff Haodcdc85b2015-12-04 14:06:18 -0800197 for (size_t i = 0; i < image_filenames.size(); ++i) {
198 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000199 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800200 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800201 if (image_fd != kInvalidFd) {
202 if (strlen(image_filename) == 0u) {
203 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800204 // Empty the file in case it already exists.
205 if (image_file != nullptr) {
206 TEMP_FAILURE_RETRY(image_file->SetLength(0));
207 TEMP_FAILURE_RETRY(image_file->Flush());
208 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800209 } else {
210 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
211 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800212 } else {
213 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800214 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800215
Jeff Haodcdc85b2015-12-04 14:06:18 -0800216 if (image_file == nullptr) {
217 LOG(ERROR) << "Failed to open image file " << image_filename;
218 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800219 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800220
221 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800222 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
223 image_file->Erase();
224 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800225 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800226
Jeff Haodcdc85b2015-12-04 14:06:18 -0800227 std::unique_ptr<char[]> compressed_data;
228 // Image data size excludes the bitmap and the header.
229 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
230 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
231 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
232 size_t data_size;
233 const char* image_data_to_write;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800234 const uint64_t compress_start_time = NanoTime();
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000235
Jeff Haodcdc85b2015-12-04 14:06:18 -0800236 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
237 switch (image_storage_mode_) {
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700238 case ImageHeader::kStorageModeLZ4HC: // Fall-through.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800239 case ImageHeader::kStorageModeLZ4: {
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800240 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800241 compressed_data.reset(new char[compressed_max_size]);
David Lin915ec552017-02-23 15:36:06 -0800242 data_size = LZ4_compress_default(
Jeff Haodcdc85b2015-12-04 14:06:18 -0800243 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
244 &compressed_data[0],
David Lin915ec552017-02-23 15:36:06 -0800245 image_data_size,
246 compressed_max_size);
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800247
248 break;
249 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700250 /*
251 * Disabled due to image_test64 flakyness. Both use same decompression. b/27560444
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800252 case ImageHeader::kStorageModeLZ4HC: {
253 // Bound is same as non HC.
254 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
255 compressed_data.reset(new char[compressed_max_size]);
256 data_size = LZ4_compressHC(
257 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
258 &compressed_data[0],
259 image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800260 break;
261 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700262 */
Jeff Haodcdc85b2015-12-04 14:06:18 -0800263 case ImageHeader::kStorageModeUncompressed: {
264 data_size = image_data_size;
265 image_data_to_write = image_data;
266 break;
267 }
268 default: {
269 LOG(FATAL) << "Unsupported";
270 UNREACHABLE();
271 }
272 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800273
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800274 if (compressed_data != nullptr) {
275 image_data_to_write = &compressed_data[0];
276 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
277 << PrettyDuration(NanoTime() - compress_start_time);
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700278 if (kIsDebugBuild) {
279 std::unique_ptr<uint8_t[]> temp(new uint8_t[image_data_size]);
280 const size_t decompressed_size = LZ4_decompress_safe(
281 reinterpret_cast<char*>(&compressed_data[0]),
282 reinterpret_cast<char*>(&temp[0]),
283 data_size,
284 image_data_size);
285 CHECK_EQ(decompressed_size, image_data_size);
286 CHECK_EQ(memcmp(image_data, &temp[0], image_data_size), 0) << image_storage_mode_;
287 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800288 }
289
Jeff Haodcdc85b2015-12-04 14:06:18 -0800290 // Write out the image + fields + methods.
291 const bool is_compressed = compressed_data != nullptr;
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800292 if (!image_file->PwriteFully(image_data_to_write, data_size, sizeof(ImageHeader))) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800293 PLOG(ERROR) << "Failed to write image file data " << image_filename;
294 image_file->Erase();
295 return false;
296 }
297
298 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
299 // convenience.
300 const ImageSection& bitmap_section = image_header->GetImageSection(
301 ImageHeader::kSectionImageBitmap);
302 // Align up since data size may be unaligned if the image is compressed.
303 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
304 if (!is_compressed) {
305 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
306 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800307 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
308 bitmap_section.Size(),
309 bitmap_position_in_file)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800310 PLOG(ERROR) << "Failed to write image file " << image_filename;
311 image_file->Erase();
312 return false;
313 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800314
315 int err = image_file->Flush();
316 if (err < 0) {
317 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
318 image_file->Erase();
319 return false;
320 }
321
322 // Write header last in case the compiler gets killed in the middle of image writing.
323 // We do not want to have a corrupted image with a valid header.
324 // The header is uncompressed since it contains whether the image is compressed or not.
325 image_header->data_size_ = data_size;
326 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
327 sizeof(ImageHeader),
328 0)) {
329 PLOG(ERROR) << "Failed to write image file header " << image_filename;
330 image_file->Erase();
331 return false;
332 }
333
Jeff Haodcdc85b2015-12-04 14:06:18 -0800334 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
335 static_cast<size_t>(image_file->GetLength()));
336 if (image_file->FlushCloseOrErase() != 0) {
337 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
338 return false;
339 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800340 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700341 return true;
342}
343
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700344void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700345 DCHECK(object != nullptr);
346 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800347
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800348 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700349 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700350 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700351 DCHECK(IsImageOffsetAssigned(object));
352}
353
Mathieu Chartiere401d142015-04-22 13:56:20 -0700354void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
355 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
356 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
357 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
358}
359
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800360void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700361 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800362 DCHECK_NE(image_objects_offset_begin_, 0u);
363
Vladimir Marko944da602016-02-19 12:27:55 +0000364 size_t oat_index = GetOatIndex(object);
365 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800366 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100367 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800368 DCHECK_ALIGNED(new_offset, kObjectAlignment);
369
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700370 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800371 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700372}
373
Ian Rogersef7d42f2014-01-06 12:55:46 -0800374bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800375 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700376 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700377 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700378}
379
Ian Rogersef7d42f2014-01-06 12:55:46 -0800380size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700381 DCHECK(object != nullptr);
382 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700383 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700384 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000385 size_t oat_index = GetOatIndex(object);
386 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800387 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700388 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700389}
390
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800391void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
392 DCHECK(object != nullptr);
393 DCHECK(!IsImageOffsetAssigned(object));
394 DCHECK(!IsImageBinSlotAssigned(object));
395
396 // Before we stomp over the lock word, save the hash code for later.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800397 LockWord lw(object->GetLockWord(false));
398 switch (lw.GetState()) {
399 case LockWord::kFatLocked: {
400 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
401 break;
402 }
403 case LockWord::kThinLocked: {
404 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
405 break;
406 }
407 case LockWord::kUnlocked:
408 // No hash, don't need to save it.
409 break;
410 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700411 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
412 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800413 break;
414 default:
415 LOG(FATAL) << "Unreachable.";
416 UNREACHABLE();
417 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700418 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700419 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800420 DCHECK(IsImageBinSlotAssigned(object));
421}
422
Vladimir Marko20f85592015-03-19 10:07:02 +0000423void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000424 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000425 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
426 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800427 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000428 auto it = dex_file_oat_index_map_.find(dex_file);
429 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800430 ImageInfo& image_info = GetImageInfo(it->second);
431 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
432 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
433 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
434 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000435
Vladimir Marko20f85592015-03-19 10:07:02 +0000436 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700437 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -0800438 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800439 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700440 ObjPtr<mirror::DexCache> dex_cache =
441 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
442 if (dex_cache == nullptr || IsInBootImage(dex_cache.Ptr())) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700443 continue;
444 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000445 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartier0b490842016-05-25 15:05:59 -0700446 CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
447 << "Dex cache should have been pruned " << dex_file->GetLocation()
448 << "; possibly in class path";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700449 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000450 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000451 size_t oat_index = GetOatIndexForDexCache(dex_cache);
452 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800453 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100454 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800455 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
456 start + layout.TypesOffset(),
457 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100458 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800459 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
460 start + layout.MethodsOffset(),
461 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100462 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800463 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
464 start + layout.FieldsOffset(),
465 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100466 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800467 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Narayan Kamath7fe56582016-10-14 18:49:12 +0100468
469 if (dex_cache->GetResolvedMethodTypes() != nullptr) {
470 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethodTypes(),
471 start + layout.MethodTypesOffset(),
472 dex_cache);
473 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000474 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000475}
476
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700477void ImageWriter::AddDexCacheArrayRelocation(void* array,
478 size_t offset,
479 ObjPtr<mirror::DexCache> dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100480 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800481 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000482 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800483 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000484 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100485 }
486}
487
Mathieu Chartiere401d142015-04-22 13:56:20 -0700488void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
489 DCHECK(arr != nullptr);
490 if (kIsDebugBuild) {
491 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800492 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700493 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800494 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800495 CHECK(klass == nullptr || KeepClass(klass))
David Sehr709b0702016-10-13 09:12:37 -0700496 << Class::PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700497 }
498 }
499 }
500 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
501 // ArtMethods.
502 pointer_arrays_.emplace(arr, kBinArtMethodClean);
503}
504
Mathieu Chartier496577f2016-09-20 15:33:31 -0700505void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800506 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800507 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800508
509 // The magic happens here. We segregate objects into different bins based
510 // on how likely they are to get dirty at runtime.
511 //
512 // Likely-to-dirty objects get packed together into the same bin so that
513 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
514 // maximized.
515 //
516 // This means more pages will stay either clean or shared dirty (with zygote) and
517 // the app will use less of its own (private) memory.
518 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000519 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800520
521 if (kBinObjects) {
522 //
523 // Changing the bin of an object is purely a memory-use tuning.
524 // It has no change on runtime correctness.
525 //
526 // Memory analysis has determined that the following types of objects get dirtied
527 // the most:
528 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000529 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
530 // a fixed layout which helps improve generated code (using PC-relative addressing),
531 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
532 // Since these arrays are huge, most pages do not overlap other objects and it's not
533 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100534 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800535 // * Class'es which are verified [their clinit runs only at runtime]
536 // - classes in general [because their static fields get overwritten]
537 // - initialized classes with all-final statics are unlikely to be ever dirty,
538 // so bin them separately
539 // * Art Methods that are:
540 // - native [their native entry point is not looked up until runtime]
541 // - have declaring classes that aren't initialized
542 // [their interpreter/quick entry points are trampolines until the class
543 // becomes initialized]
544 //
545 // We also assume the following objects get dirtied either never or extremely rarely:
546 // * Strings (they are immutable)
547 // * Art methods that aren't native and have initialized declared classes
548 //
549 // We assume that "regular" bin objects are highly unlikely to become dirtied,
550 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
551 //
552 if (object->IsClass()) {
553 bin = kBinClassVerified;
554 mirror::Class* klass = object->AsClass();
555
Mathieu Chartiere401d142015-04-22 13:56:20 -0700556 // Add non-embedded vtable to the pointer array table if there is one.
557 auto* vtable = klass->GetVTable();
558 if (vtable != nullptr) {
559 AddMethodPointerArray(vtable);
560 }
561 auto* iftable = klass->GetIfTable();
562 if (iftable != nullptr) {
563 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
564 if (iftable->GetMethodArrayCount(i) > 0) {
565 AddMethodPointerArray(iftable->GetMethodArray(i));
566 }
567 }
568 }
569
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800570 if (klass->GetStatus() == Class::kStatusInitialized) {
571 bin = kBinClassInitialized;
572
573 // If the class's static fields are all final, put it into a separate bin
574 // since it's very likely it will stay clean.
575 uint32_t num_static_fields = klass->NumStaticFields();
576 if (num_static_fields == 0) {
577 bin = kBinClassInitializedFinalStatics;
578 } else {
579 // Maybe all the statics are final?
580 bool all_final = true;
581 for (uint32_t i = 0; i < num_static_fields; ++i) {
582 ArtField* field = klass->GetStaticField(i);
583 if (!field->IsFinal()) {
584 all_final = false;
585 break;
586 }
587 }
588
589 if (all_final) {
590 bin = kBinClassInitializedFinalStatics;
591 }
592 }
593 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800594 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
595 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700596 } else if (object->GetClass<kVerifyNone>() ==
597 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
598 // Instance of java lang object, probably a lock object. This means it will be dirty when we
599 // synchronize on it.
600 bin = kBinMiscDirty;
601 } else if (object->IsDexCache()) {
602 // Dex file field becomes dirty when the image is loaded.
603 bin = kBinMiscDirty;
604 }
605 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800606 }
607
Mathieu Chartier496577f2016-09-20 15:33:31 -0700608 // Assign the oat index too.
609 DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
610 oat_index_map_.emplace(object, oat_index);
611
Vladimir Marko944da602016-02-19 12:27:55 +0000612 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800613
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800614 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800615 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
616 // Move the current bin size up to accommodate the object we just assigned a bin slot.
617 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800618
619 BinSlot new_bin_slot(bin, current_offset);
620 SetImageBinSlot(object, new_bin_slot);
621
Jeff Haodcdc85b2015-12-04 14:06:18 -0800622 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800623
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800624 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800625 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800626}
627
Mathieu Chartiere401d142015-04-22 13:56:20 -0700628bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
629 if (m->IsNative()) {
630 return true;
631 }
632 mirror::Class* declaring_class = m->GetDeclaringClass();
633 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
634 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
635}
636
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800637bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
638 DCHECK(object != nullptr);
639
640 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
641 // If it's in some other state, then we haven't yet assigned an image bin slot.
642 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
643 return false;
644 } else if (kIsDebugBuild) {
645 LockWord lock_word = object->GetLockWord(false);
646 size_t offset = lock_word.ForwardingAddress();
647 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000648 size_t oat_index = GetOatIndex(object);
649 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800650 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800651 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800652 }
653 return true;
654}
655
656ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
657 DCHECK(object != nullptr);
658 DCHECK(IsImageBinSlotAssigned(object));
659
660 LockWord lock_word = object->GetLockWord(false);
661 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
662 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
663
664 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000665 size_t oat_index = GetOatIndex(object);
666 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800667 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800668
669 return bin_slot;
670}
671
Brian Carlstrom7940e442013-07-12 13:46:57 -0700672bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000673 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800674 ImageSection unused_sections[ImageHeader::kSectionCount];
675 const size_t length = RoundUp(
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700676 image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800677
Jeff Haodcdc85b2015-12-04 14:06:18 -0800678 std::string error_msg;
679 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
680 nullptr,
681 length,
682 PROT_READ | PROT_WRITE,
683 false,
684 false,
685 &error_msg));
686 if (UNLIKELY(image_info.image_.get() == nullptr)) {
687 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
688 return false;
689 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700690
Jeff Haodcdc85b2015-12-04 14:06:18 -0800691 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
692 CHECK_LE(image_info.image_end_, length);
693 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
694 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
695 if (image_info.image_bitmap_.get() == nullptr) {
696 LOG(ERROR) << "Failed to allocate memory for image bitmap";
697 return false;
698 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700699 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700700 return true;
701}
702
Vladimir Markoad06b982016-11-17 16:38:59 +0000703class ImageWriter::ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700704 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700705 bool operator()(ObjPtr<Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700706 StackHandleScope<1> hs(Thread::Current());
707 mirror::Class::ComputeName(hs.NewHandle(c));
708 return true;
709 }
710};
711
Brian Carlstrom7940e442013-07-12 13:46:57 -0700712void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700713 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700714 ComputeLazyFieldsForClassesVisitor visitor;
715 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700716}
717
Vladimir Markof25cc732017-03-16 16:18:15 +0000718static bool IsBootClassLoaderClass(ObjPtr<mirror::Class> klass)
719 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800720 return klass->GetClassLoader() == nullptr;
721}
722
723bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
724 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
725}
726
Vladimir Markof25cc732017-03-16 16:18:15 +0000727bool ImageWriter::PruneAppImageClass(ObjPtr<mirror::Class> klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800728 bool early_exit = false;
729 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800730 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800731}
732
Mathieu Chartier901e0702016-02-19 13:42:48 -0800733bool ImageWriter::PruneAppImageClassInternal(
Vladimir Markof25cc732017-03-16 16:18:15 +0000734 ObjPtr<mirror::Class> klass,
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800735 bool* early_exit,
736 std::unordered_set<mirror::Class*>* visited) {
737 DCHECK(early_exit != nullptr);
738 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800739 DCHECK(compile_app_image_);
Vladimir Markof25cc732017-03-16 16:18:15 +0000740 if (klass == nullptr || IsInBootImage(klass.Ptr())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700741 return false;
742 }
Vladimir Markof25cc732017-03-16 16:18:15 +0000743 auto found = prune_class_memo_.find(klass.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800744 if (found != prune_class_memo_.end()) {
745 // Already computed, return the found value.
746 return found->second;
747 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800748 // Circular dependencies, return false but do not store the result in the memoization table.
Vladimir Markof25cc732017-03-16 16:18:15 +0000749 if (visited->find(klass.Ptr()) != visited->end()) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800750 *early_exit = true;
751 return false;
752 }
Vladimir Markof25cc732017-03-16 16:18:15 +0000753 visited->emplace(klass.Ptr());
Mathieu Chartier901e0702016-02-19 13:42:48 -0800754 bool result = IsBootClassLoaderClass(klass);
755 std::string temp;
756 // Prune if not an image class, this handles any broken sets of image classes such as having a
757 // class in the set but not it's superclass.
758 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800759 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800760 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
761 // app image.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000762 if (klass->IsErroneous()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800763 result = true;
764 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700765 ObjPtr<mirror::ClassExt> ext(klass->GetExtData());
766 CHECK(ext.IsNull() || ext->GetVerifyError() == nullptr) << klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800767 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800768 if (!result) {
769 // Check interfaces since these wont be visited through VisitReferences.)
770 mirror::IfTable* if_table = klass->GetIfTable();
771 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800772 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
773 &my_early_exit,
774 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800775 }
776 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800777 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800778 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
779 &my_early_exit,
780 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800781 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800782 // Check static fields and their classes.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000783 if (klass->IsResolved() && klass->NumReferenceStaticFields() != 0) {
784 size_t num_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800785 // Presumably GC can happen when we are cross compiling, it should not cause performance
786 // problems to do pointer size logic.
787 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
788 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
789 for (size_t i = 0u; i < num_static_fields; ++i) {
790 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
791 if (ref != nullptr) {
792 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800793 result = result || PruneAppImageClassInternal(ref->AsClass(),
794 &my_early_exit,
795 visited);
796 } else {
797 result = result || PruneAppImageClassInternal(ref->GetClass(),
798 &my_early_exit,
799 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800800 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800801 }
802 field_offset = MemberOffset(field_offset.Uint32Value() +
803 sizeof(mirror::HeapReference<mirror::Object>));
804 }
805 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800806 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
807 &my_early_exit,
808 visited);
Mathieu Chartierc27bc402016-08-05 16:09:09 -0700809 // Remove the class if the dex file is not in the set of dex files. This happens for classes that
810 // are from uses library if there is no profile. b/30688277
811 mirror::DexCache* dex_cache = klass->GetDexCache();
812 if (dex_cache != nullptr) {
813 result = result ||
814 dex_file_oat_index_map_.find(dex_cache->GetDexFile()) == dex_file_oat_index_map_.end();
815 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800816 // Erase the element we stored earlier since we are exiting the function.
Vladimir Markof25cc732017-03-16 16:18:15 +0000817 auto it = visited->find(klass.Ptr());
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800818 DCHECK(it != visited->end());
819 visited->erase(it);
820 // Only store result if it is true or none of the calls early exited due to circular
821 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
822 // a child call and we can remember the result.
823 if (result == true || !my_early_exit || visited->empty()) {
Vladimir Markof25cc732017-03-16 16:18:15 +0000824 prune_class_memo_[klass.Ptr()] = result;
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800825 }
826 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800827 return result;
828}
829
Vladimir Markof25cc732017-03-16 16:18:15 +0000830bool ImageWriter::KeepClass(ObjPtr<mirror::Class> klass) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800831 if (klass == nullptr) {
832 return false;
833 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800834 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
835 // Already in boot image, return true.
836 return true;
837 }
838 std::string temp;
839 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
840 return false;
841 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800842 if (compile_app_image_) {
843 // For app images, we need to prune boot loader classes that are not in the boot image since
844 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800845 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800846 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800847 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800848 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700849}
850
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000851class ImageWriter::PruneClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700852 public:
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000853 PruneClassesVisitor(ImageWriter* image_writer, ObjPtr<mirror::ClassLoader> class_loader)
854 : image_writer_(image_writer),
855 class_loader_(class_loader),
856 classes_to_prune_(),
857 defined_class_count_(0u) { }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700858
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000859 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700860 if (!image_writer_->KeepClass(klass.Ptr())) {
861 classes_to_prune_.insert(klass.Ptr());
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000862 if (klass->GetClassLoader() == class_loader_) {
863 ++defined_class_count_;
864 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700865 }
866 return true;
867 }
868
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000869 size_t Prune() REQUIRES_SHARED(Locks::mutator_lock_) {
870 ClassTable* class_table =
871 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader_);
872 for (mirror::Class* klass : classes_to_prune_) {
873 std::string storage;
874 const char* descriptor = klass->GetDescriptor(&storage);
875 bool result = class_table->Remove(descriptor);
876 DCHECK(result);
877 DCHECK(!class_table->Remove(descriptor)) << descriptor;
878 }
879 return defined_class_count_;
880 }
881
882 private:
Vladimir Markocb5ab352016-11-30 15:31:13 +0000883 ImageWriter* const image_writer_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000884 const ObjPtr<mirror::ClassLoader> class_loader_;
885 std::unordered_set<mirror::Class*> classes_to_prune_;
886 size_t defined_class_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700887};
888
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000889class ImageWriter::PruneClassLoaderClassesVisitor : public ClassLoaderVisitor {
890 public:
891 explicit PruneClassLoaderClassesVisitor(ImageWriter* image_writer)
892 : image_writer_(image_writer), removed_class_count_(0) {}
893
894 virtual void Visit(ObjPtr<mirror::ClassLoader> class_loader) OVERRIDE
895 REQUIRES_SHARED(Locks::mutator_lock_) {
896 PruneClassesVisitor classes_visitor(image_writer_, class_loader);
897 ClassTable* class_table =
898 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader);
899 class_table->Visit(classes_visitor);
900 removed_class_count_ += classes_visitor.Prune();
Vladimir Markof25cc732017-03-16 16:18:15 +0000901
902 // Record app image class loader. The fake boot class loader should not get registered
903 // and we should end up with only one class loader for an app and none for boot image.
904 if (class_loader != nullptr && class_table != nullptr) {
905 DCHECK(class_loader_ == nullptr);
906 class_loader_ = class_loader;
907 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000908 }
909
910 size_t GetRemovedClassCount() const {
911 return removed_class_count_;
912 }
913
Vladimir Markof25cc732017-03-16 16:18:15 +0000914 ObjPtr<mirror::ClassLoader> GetClassLoader() const REQUIRES_SHARED(Locks::mutator_lock_) {
915 return class_loader_;
916 }
917
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000918 private:
919 ImageWriter* const image_writer_;
920 size_t removed_class_count_;
Vladimir Markof25cc732017-03-16 16:18:15 +0000921 ObjPtr<mirror::ClassLoader> class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000922};
923
924void ImageWriter::VisitClassLoaders(ClassLoaderVisitor* visitor) {
925 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
926 visitor->Visit(nullptr); // Visit boot class loader.
927 Runtime::Current()->GetClassLinker()->VisitClassLoaders(visitor);
928}
929
Vladimir Markof25cc732017-03-16 16:18:15 +0000930void ImageWriter::PruneAndPreloadDexCache(ObjPtr<mirror::DexCache> dex_cache,
931 ObjPtr<mirror::ClassLoader> class_loader) {
932 // To ensure deterministic contents of the hash-based arrays, each slot shall contain
933 // the candidate with the lowest index. As we're processing entries in increasing index
934 // order, this means trying to look up the entry for the current index if the slot is
935 // empty or if it contains a higher index.
936
937 Runtime* runtime = Runtime::Current();
938 ClassLinker* class_linker = runtime->GetClassLinker();
939 ArtMethod* resolution_method = runtime->GetResolutionMethod();
940 const DexFile& dex_file = *dex_cache->GetDexFile();
941 // Prune methods.
942 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
943 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
944 ArtMethod* method =
945 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
946 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
947 mirror::Class* declaring_class = method->GetDeclaringClass();
948 // Copied methods may be held live by a class which was not an image class but have a
949 // declaring class which is an image class. Set it to the resolution method to be safe and
950 // prevent dangling pointers.
951 if (method->IsCopied() || !KeepClass(declaring_class)) {
952 mirror::DexCache::SetElementPtrSize(resolved_methods,
953 i,
954 resolution_method,
955 target_ptr_size_);
956 } else if (kIsDebugBuild) {
957 // Check that the class is still in the classes table.
958 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
959 CHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
960 << Class::PrettyClass(declaring_class) << " not in class linker table";
961 }
962 }
963 // Prune fields and make the contents of the field array deterministic.
964 mirror::FieldDexCacheType* resolved_fields = dex_cache->GetResolvedFields();
965 dex::TypeIndex last_class_idx; // Initialized to invalid index.
966 ObjPtr<mirror::Class> last_class = nullptr;
967 for (size_t i = 0, end = dex_file.NumFieldIds(); i < end; ++i) {
968 uint32_t slot_idx = dex_cache->FieldSlotIndex(i);
969 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_fields, slot_idx, target_ptr_size_);
970 uint32_t stored_index = pair.index;
971 ArtField* field = pair.object;
972 if (field != nullptr && i > stored_index) {
973 continue; // Already checked.
974 }
975 // Check if the referenced class is in the image. Note that we want to check the referenced
976 // class rather than the declaring class to preserve the semantics, i.e. using a FieldId
977 // results in resolving the referenced class and that can for example throw OOME.
978 const DexFile::FieldId& field_id = dex_file.GetFieldId(i);
979 if (field_id.class_idx_ != last_class_idx) {
980 last_class_idx = field_id.class_idx_;
981 last_class = class_linker->LookupResolvedType(
982 dex_file, last_class_idx, dex_cache, class_loader);
983 if (last_class != nullptr && !KeepClass(last_class)) {
984 last_class = nullptr;
985 }
986 }
987 if (field == nullptr || i < stored_index) {
988 if (last_class != nullptr) {
989 const char* name = dex_file.StringDataByIdx(field_id.name_idx_);
990 const char* type = dex_file.StringByTypeIdx(field_id.type_idx_);
991 field = mirror::Class::FindField(Thread::Current(), last_class, name, type);
992 if (field != nullptr) {
993 // If the referenced class is in the image, the defining class must also be there.
994 DCHECK(KeepClass(field->GetDeclaringClass()));
995 dex_cache->SetResolvedField(i, field, target_ptr_size_);
996 }
997 }
998 } else {
999 DCHECK_EQ(i, stored_index);
1000 if (last_class == nullptr) {
1001 dex_cache->ClearResolvedField(stored_index, target_ptr_size_);
1002 }
1003 }
1004 }
1005 // Prune types and make the contents of the type array deterministic.
1006 // This is done after fields and methods as their lookup can touch the types array.
1007 for (size_t i = 0, end = dex_cache->GetDexFile()->NumTypeIds(); i < end; ++i) {
1008 dex::TypeIndex type_idx(i);
1009 uint32_t slot_idx = dex_cache->TypeSlotIndex(type_idx);
1010 mirror::TypeDexCachePair pair =
1011 dex_cache->GetResolvedTypes()[slot_idx].load(std::memory_order_relaxed);
1012 uint32_t stored_index = pair.index;
1013 ObjPtr<mirror::Class> klass = pair.object.Read();
1014 if (klass == nullptr || i < stored_index) {
1015 klass = class_linker->LookupResolvedType(dex_file, type_idx, dex_cache, class_loader);
1016 if (klass != nullptr) {
1017 DCHECK_EQ(dex_cache->GetResolvedType(type_idx), klass);
1018 stored_index = i; // For correct clearing below if not keeping the `klass`.
1019 }
1020 } else if (i == stored_index && !KeepClass(klass)) {
1021 dex_cache->ClearResolvedType(dex::TypeIndex(stored_index));
1022 }
1023 }
1024 // Strings do not need pruning, but the contents of the string array must be deterministic.
1025 for (size_t i = 0, end = dex_cache->GetDexFile()->NumStringIds(); i < end; ++i) {
1026 dex::StringIndex string_idx(i);
1027 uint32_t slot_idx = dex_cache->StringSlotIndex(string_idx);
1028 mirror::StringDexCachePair pair =
1029 dex_cache->GetStrings()[slot_idx].load(std::memory_order_relaxed);
1030 uint32_t stored_index = pair.index;
1031 ObjPtr<mirror::String> string = pair.object.Read();
1032 if (string == nullptr || i < stored_index) {
1033 string = class_linker->LookupString(dex_file, string_idx, dex_cache);
1034 DCHECK(string == nullptr || dex_cache->GetResolvedString(string_idx) == string);
1035 }
1036 }
1037}
1038
Brian Carlstrom7940e442013-07-12 13:46:57 -07001039void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001040 Runtime* runtime = Runtime::Current();
1041 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001042 Thread* self = Thread::Current();
Vladimir Markof25cc732017-03-16 16:18:15 +00001043 ScopedAssertNoThreadSuspension sa(__FUNCTION__);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001044
Mathieu Chartier696632e2016-06-03 17:47:32 -07001045 // Clear class table strong roots so that dex caches can get pruned. We require pruning the class
1046 // path dex caches.
1047 class_linker->ClearClassTableStrongRoots();
1048
Brian Carlstrom7940e442013-07-12 13:46:57 -07001049 // Remove the undesired classes from the class roots.
Vladimir Markof25cc732017-03-16 16:18:15 +00001050 ObjPtr<mirror::ClassLoader> class_loader;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001051 {
1052 PruneClassLoaderClassesVisitor class_loader_visitor(this);
1053 VisitClassLoaders(&class_loader_visitor);
1054 VLOG(compiler) << "Pruned " << class_loader_visitor.GetRemovedClassCount() << " classes";
Vladimir Markof25cc732017-03-16 16:18:15 +00001055 class_loader = class_loader_visitor.GetClassLoader();
1056 DCHECK_EQ(class_loader != nullptr, compile_app_image_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001057 }
1058
1059 // Clear references to removed classes from the DexCaches.
Vladimir Markof25cc732017-03-16 16:18:15 +00001060 std::vector<ObjPtr<mirror::DexCache>> dex_caches;
1061 {
1062 ReaderMutexLock mu2(self, *Locks::dex_lock_);
1063 dex_caches.reserve(class_linker->GetDexCachesData().size());
1064 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1065 if (self->IsJWeakCleared(data.weak_root)) {
1066 continue;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001067 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001068 dex_caches.push_back(self->DecodeJObject(data.weak_root)->AsDexCache());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001069 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001070 }
1071 for (ObjPtr<mirror::DexCache> dex_cache : dex_caches) {
1072 PruneAndPreloadDexCache(dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001073 }
Andreas Gampe8ac75952015-06-02 21:01:45 -07001074
1075 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
1076 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001077
1078 // Clear to save RAM.
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00001079 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001080}
1081
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001082void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001083 if (compiler_driver_.GetImageClasses() != nullptr) {
1084 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001085 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001086 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001087}
1088
1089void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
1090 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001091 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001092 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001093 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001094 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001095 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001096 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
David Sehr709b0702016-10-13 09:12:37 -07001097 << " " << klass->PrettyDescriptor();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001098 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001099 }
1100}
1101
1102void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001103 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001104 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001105 for (const std::string& image_class : *image_classes) {
1106 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001107 }
1108}
1109
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001110mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
1111 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +00001112 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001113 ObjPtr<mirror::String> const found = image_info.intern_table_->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001114 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
1115 << string->ToModifiedUtf8();
1116 if (found != nullptr) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001117 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001118 }
1119 }
1120 if (compile_app_image_) {
1121 Runtime* const runtime = Runtime::Current();
Mathieu Chartier9e868092016-10-31 14:58:04 -07001122 ObjPtr<mirror::String> found = runtime->GetInternTable()->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001123 // If we found it in the runtime intern table it could either be in the boot image or interned
1124 // during app image compilation. If it was in the boot image return that, otherwise return null
1125 // since it belongs to another image space.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001126 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found.Ptr())) {
1127 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001128 }
1129 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
1130 << string->ToModifiedUtf8();
1131 }
1132 return nullptr;
1133}
1134
Brian Carlstrom7940e442013-07-12 13:46:57 -07001135
Vladimir Marko944da602016-02-19 12:27:55 +00001136ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001137 Runtime* runtime = Runtime::Current();
1138 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001139 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001140 StackHandleScope<3> hs(self);
1141 Handle<Class> object_array_class(hs.NewHandle(
1142 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001143
Jeff Haodcdc85b2015-12-04 14:06:18 -08001144 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +00001145 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001146 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +00001147 size_t image_oat_index = pair.second;
1148 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001149 image_dex_files.insert(image_dex_file);
1150 }
1151 }
1152
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001153 // build an Object[] of all the DexCaches used in the source_space_.
1154 // Since we can't hold the dex lock when allocating the dex_caches
1155 // ObjectArray, we lock the dex lock twice, first to get the number
1156 // of dex caches first and then lock it again to copy the dex
1157 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001158 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001159 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001160 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001161 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001162 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001163 ObjPtr<mirror::DexCache> dex_cache =
1164 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001165 if (dex_cache == nullptr) {
1166 continue;
1167 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001168 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001169 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001170 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1171 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001172 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001173 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001174 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001175 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001176 CHECK(dex_caches != nullptr) << "Failed to allocate a dex cache array.";
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001177 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001178 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001179 size_t non_image_dex_caches = 0;
1180 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001181 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001182 ObjPtr<mirror::DexCache> dex_cache =
1183 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001184 if (dex_cache == nullptr) {
1185 continue;
1186 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001187 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001188 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001189 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1190 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001191 }
1192 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1193 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001194 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001195 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001196 ObjPtr<mirror::DexCache> dex_cache =
1197 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001198 if (dex_cache == nullptr) {
1199 continue;
1200 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001201 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001202 if (!IsInBootImage(dex_cache.Ptr()) &&
1203 image_dex_files.find(dex_file) != image_dex_files.end()) {
1204 dex_caches->Set<false>(i, dex_cache.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001205 ++i;
1206 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001207 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001208 }
1209
1210 // build an Object[] of the roots needed to restore the runtime
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001211 int32_t image_roots_size = ImageHeader::NumberOfImageRoots(compile_app_image_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001212 auto image_roots(hs.NewHandle(
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001213 ObjectArray<Object>::Alloc(self, object_array_class.Get(), image_roots_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001214 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001215 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001216 // image_roots[ImageHeader::kClassLoader] will be set later for app image.
1217 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1218 "Class loader should be the last image root.");
1219 for (int32_t i = 0; i < ImageHeader::kImageRootsMax - 1; ++i) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001220 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001221 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001222 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001223}
1224
Mathieu Chartier496577f2016-09-20 15:33:31 -07001225mirror::Object* ImageWriter::TryAssignBinSlot(WorkStack& work_stack,
1226 mirror::Object* obj,
1227 size_t oat_index) {
1228 if (obj == nullptr || IsInBootImage(obj)) {
1229 // Object is null or already in the image, there is no work to do.
1230 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001231 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001232 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001233 // We want to intern all strings but also assign offsets for the source string. Since the
1234 // pruning phase has already happened, if we intern a string to one in the image we still
1235 // end up copying an unreachable string.
1236 if (obj->IsString()) {
1237 // Need to check if the string is already interned in another image info so that we don't have
1238 // the intern tables of two different images contain the same string.
1239 mirror::String* interned = FindInternedString(obj->AsString());
1240 if (interned == nullptr) {
1241 // Not in another image space, insert to our table.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001242 interned =
1243 GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString()).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001244 DCHECK_EQ(interned, obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001245 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001246 } else if (obj->IsDexCache()) {
1247 oat_index = GetOatIndexForDexCache(obj->AsDexCache());
1248 } else if (obj->IsClass()) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001249 // Visit and assign offsets for fields and field arrays.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001250 mirror::Class* as_klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001251 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Vladimir Marko72ab6842017-01-20 19:32:50 +00001252 DCHECK(!as_klass->IsErroneous()) << as_klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001253 if (compile_app_image_) {
1254 // Extra sanity, no boot loader classes should be left!
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00001255 CHECK(!IsBootClassLoaderClass(as_klass)) << as_klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001256 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001257 LengthPrefixedArray<ArtField>* fields[] = {
1258 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1259 };
Mathieu Chartier496577f2016-09-20 15:33:31 -07001260 // Overwrite the oat index value since the class' dex cache is more accurate of where it
1261 // belongs.
1262 oat_index = GetOatIndexForDexCache(dex_cache);
Vladimir Marko944da602016-02-19 12:27:55 +00001263 ImageInfo& image_info = GetImageInfo(oat_index);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001264 if (!compile_app_image_) {
1265 // Note: Avoid locking to prevent lock order violations from root visiting;
1266 // image_info.class_table_ is only accessed from the image writer.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001267 image_info.class_table_->InsertWithoutLocks(as_klass);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001268 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001269 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1270 // Total array length including header.
1271 if (cur_fields != nullptr) {
1272 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1273 // Forward the entire array at once.
1274 auto it = native_object_relocations_.find(cur_fields);
1275 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1276 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001277 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001278 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001279 native_object_relocations_.emplace(
1280 cur_fields,
1281 NativeObjectRelocation {
1282 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1283 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001284 offset += header_size;
1285 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001286 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001287 // Need to forward arrays separate of fields.
1288 ArtField* field = &cur_fields->At(i);
1289 auto it2 = native_object_relocations_.find(field);
1290 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
David Sehr709b0702016-10-13 09:12:37 -07001291 << " already assigned " << field->PrettyField() << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001292 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001293 native_object_relocations_.emplace(
1294 field,
1295 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001296 offset += sizeof(ArtField);
1297 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001298 }
1299 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001300 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001301 size_t num_methods = as_klass->NumMethods();
1302 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001303 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001304 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1305 if (WillMethodBeDirty(&m)) {
1306 any_dirty = true;
1307 break;
1308 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001309 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001310 NativeObjectRelocationType type = any_dirty
1311 ? kNativeObjectRelocationTypeArtMethodDirty
1312 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001313 Bin bin_type = BinTypeForNativeRelocationType(type);
1314 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001315 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1316 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001317 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1318 method_size,
1319 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001320 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001321 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001322 CHECK(it == native_object_relocations_.end())
1323 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001324 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001325 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001326 native_object_relocations_.emplace(array,
1327 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001328 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001329 offset,
1330 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1331 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001332 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001333 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001334 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001335 }
Alex Lighte64300b2015-12-15 15:02:47 -08001336 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001337 }
1338 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1339 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001340 if (as_klass->ShouldHaveImt()) {
1341 ImTable* imt = as_klass->GetImt(target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001342 if (TryAssignImTableOffset(imt, oat_index)) {
1343 // Since imt's can be shared only do this the first time to not double count imt method
1344 // fixups.
1345 for (size_t i = 0; i < ImTable::kSize; ++i) {
1346 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
1347 DCHECK(imt_method != nullptr);
1348 if (imt_method->IsRuntimeMethod() &&
1349 !IsInBootImage(imt_method) &&
1350 !NativeRelocationAssigned(imt_method)) {
1351 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
1352 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001353 }
1354 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001355 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001356 } else if (obj->IsClassLoader()) {
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001357 // Register the class loader if it has a class table.
1358 // The fake boot class loader should not get registered and we should end up with only one
1359 // class loader.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001360 mirror::ClassLoader* class_loader = obj->AsClassLoader();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001361 if (class_loader->GetClassTable() != nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001362 DCHECK(compile_app_image_);
1363 DCHECK(class_loaders_.empty());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001364 class_loaders_.insert(class_loader);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001365 ImageInfo& image_info = GetImageInfo(oat_index);
1366 // Note: Avoid locking to prevent lock order violations from root visiting;
1367 // image_info.class_table_ table is only accessed from the image writer
1368 // and class_loader->GetClassTable() is iterated but not modified.
1369 image_info.class_table_->CopyWithoutLocks(*class_loader->GetClassTable());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001370 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001371 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001372 AssignImageBinSlot(obj, oat_index);
1373 work_stack.emplace(obj, oat_index);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001374 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001375 if (obj->IsString()) {
1376 // Always return the interned string if there exists one.
1377 mirror::String* interned = FindInternedString(obj->AsString());
1378 if (interned != nullptr) {
1379 return interned;
1380 }
1381 }
1382 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001383}
1384
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001385bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1386 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1387}
1388
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001389bool ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001390 // No offset, or already assigned.
1391 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001392 return false;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001393 }
1394 // If the method is a conflict method we also want to assign the conflict table offset.
1395 ImageInfo& image_info = GetImageInfo(oat_index);
1396 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1397 native_object_relocations_.emplace(
1398 imt,
1399 NativeObjectRelocation {
1400 oat_index,
1401 image_info.bin_slot_sizes_[kBinImTable],
1402 kNativeObjectRelocationTypeIMTable});
1403 image_info.bin_slot_sizes_[kBinImTable] += size;
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001404 return true;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001405}
1406
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001407void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1408 // No offset, or already assigned.
1409 if (table == nullptr || NativeRelocationAssigned(table)) {
1410 return;
1411 }
1412 CHECK(!IsInBootImage(table));
1413 // If the method is a conflict method we also want to assign the conflict table offset.
1414 ImageInfo& image_info = GetImageInfo(oat_index);
1415 const size_t size = table->ComputeSize(target_ptr_size_);
1416 native_object_relocations_.emplace(
1417 table,
1418 NativeObjectRelocation {
1419 oat_index,
1420 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1421 kNativeObjectRelocationTypeIMTConflictTable});
1422 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1423}
1424
Jeff Haodcdc85b2015-12-04 14:06:18 -08001425void ImageWriter::AssignMethodOffset(ArtMethod* method,
1426 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001427 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001428 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001429 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
David Sehr709b0702016-10-13 09:12:37 -07001430 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001431 if (method->IsRuntimeMethod()) {
1432 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1433 }
Vladimir Marko944da602016-02-19 12:27:55 +00001434 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001435 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001436 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001437 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001438}
1439
Mathieu Chartier496577f2016-09-20 15:33:31 -07001440void ImageWriter::EnsureBinSlotAssignedCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001441 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1442 DCHECK(writer != nullptr);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001443 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) {
David Sehr709b0702016-10-13 09:12:37 -07001444 CHECK(writer->IsImageBinSlotAssigned(obj)) << mirror::Object::PrettyTypeOf(obj) << " " << obj;
Mathieu Chartier496577f2016-09-20 15:33:31 -07001445 }
1446}
1447
1448void ImageWriter::DeflateMonitorCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED) {
1449 Monitor::Deflate(Thread::Current(), obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001450}
1451
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001452void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1453 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1454 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001455 if (!writer->IsInBootImage(obj)) {
1456 writer->UnbinObjectsIntoOffset(obj);
1457 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001458}
1459
1460void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001461 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001462 CHECK(obj != nullptr);
1463
1464 // We know the bin slot, and the total bin sizes for all objects by now,
1465 // so calculate the object's final image offset.
1466
1467 DCHECK(IsImageBinSlotAssigned(obj));
1468 BinSlot bin_slot = GetImageBinSlot(obj);
1469 // Change the lockword from a bin slot into an offset
1470 AssignImageOffset(obj, bin_slot);
1471}
1472
Mathieu Chartier496577f2016-09-20 15:33:31 -07001473class ImageWriter::VisitReferencesVisitor {
1474 public:
1475 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index)
1476 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {}
1477
1478 // Fix up separately since we also need to fix up method entrypoints.
1479 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1480 REQUIRES_SHARED(Locks::mutator_lock_) {
1481 if (!root->IsNull()) {
1482 VisitRoot(root);
1483 }
1484 }
1485
1486 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1487 REQUIRES_SHARED(Locks::mutator_lock_) {
1488 root->Assign(VisitReference(root->AsMirrorPtr()));
1489 }
1490
Mathieu Chartier31e88222016-10-14 18:43:19 -07001491 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
Mathieu Chartier496577f2016-09-20 15:33:31 -07001492 MemberOffset offset,
1493 bool is_static ATTRIBUTE_UNUSED) const
1494 REQUIRES_SHARED(Locks::mutator_lock_) {
1495 mirror::Object* ref =
1496 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1497 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1498 }
1499
Mathieu Chartier31e88222016-10-14 18:43:19 -07001500 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1501 ObjPtr<mirror::Reference> ref) const
Mathieu Chartier496577f2016-09-20 15:33:31 -07001502 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001503 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001504 }
1505
1506 private:
1507 mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1508 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_);
1509 }
1510
1511 ImageWriter* const image_writer_;
1512 WorkStack* const work_stack_;
1513 const size_t oat_index_;
1514};
1515
1516class ImageWriter::GetRootsVisitor : public RootVisitor {
1517 public:
1518 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {}
1519
1520 void VisitRoots(mirror::Object*** roots,
1521 size_t count,
1522 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1523 REQUIRES_SHARED(Locks::mutator_lock_) {
1524 for (size_t i = 0; i < count; ++i) {
1525 roots_->push_back(*roots[i]);
1526 }
1527 }
1528
1529 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1530 size_t count,
1531 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1532 REQUIRES_SHARED(Locks::mutator_lock_) {
1533 for (size_t i = 0; i < count; ++i) {
1534 roots_->push_back(roots[i]->AsMirrorPtr());
1535 }
1536 }
1537
1538 private:
1539 std::vector<mirror::Object*>* const roots_;
1540};
1541
1542void ImageWriter::ProcessWorkStack(WorkStack* work_stack) {
1543 while (!work_stack->empty()) {
1544 std::pair<mirror::Object*, size_t> pair(work_stack->top());
1545 work_stack->pop();
1546 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second);
1547 // Walk references and assign bin slots for them.
1548 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1549 visitor,
1550 visitor);
1551 }
1552}
1553
Vladimir Markof4da6752014-08-01 19:04:18 +01001554void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001555 Thread* const self = Thread::Current();
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07001556 VariableSizedHandleScope handles(self);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001557 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001558 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1559 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001560 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001561
Mathieu Chartier496577f2016-09-20 15:33:31 -07001562 Runtime* const runtime = Runtime::Current();
1563 gc::Heap* const heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001564
Mathieu Chartier31e89252013-08-28 11:29:12 -07001565 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001566 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001567 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001568
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001569 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001570 // Write the image runtime methods.
1571 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1572 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1573 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001574 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
1575 runtime->GetCalleeSaveMethod(Runtime::kSaveAllCalleeSaves);
1576 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
1577 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsOnly);
1578 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
1579 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001580 image_methods_[ImageHeader::kSaveEverythingMethod] =
1581 runtime->GetCalleeSaveMethod(Runtime::kSaveEverything);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001582 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001583 for (auto* m : image_methods_) {
1584 CHECK(m != nullptr);
1585 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001586 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1587 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001588 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001589 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001590 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001591
Mathieu Chartier496577f2016-09-20 15:33:31 -07001592 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
1593 // this lock while holding other locks may cause lock order violations.
1594 heap->VisitObjects(DeflateMonitorCallback, this);
1595
1596 // Work list of <object, oat_index> for objects. Everything on the stack must already be
1597 // assigned a bin slot.
1598 WorkStack work_stack;
1599
1600 // Special case interned strings to put them in the image they are likely to be resolved from.
1601 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
1602 auto it = dex_file_oat_index_map_.find(dex_file);
1603 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1604 const size_t oat_index = it->second;
1605 InternTable* const intern_table = runtime->GetInternTable();
1606 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
1607 uint32_t utf16_length;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001608 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(dex::StringIndex(i),
1609 &utf16_length);
Mathieu Chartier9e868092016-10-31 14:58:04 -07001610 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001611 TryAssignBinSlot(work_stack, string, oat_index);
1612 }
1613 }
1614
1615 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor
1616 // visits roots while holding various locks.
1617 {
1618 std::vector<mirror::Object*> roots;
1619 GetRootsVisitor root_visitor(&roots);
1620 runtime->VisitRoots(&root_visitor);
1621 for (mirror::Object* obj : roots) {
1622 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex());
1623 }
1624 }
1625 ProcessWorkStack(&work_stack);
1626
1627 // For app images, there may be objects that are only held live by the by the boot image. One
1628 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback
1629 // does not fail any checks. TODO: We should probably avoid copying these objects.
1630 if (compile_app_image_) {
1631 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) {
1632 DCHECK(space->IsImageSpace());
1633 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1634 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1635 reinterpret_cast<uintptr_t>(space->Limit()),
1636 [this, &work_stack](mirror::Object* obj)
1637 REQUIRES_SHARED(Locks::mutator_lock_) {
1638 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex());
1639 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot).
1640 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1641 visitor,
1642 visitor);
1643 });
1644 }
1645 // Process the work stack in case anything was added by TryAssignBinSlot.
1646 ProcessWorkStack(&work_stack);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001647
1648 // Store the class loader in the class roots.
1649 CHECK_EQ(class_loaders_.size(), 1u);
1650 CHECK_EQ(image_roots.size(), 1u);
1651 CHECK(*class_loaders_.begin() != nullptr);
1652 image_roots[0]->Set<false>(ImageHeader::kClassLoader, *class_loaders_.begin());
Mathieu Chartier496577f2016-09-20 15:33:31 -07001653 }
1654
1655 // Verify that all objects have assigned image bin slots.
1656 heap->VisitObjects(EnsureBinSlotAssignedCallback, this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001657
Vladimir Marko05792b92015-08-03 11:56:49 +01001658 // Calculate size of the dex cache arrays slot and prepare offsets.
1659 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001660
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001661 // Calculate the sizes of the intern tables, class tables, and fixup tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001662 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001663 // Calculate how big the intern table will be after being serialized.
1664 InternTable* const intern_table = image_info.intern_table_.get();
1665 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
Vladimir Marko1a1de672016-10-13 12:53:15 +01001666 if (intern_table->StrongSize() != 0u) {
1667 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1668 }
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001669
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001670 // Calculate the size of the class table.
1671 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001672 DCHECK_EQ(image_info.class_table_->NumReferencedZygoteClasses(), 0u);
1673 if (image_info.class_table_->NumReferencedNonZygoteClasses() != 0u) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001674 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
1675 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001676 }
1677
Vladimir Markocf36d492015-08-12 19:27:26 +01001678 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001679 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001680 size_t bin_offset = image_objects_offset_begin_;
1681 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001682 switch (i) {
1683 case kBinArtMethodClean:
1684 case kBinArtMethodDirty: {
1685 bin_offset = RoundUp(bin_offset, method_alignment);
1686 break;
1687 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001688 case kBinDexCacheArray:
Vladimir Markof44d36c2017-03-14 14:18:46 +00001689 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment(target_ptr_size_));
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001690 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001691 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001692 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001693 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001694 break;
1695 }
1696 default: {
1697 // Normal alignment.
1698 }
1699 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001700 image_info.bin_slot_offsets_[i] = bin_offset;
1701 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001702 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001703 // NOTE: There may be additional padding between the bin slots and the intern table.
1704 DCHECK_EQ(image_info.image_end_,
1705 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001706 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001707
Jeff Haodcdc85b2015-12-04 14:06:18 -08001708 // Calculate image offsets.
1709 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001710 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001711 image_info.image_begin_ = global_image_begin_ + image_offset;
1712 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001713 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001714 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001715 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001716 image_offset += image_info.image_size_;
1717 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001718
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001719 // Transform each object's bin slot into an offset which will be used to do the final copy.
1720 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001721
Jeff Haodcdc85b2015-12-04 14:06:18 -08001722 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001723 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001724 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1725 i++;
1726 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001727
Mathieu Chartiere401d142015-04-22 13:56:20 -07001728 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001729 for (auto& pair : native_object_relocations_) {
1730 NativeObjectRelocation& relocation = pair.second;
1731 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001732 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001733 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001734 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001735}
1736
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001737size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001738 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001739
1740 // Do not round up any sections here that are represented by the bins since it will break
1741 // offsets.
1742
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001743 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001744 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001745 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001746
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001747 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001748 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1749 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001750 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001751
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001752 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001753 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1754 *methods_section = ImageSection(
1755 bin_slot_offsets_[kBinArtMethodClean],
1756 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1757
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001758 // IMT section.
1759 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1760 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1761
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001762 // Conflict tables section.
1763 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1764 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1765 bin_slot_sizes_[kBinIMTConflictTable]);
1766
1767 // Runtime methods section.
1768 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1769 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1770 bin_slot_sizes_[kBinRuntimeMethod]);
1771
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001772 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001773 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1774 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1775 bin_slot_sizes_[kBinDexCacheArray]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001776 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001777 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001778 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001779 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001780 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1781 cur_pos = interned_strings_section->End();
1782 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1783 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1784 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001785 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001786 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001787 cur_pos = class_table_section->End();
1788 // Image end goes right before the start of the image bitmap.
1789 return cur_pos;
1790}
1791
Vladimir Marko944da602016-02-19 12:27:55 +00001792void ImageWriter::CreateHeader(size_t oat_index) {
1793 ImageInfo& image_info = GetImageInfo(oat_index);
1794 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1795 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1796 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001797
1798 // Create the image sections.
1799 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001800 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001801
Mathieu Chartiere401d142015-04-22 13:56:20 -07001802 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001803 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001804 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001805 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001806 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001807 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001808 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001809 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001810 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1811 ++idx;
1812 }
1813 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001814 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1815 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1816 << " Image offset=" << image_info.image_offset_ << std::dec;
1817 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1818 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1819 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1820 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001821 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001822 // Store boot image info for app image so that we can relocate.
1823 uint32_t boot_image_begin = 0;
1824 uint32_t boot_image_end = 0;
1825 uint32_t boot_oat_begin = 0;
1826 uint32_t boot_oat_end = 0;
1827 gc::Heap* const heap = Runtime::Current()->GetHeap();
1828 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001829
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001830 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1831 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001832 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1833 image_end,
1834 sections,
1835 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001836 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001837 PointerToLowMemUInt32(oat_file_begin),
1838 PointerToLowMemUInt32(image_info.oat_data_begin_),
1839 PointerToLowMemUInt32(oat_data_end),
1840 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001841 boot_image_begin,
1842 boot_image_end - boot_image_begin,
1843 boot_oat_begin,
1844 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001845 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001846 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001847 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001848 image_storage_mode_,
1849 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001850}
1851
1852ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001853 auto it = native_object_relocations_.find(method);
David Sehr709b0702016-10-13 09:12:37 -07001854 CHECK(it != native_object_relocations_.end()) << ArtMethod::PrettyMethod(method) << " @ "
1855 << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001856 size_t oat_index = GetOatIndex(method->GetDexCache());
1857 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001858 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1859 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001860}
1861
Vladimir Markoad06b982016-11-17 16:38:59 +00001862class ImageWriter::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001863 public:
1864 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1865 }
1866
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001867 void VisitRoots(mirror::Object*** roots ATTRIBUTE_UNUSED,
1868 size_t count ATTRIBUTE_UNUSED,
1869 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001870 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001871 LOG(FATAL) << "Unsupported";
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001872 }
1873
1874 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1875 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001876 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001877 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001878 image_writer_->CopyReference(roots[i], roots[i]->AsMirrorPtr());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001879 }
1880 }
1881
1882 private:
1883 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001884};
1885
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001886void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
1887 for (size_t i = 0; i < ImTable::kSize; ++i) {
1888 ArtMethod* method = orig->Get(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001889 void** address = reinterpret_cast<void**>(copy->AddressOfElement(i, target_ptr_size_));
1890 CopyAndFixupPointer(address, method);
1891 DCHECK_EQ(copy->Get(i, target_ptr_size_), NativeLocationInImage(method));
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001892 }
1893}
1894
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001895void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
1896 const size_t count = orig->NumEntries(target_ptr_size_);
1897 for (size_t i = 0; i < count; ++i) {
1898 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
1899 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001900 CopyAndFixupPointer(copy->AddressOfInterfaceMethod(i, target_ptr_size_), interface_method);
1901 CopyAndFixupPointer(copy->AddressOfImplementationMethod(i, target_ptr_size_),
1902 implementation_method);
1903 DCHECK_EQ(copy->GetInterfaceMethod(i, target_ptr_size_),
1904 NativeLocationInImage(interface_method));
1905 DCHECK_EQ(copy->GetImplementationMethod(i, target_ptr_size_),
1906 NativeLocationInImage(implementation_method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001907 }
1908}
1909
Vladimir Marko944da602016-02-19 12:27:55 +00001910void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001911 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001912 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001913 for (auto& pair : native_object_relocations_) {
1914 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001915 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001916 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001917 continue;
1918 }
1919 auto* dest = image_info.image_->Begin() + relocation.offset;
1920 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001921 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001922 switch (relocation.type) {
1923 case kNativeObjectRelocationTypeArtField: {
1924 memcpy(dest, pair.first, sizeof(ArtField));
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001925 CopyReference(
1926 reinterpret_cast<ArtField*>(dest)->GetDeclaringClassAddressWithoutBarrier(),
1927 reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass().Ptr());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001928 break;
1929 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001930 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001931 case kNativeObjectRelocationTypeArtMethodClean:
1932 case kNativeObjectRelocationTypeArtMethodDirty: {
1933 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001934 reinterpret_cast<ArtMethod*>(dest),
1935 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001936 break;
1937 }
1938 // For arrays, copy just the header since the elements will get copied by their corresponding
1939 // relocations.
1940 case kNativeObjectRelocationTypeArtFieldArray: {
1941 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1942 break;
1943 }
1944 case kNativeObjectRelocationTypeArtMethodArrayClean:
1945 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00001946 size_t size = ArtMethod::Size(target_ptr_size_);
1947 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1948 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1949 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1950 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001951 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00001952 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001953 case kNativeObjectRelocationTypeDexCacheArray:
1954 // Nothing to copy here, everything is done in FixupDexCache().
1955 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001956 case kNativeObjectRelocationTypeIMTable: {
1957 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
1958 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
1959 CopyAndFixupImTable(orig_imt, dest_imt);
1960 break;
1961 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001962 case kNativeObjectRelocationTypeIMTConflictTable: {
1963 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
1964 CopyAndFixupImtConflictTable(
1965 orig_table,
1966 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
1967 break;
1968 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001969 }
1970 }
1971 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001972 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001973 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001974 ArtMethod* method = image_methods_[i];
1975 CHECK(method != nullptr);
1976 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001977 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001978 }
1979 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001980 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001981 FixupRootVisitor root_visitor(this);
1982
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001983 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001984 if (image_info.intern_table_bytes_ > 0) {
1985 const ImageSection& intern_table_section = image_header->GetImageSection(
1986 ImageHeader::kSectionInternedStrings);
1987 InternTable* const intern_table = image_info.intern_table_.get();
1988 uint8_t* const intern_table_memory_ptr =
1989 image_info.image_->Begin() + intern_table_section.Offset();
1990 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1991 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1992 // Fixup the pointers in the newly written intern table to contain image addresses.
1993 InternTable temp_intern_table;
1994 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1995 // the VisitRoots() will update the memory directly rather than the copies.
1996 // This also relies on visit roots not doing any verification which could fail after we update
1997 // the roots to be the image addresses.
1998 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1999 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
2000 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
2001 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002002 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
2003 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002004 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002005 const ImageSection& class_table_section = image_header->GetImageSection(
2006 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002007 uint8_t* const class_table_memory_ptr =
2008 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002009 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002010
2011 ClassTable* table = image_info.class_table_.get();
2012 CHECK(table != nullptr);
2013 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
2014 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
2015 // Fixup the pointers in the newly written class table to contain image addresses. See
2016 // above comment for intern tables.
2017 ClassTable temp_class_table;
2018 temp_class_table.ReadFromMemory(class_table_memory_ptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002019 CHECK_EQ(temp_class_table.NumReferencedZygoteClasses(),
2020 table->NumReferencedNonZygoteClasses() + table->NumReferencedZygoteClasses());
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002021 UnbufferedRootVisitor visitor(&root_visitor, RootInfo(kRootUnknown));
2022 temp_class_table.VisitRoots(visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002023 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002024}
2025
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08002026void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002027 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002028 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
2029 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002030 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08002031 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07002032 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
2033 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002034 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002035 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002036}
2037
Mathieu Chartier590fee92013-09-13 13:46:47 -07002038void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07002039 DCHECK(obj != nullptr);
2040 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002041 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
2042}
2043
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002044void ImageWriter::FixupPointerArray(mirror::Object* dst,
2045 mirror::PointerArray* arr,
2046 mirror::Class* klass,
2047 Bin array_type) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002048 CHECK(klass->IsArrayClass());
David Sehr709b0702016-10-13 09:12:37 -07002049 CHECK(arr->IsIntArray() || arr->IsLongArray()) << klass->PrettyClass() << " " << arr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002050 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07002051 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002052 dst->SetClass(GetImageAddress(arr->GetClass()));
2053 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002054 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002055 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002056 if (kIsDebugBuild && elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002057 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01002058 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002059 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002060 auto* method = reinterpret_cast<ArtMethod*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07002061 LOG(FATAL) << "No relocation entry for ArtMethod " << method->PrettyMethod() << " @ "
2062 << method << " idx=" << i << "/" << num_elements << " with declaring class "
2063 << Class::PrettyClass(method->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002064 } else {
2065 CHECK_EQ(array_type, kBinArtField);
2066 auto* field = reinterpret_cast<ArtField*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07002067 LOG(FATAL) << "No relocation entry for ArtField " << field->PrettyField() << " @ "
Mathieu Chartiere401d142015-04-22 13:56:20 -07002068 << field << " idx=" << i << "/" << num_elements << " with declaring class "
David Sehr709b0702016-10-13 09:12:37 -07002069 << Class::PrettyClass(field->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002070 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002071 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002072 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002073 }
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002074 CopyAndFixupPointer(dest_array->ElementAddress(i, target_ptr_size_), elem);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002075 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002076}
2077
2078void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002079 if (IsInBootImage(obj)) {
2080 return;
2081 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002082 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00002083 size_t oat_index = GetOatIndex(obj);
2084 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002085 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
2086 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002087 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002088
Jeff Haodcdc85b2015-12-04 14:06:18 -08002089 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002090
2091 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002092 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002093 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002094
Mathieu Chartierad2541a2013-10-25 10:05:23 -07002095 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
2096 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002097 const auto it = saved_hashcode_map_.find(obj);
2098 dst->SetLockWord(it != saved_hashcode_map_.end() ?
2099 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002100 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
2101 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
2102 // safe since we mark all of the objects that may reference non immune objects as gray.
2103 CHECK(dst->AtomicSetMarkBit(0, 1));
2104 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002105 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002106}
2107
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002108// Rewrite all the references in the copied object to point to their image address equivalent
Vladimir Markoad06b982016-11-17 16:38:59 +00002109class ImageWriter::FixupVisitor {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002110 public:
2111 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
2112 }
2113
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002114 // Ignore class roots since we don't have a way to map them to the destination. These are handled
2115 // with other logic.
2116 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
2117 const {}
2118 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
2119
2120
Mathieu Chartier31e88222016-10-14 18:43:19 -07002121 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002122 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07002123 ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002124 // Copy the reference and record the fixup if necessary.
2125 image_writer_->CopyReference(
2126 copy_->GetFieldObjectReferenceAddr<kVerifyNone>(offset),
2127 ref.Ptr());
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002128 }
2129
2130 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07002131 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2132 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002133 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002134 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002135 }
2136
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002137 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002138 ImageWriter* const image_writer_;
2139 mirror::Object* const copy_;
2140};
2141
Vladimir Markoad06b982016-11-17 16:38:59 +00002142class ImageWriter::FixupClassVisitor FINAL : public FixupVisitor {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002143 public:
2144 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
2145 }
2146
Mathieu Chartier31e88222016-10-14 18:43:19 -07002147 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07002148 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002149 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002150 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002151 }
2152
Mathieu Chartier31e88222016-10-14 18:43:19 -07002153 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2154 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002155 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002156 LOG(FATAL) << "Reference not expected here.";
2157 }
2158};
2159
Vladimir Marko05792b92015-08-03 11:56:49 +01002160uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
2161 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002162 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002163 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002164 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
2165 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002166 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01002167 return relocation.offset;
2168}
2169
2170template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002171std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002172 std::ostringstream oss;
2173 oss << ptr;
2174 return oss.str();
2175}
2176
2177template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002178std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07002179 return ArtMethod::PrettyMethod(method);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002180}
2181
2182template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002183T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002184 if (obj == nullptr || IsInBootImage(obj)) {
2185 return obj;
2186 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002187 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002188 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
2189 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002190 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00002191 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002192 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002193 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002194}
2195
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002196template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08002197T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
2198 if (obj == nullptr || IsInBootImage(obj)) {
2199 return obj;
2200 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002201 size_t oat_index = GetOatIndexForDexCache(dex_cache);
2202 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002203 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
2204 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002205}
2206
Vladimir Markoad06b982016-11-17 16:38:59 +00002207class ImageWriter::NativeLocationVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002208 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002209 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002210
2211 template <typename T>
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002212 T* operator()(T* ptr, void** dest_addr = nullptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
2213 if (dest_addr != nullptr) {
2214 image_writer_->CopyAndFixupPointer(dest_addr, ptr);
2215 }
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002216 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002217 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002218
2219 private:
2220 ImageWriter* const image_writer_;
2221};
2222
2223void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002224 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002225 FixupClassVisitor visitor(this, copy);
Mathieu Chartier31e88222016-10-14 18:43:19 -07002226 ObjPtr<mirror::Object>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002227
2228 // Remove the clinitThreadId. This is required for image determinism.
2229 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002230}
2231
Ian Rogersef7d42f2014-01-06 12:55:46 -08002232void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002233 DCHECK(orig != nullptr);
2234 DCHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002235 if (kUseBakerReadBarrier) {
2236 orig->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002237 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002238 auto* klass = orig->GetClass();
2239 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002240 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07002241 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
2242 if (it != pointer_arrays_.end()) {
2243 // Should only need to fixup every pointer array exactly once.
2244 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
2245 pointer_arrays_.erase(it);
2246 return;
2247 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002248 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002249 if (orig->IsClass()) {
2250 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002251 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002252 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
2253 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01002254 auto* dest = down_cast<mirror::Executable*>(copy);
2255 auto* src = down_cast<mirror::Executable*>(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002256 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05002257 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01002258 } else if (!klass->IsArrayClass()) {
2259 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2260 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
2261 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002262 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002263 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002264 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2265 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002266 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002267 // Also set allocator to null to be safe. The allocator is created when we create the class
2268 // table. We also never expect to unload things in the image since they are held live as
2269 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002270 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002271 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002272 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002273 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002274 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002275 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002276}
2277
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002278class ImageWriter::ImageAddressVisitorForDexCacheArray {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002279 public:
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002280 explicit ImageAddressVisitorForDexCacheArray(ImageWriter* image_writer)
2281 : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002282
2283 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002284 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002285 return image_writer_->GetImageAddress(ptr);
2286 }
2287
2288 private:
2289 ImageWriter* const image_writer_;
2290};
2291
Vladimir Marko05792b92015-08-03 11:56:49 +01002292void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2293 mirror::DexCache* copy_dex_cache) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002294 ImageAddressVisitorForDexCacheArray fixup_visitor(this);
Vladimir Marko05792b92015-08-03 11:56:49 +01002295 // Though the DexCache array fields are usually treated as native pointers, we set the full
2296 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2297 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2298 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002299 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002300 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002301 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002302 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002303 PointerSize::k64);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002304 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache), fixup_visitor);
Vladimir Marko05792b92015-08-03 11:56:49 +01002305 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002306 mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
Vladimir Marko05792b92015-08-03 11:56:49 +01002307 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002308 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002309 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002310 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002311 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002312 fixup_visitor);
Vladimir Marko05792b92015-08-03 11:56:49 +01002313 }
2314 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
2315 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002316 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002317 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002318 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002319 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002320 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
2321 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002322 // NativeLocationInImage also handles runtime methods since these have relocation info.
2323 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002324 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
2325 }
2326 }
Vladimir Markof44d36c2017-03-14 14:18:46 +00002327 mirror::FieldDexCacheType* orig_fields = orig_dex_cache->GetResolvedFields();
Vladimir Marko05792b92015-08-03 11:56:49 +01002328 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002329 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002330 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002331 PointerSize::k64);
Vladimir Markof44d36c2017-03-14 14:18:46 +00002332 mirror::FieldDexCacheType* copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002333 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00002334 mirror::FieldDexCachePair orig =
2335 mirror::DexCache::GetNativePairPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002336 mirror::FieldDexCachePair copy = orig;
2337 copy.object = NativeLocationInImage(orig.object);
Vladimir Markof44d36c2017-03-14 14:18:46 +00002338 mirror::DexCache::SetNativePairPtrSize(copy_fields, i, copy, target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002339 }
2340 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01002341 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
2342 if (orig_method_types != nullptr) {
2343 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodTypesOffset(),
2344 NativeLocationInImage(orig_method_types),
2345 PointerSize::k64);
2346 orig_dex_cache->FixupResolvedMethodTypes(NativeCopyLocation(orig_method_types, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002347 fixup_visitor);
Narayan Kamath7fe56582016-10-14 18:49:12 +01002348 }
Orion Hodsonc069a302017-01-18 09:23:12 +00002349 GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
2350 if (orig_call_sites != nullptr) {
2351 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedCallSitesOffset(),
2352 NativeLocationInImage(orig_call_sites),
2353 PointerSize::k64);
2354 orig_dex_cache->FixupResolvedCallSites(NativeCopyLocation(orig_call_sites, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002355 fixup_visitor);
Orion Hodsonc069a302017-01-18 09:23:12 +00002356 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002357
2358 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2359 // compiler pointers in here will make the output non-deterministic.
2360 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002361}
2362
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002363const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2364 DCHECK_LT(type, kOatAddressCount);
2365 // If we are compiling an app image, we need to use the stubs of the boot image.
2366 if (compile_app_image_) {
2367 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002368 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002369 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2370 DCHECK(!image_spaces.empty());
2371 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002372 CHECK(oat_file != nullptr);
2373 const OatHeader& header = oat_file->GetOatHeader();
2374 switch (type) {
2375 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2376 case kOatAddressQuickGenericJNITrampoline:
2377 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2378 case kOatAddressInterpreterToInterpreterBridge:
2379 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2380 case kOatAddressInterpreterToCompiledCodeBridge:
2381 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2382 case kOatAddressJNIDlsymLookup:
2383 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2384 case kOatAddressQuickIMTConflictTrampoline:
2385 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2386 case kOatAddressQuickResolutionTrampoline:
2387 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2388 case kOatAddressQuickToInterpreterBridge:
2389 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2390 default:
2391 UNREACHABLE();
2392 }
2393 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002394 const ImageInfo& primary_image_info = GetImageInfo(0);
2395 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002396}
2397
Jeff Haodcdc85b2015-12-04 14:06:18 -08002398const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2399 const ImageInfo& image_info,
2400 bool* quick_is_interpreted) {
David Sehr709b0702016-10-13 09:12:37 -07002401 DCHECK(!method->IsResolutionMethod()) << method->PrettyMethod();
2402 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << method->PrettyMethod();
2403 DCHECK(!method->IsImtUnimplementedMethod()) << method->PrettyMethod();
2404 DCHECK(method->IsInvokable()) << method->PrettyMethod();
2405 DCHECK(!IsInBootImage(method)) << method->PrettyMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002406
2407 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2408 // trampoline.
2409
2410 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002411 const void* quick_oat_entry_point =
2412 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2413 const uint8_t* quick_code;
2414
2415 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2416 DCHECK(method->IsCopied());
2417 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2418 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2419 } else {
2420 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2421 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2422 }
2423
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002424 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002425 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2426 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002427 // We have code for a non-static or initialized method, just use the code.
2428 } else if (quick_code == nullptr && method->IsNative() &&
2429 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2430 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002431 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002432 } else if (quick_code == nullptr && !method->IsNative()) {
2433 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002434 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002435 *quick_is_interpreted = true;
2436 } else {
2437 CHECK(!method->GetDeclaringClass()->IsInitialized());
2438 // We have code for a static method, but need to go through the resolution stub for class
2439 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002440 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2441 }
2442 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002443 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002444 }
2445 return quick_code;
2446}
2447
Jeff Haodcdc85b2015-12-04 14:06:18 -08002448void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2449 ArtMethod* copy,
2450 const ImageInfo& image_info) {
Mingyao Yange8fcd012017-01-20 10:43:30 -08002451 if (orig->IsAbstract()) {
2452 // Ignore the single-implementation info for abstract method.
2453 // Do this on orig instead of copy, otherwise there is a crash due to methods
2454 // are copied before classes.
2455 // TODO: handle fixup of single-implementation method for abstract method.
2456 orig->SetHasSingleImplementation(false);
2457 orig->SetSingleImplementation(
2458 nullptr, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
2459 }
2460
Vladimir Marko14632852015-08-17 12:07:23 +01002461 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002462
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002463 CopyReference(copy->GetDeclaringClassAddressWithoutBarrier(), orig->GetDeclaringClassUnchecked());
2464
Vladimir Marko05792b92015-08-03 11:56:49 +01002465 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002466 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002467
Ian Rogers848871b2013-08-05 10:56:33 -07002468 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2469 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002470
Ian Rogers848871b2013-08-05 10:56:33 -07002471 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002472 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002473 if (orig->IsRuntimeMethod()) {
2474 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2475 if (orig_table != nullptr) {
2476 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2477 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2478 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2479 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2480 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2481 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2482 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2483 } else {
2484 bool found_one = false;
2485 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2486 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2487 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2488 found_one = true;
2489 break;
2490 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002491 }
David Sehr709b0702016-10-13 09:12:37 -07002492 CHECK(found_one) << "Expected to find callee save method but got " << orig->PrettyMethod();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002493 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002494 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002495 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002496 // We assume all methods have code. If they don't currently then we set them to the use the
2497 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2498 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002499 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002500 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002501 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002502 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002503 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002504 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002505 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002506
Sebastien Hertze1d07812014-05-21 15:44:09 +02002507 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002508 if (orig->IsNative()) {
2509 // The native method's pointer is set to a stub to lookup via dlsym.
2510 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002511 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002512 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002513 }
2514 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002515 }
2516}
2517
Jeff Haodcdc85b2015-12-04 14:06:18 -08002518size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002519 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002520 return std::accumulate(&image_info.bin_slot_sizes_[0],
2521 &image_info.bin_slot_sizes_[up_to],
2522 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002523}
2524
2525ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2526 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002527 static_assert(kBinBits == 3, "wrong number of bin bits");
2528 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002529 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2530
2531 DCHECK_LT(GetBin(), kBinSize);
2532 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2533}
2534
2535ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2536 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2537 DCHECK_EQ(index, GetIndex());
2538}
2539
2540ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2541 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2542}
2543
2544uint32_t ImageWriter::BinSlot::GetIndex() const {
2545 return lockword_ & ~kBinMask;
2546}
2547
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002548ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2549 switch (type) {
2550 case kNativeObjectRelocationTypeArtField:
2551 case kNativeObjectRelocationTypeArtFieldArray:
2552 return kBinArtField;
2553 case kNativeObjectRelocationTypeArtMethodClean:
2554 case kNativeObjectRelocationTypeArtMethodArrayClean:
2555 return kBinArtMethodClean;
2556 case kNativeObjectRelocationTypeArtMethodDirty:
2557 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2558 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002559 case kNativeObjectRelocationTypeDexCacheArray:
2560 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002561 case kNativeObjectRelocationTypeRuntimeMethod:
2562 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002563 case kNativeObjectRelocationTypeIMTable:
2564 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002565 case kNativeObjectRelocationTypeIMTConflictTable:
2566 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002567 }
2568 UNREACHABLE();
2569}
2570
Vladimir Marko944da602016-02-19 12:27:55 +00002571size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002572 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002573 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002574 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002575 auto it = oat_index_map_.find(obj);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002576 DCHECK(it != oat_index_map_.end()) << obj;
Mathieu Chartier496577f2016-09-20 15:33:31 -07002577 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002578}
2579
Vladimir Marko944da602016-02-19 12:27:55 +00002580size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002581 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002582 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002583 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002584 auto it = dex_file_oat_index_map_.find(dex_file);
2585 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2586 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002587}
2588
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002589size_t ImageWriter::GetOatIndexForDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
2590 return (dex_cache == nullptr)
2591 ? GetDefaultOatIndex()
2592 : GetOatIndexForDexFile(dex_cache->GetDexFile());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002593}
2594
Vladimir Marko944da602016-02-19 12:27:55 +00002595void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2596 size_t oat_loaded_size,
2597 size_t oat_data_offset,
2598 size_t oat_data_size) {
2599 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2600 for (const ImageInfo& info : image_infos_) {
2601 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2602 }
2603 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002604
Vladimir Marko944da602016-02-19 12:27:55 +00002605 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2606 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2607 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2608 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2609 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002610
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002611 if (compile_app_image_) {
2612 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2613 return;
2614 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002615
2616 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002617 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002618 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002619 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002620 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2621 }
2622}
2623
Vladimir Marko944da602016-02-19 12:27:55 +00002624void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2625 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2626 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2627
2628 if (oat_index == GetDefaultOatIndex()) {
2629 // Primary oat file, read the trampolines.
2630 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2631 oat_header.GetInterpreterToInterpreterBridgeOffset();
2632 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2633 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2634 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2635 oat_header.GetJniDlsymLookupOffset();
2636 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2637 oat_header.GetQuickGenericJniTrampolineOffset();
2638 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2639 oat_header.GetQuickImtConflictTrampolineOffset();
2640 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2641 oat_header.GetQuickResolutionTrampolineOffset();
2642 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2643 oat_header.GetQuickToInterpreterBridgeOffset();
2644 }
2645}
2646
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002647ImageWriter::ImageWriter(
2648 const CompilerDriver& compiler_driver,
2649 uintptr_t image_begin,
2650 bool compile_pic,
2651 bool compile_app_image,
2652 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002653 const std::vector<const char*>& oat_filenames,
2654 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002655 : compiler_driver_(compiler_driver),
2656 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2657 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002658 compile_pic_(compile_pic),
2659 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002660 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002661 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002662 dirty_methods_(0u),
2663 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002664 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002665 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002666 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002667 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002668 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002669 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2670 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002671}
2672
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002673ImageWriter::ImageInfo::ImageInfo()
2674 : intern_table_(new InternTable),
2675 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002676
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002677void ImageWriter::CopyReference(mirror::HeapReference<mirror::Object>* dest,
2678 ObjPtr<mirror::Object> src) {
2679 dest->Assign(GetImageAddress(src.Ptr()));
2680}
2681
2682void ImageWriter::CopyReference(mirror::CompressedReference<mirror::Object>* dest,
2683 ObjPtr<mirror::Object> src) {
2684 dest->Assign(GetImageAddress(src.Ptr()));
2685}
2686
2687void ImageWriter::CopyAndFixupPointer(void** target, void* value) {
2688 void* new_value = value;
2689 if (value != nullptr && !IsInBootImage(value)) {
2690 auto it = native_object_relocations_.find(value);
2691 CHECK(it != native_object_relocations_.end()) << value;
2692 const NativeObjectRelocation& relocation = it->second;
2693 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2694 new_value = reinterpret_cast<void*>(image_info.image_begin_ + relocation.offset);
2695 }
2696 if (target_ptr_size_ == PointerSize::k32) {
2697 *reinterpret_cast<uint32_t*>(target) = PointerToLowMemUInt32(new_value);
2698 } else {
2699 *reinterpret_cast<uint64_t*>(target) = reinterpret_cast<uintptr_t>(new_value);
2700 }
2701}
2702
2703
Brian Carlstrom7940e442013-07-12 13:46:57 -07002704} // namespace art