blob: 65d82ed9805edd109eea109480bb4361b262349c [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"
62#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070063#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "oat.h"
65#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070066#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070068#include "scoped_thread_state_change-inl.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070069#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000070#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070071
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070072using ::art::mirror::Class;
73using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070074using ::art::mirror::Object;
75using ::art::mirror::ObjectArray;
76using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070077
78namespace art {
79
Igor Murashkinf5b4c502014-11-14 15:01:59 -080080// Separate objects into multiple bins to optimize dirty memory use.
81static constexpr bool kBinObjects = true;
82
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080083// Return true if an object is already in an image space.
84bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080085 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080086 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080087 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080088 return false;
89 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080090 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
91 const uint8_t* image_begin = boot_image_space->Begin();
92 // Real image end including ArtMethods and ArtField sections.
93 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
94 if (image_begin <= obj && obj < image_end) {
95 return true;
96 }
97 }
98 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080099}
100
101bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800102 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800103 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800104 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800105 return false;
106 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800107 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
108 const ImageHeader& image_header = boot_image_space->GetImageHeader();
109 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
110 return true;
111 }
112 }
113 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800114}
115
Andreas Gampedd9d0552015-03-09 12:57:41 -0700116static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700117 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700118 Class* klass = obj->GetClass();
David Sehr709b0702016-10-13 09:12:37 -0700119 CHECK_NE(Class::PrettyClass(klass), "com.android.dex.Dex");
Andreas Gampedd9d0552015-03-09 12:57:41 -0700120}
121
122static void CheckNoDexObjects() {
123 ScopedObjectAccess soa(Thread::Current());
124 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
125}
126
Vladimir Markof4da6752014-08-01 19:04:18 +0100127bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800128 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800129 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100130 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700131 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100132 PruneNonImageClasses(); // Remove junk
Mathieu Chartier901e0702016-02-19 13:42:48 -0800133 if (!compile_app_image_) {
134 // Avoid for app image since this may increase RAM and image size.
135 ComputeLazyFieldsForImageClasses(); // Add useful information
136 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100137 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100138 heap->CollectGarbage(false); // Remove garbage.
139
Andreas Gampedd9d0552015-03-09 12:57:41 -0700140 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
141 // dex files.
142 //
143 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
144 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
145 // true.
146 if (kIsDebugBuild) {
147 CheckNoDexObjects();
148 }
149
Vladimir Markof4da6752014-08-01 19:04:18 +0100150 if (kIsDebugBuild) {
151 ScopedObjectAccess soa(Thread::Current());
152 CheckNonImageClassesRemoved();
153 }
154
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700155 {
156 ScopedObjectAccess soa(Thread::Current());
157 CalculateNewObjectOffsets();
158 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100159
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700160 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
161 // bin size sums being calculated.
162 if (!AllocMemory()) {
163 return false;
164 }
165
Vladimir Markof4da6752014-08-01 19:04:18 +0100166 return true;
167}
168
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700169bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800170 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000171 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800172 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
173 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800174 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800175 if (image_fd != kInvalidFd) {
176 CHECK_EQ(image_filenames.size(), 1u);
177 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800178 CHECK(!oat_filenames.empty());
179 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700180
Vladimir Marko944da602016-02-19 12:27:55 +0000181 {
182 ScopedObjectAccess soa(Thread::Current());
183 for (size_t i = 0; i < oat_filenames.size(); ++i) {
184 CreateHeader(i);
185 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800186 }
187 }
Alex Light53cb16b2014-06-12 11:26:29 -0700188
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700189 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700190 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800191 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700192 Runtime::Current()->GetHeap()->DisableObjectValidation();
193 CopyAndFixupObjects();
194 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700195
Jeff Haodcdc85b2015-12-04 14:06:18 -0800196 for (size_t i = 0; i < image_filenames.size(); ++i) {
197 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000198 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800199 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800200 if (image_fd != kInvalidFd) {
201 if (strlen(image_filename) == 0u) {
202 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800203 // Empty the file in case it already exists.
204 if (image_file != nullptr) {
205 TEMP_FAILURE_RETRY(image_file->SetLength(0));
206 TEMP_FAILURE_RETRY(image_file->Flush());
207 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800208 } else {
209 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
210 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800211 } else {
212 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800213 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800214
Jeff Haodcdc85b2015-12-04 14:06:18 -0800215 if (image_file == nullptr) {
216 LOG(ERROR) << "Failed to open image file " << image_filename;
217 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800218 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800219
220 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800221 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
222 image_file->Erase();
223 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800224 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800225
Jeff Haodcdc85b2015-12-04 14:06:18 -0800226 std::unique_ptr<char[]> compressed_data;
227 // Image data size excludes the bitmap and the header.
228 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
229 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
230 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
231 size_t data_size;
232 const char* image_data_to_write;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800233 const uint64_t compress_start_time = NanoTime();
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000234
Jeff Haodcdc85b2015-12-04 14:06:18 -0800235 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
236 switch (image_storage_mode_) {
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700237 case ImageHeader::kStorageModeLZ4HC: // Fall-through.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800238 case ImageHeader::kStorageModeLZ4: {
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800239 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800240 compressed_data.reset(new char[compressed_max_size]);
David Lin915ec552017-02-23 15:36:06 -0800241 data_size = LZ4_compress_default(
Jeff Haodcdc85b2015-12-04 14:06:18 -0800242 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
243 &compressed_data[0],
David Lin915ec552017-02-23 15:36:06 -0800244 image_data_size,
245 compressed_max_size);
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800246
247 break;
248 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700249 /*
250 * Disabled due to image_test64 flakyness. Both use same decompression. b/27560444
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800251 case ImageHeader::kStorageModeLZ4HC: {
252 // Bound is same as non HC.
253 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
254 compressed_data.reset(new char[compressed_max_size]);
255 data_size = LZ4_compressHC(
256 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
257 &compressed_data[0],
258 image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800259 break;
260 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700261 */
Jeff Haodcdc85b2015-12-04 14:06:18 -0800262 case ImageHeader::kStorageModeUncompressed: {
263 data_size = image_data_size;
264 image_data_to_write = image_data;
265 break;
266 }
267 default: {
268 LOG(FATAL) << "Unsupported";
269 UNREACHABLE();
270 }
271 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800272
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800273 if (compressed_data != nullptr) {
274 image_data_to_write = &compressed_data[0];
275 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
276 << PrettyDuration(NanoTime() - compress_start_time);
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700277 if (kIsDebugBuild) {
278 std::unique_ptr<uint8_t[]> temp(new uint8_t[image_data_size]);
279 const size_t decompressed_size = LZ4_decompress_safe(
280 reinterpret_cast<char*>(&compressed_data[0]),
281 reinterpret_cast<char*>(&temp[0]),
282 data_size,
283 image_data_size);
284 CHECK_EQ(decompressed_size, image_data_size);
285 CHECK_EQ(memcmp(image_data, &temp[0], image_data_size), 0) << image_storage_mode_;
286 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800287 }
288
Jeff Haodcdc85b2015-12-04 14:06:18 -0800289 // Write out the image + fields + methods.
290 const bool is_compressed = compressed_data != nullptr;
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800291 if (!image_file->PwriteFully(image_data_to_write, data_size, sizeof(ImageHeader))) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800292 PLOG(ERROR) << "Failed to write image file data " << image_filename;
293 image_file->Erase();
294 return false;
295 }
296
297 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
298 // convenience.
299 const ImageSection& bitmap_section = image_header->GetImageSection(
300 ImageHeader::kSectionImageBitmap);
301 // Align up since data size may be unaligned if the image is compressed.
302 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
303 if (!is_compressed) {
304 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
305 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800306 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
307 bitmap_section.Size(),
308 bitmap_position_in_file)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800309 PLOG(ERROR) << "Failed to write image file " << image_filename;
310 image_file->Erase();
311 return false;
312 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800313
314 int err = image_file->Flush();
315 if (err < 0) {
316 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
317 image_file->Erase();
318 return false;
319 }
320
321 // Write header last in case the compiler gets killed in the middle of image writing.
322 // We do not want to have a corrupted image with a valid header.
323 // The header is uncompressed since it contains whether the image is compressed or not.
324 image_header->data_size_ = data_size;
325 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
326 sizeof(ImageHeader),
327 0)) {
328 PLOG(ERROR) << "Failed to write image file header " << image_filename;
329 image_file->Erase();
330 return false;
331 }
332
Jeff Haodcdc85b2015-12-04 14:06:18 -0800333 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
334 static_cast<size_t>(image_file->GetLength()));
335 if (image_file->FlushCloseOrErase() != 0) {
336 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
337 return false;
338 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800339 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700340 return true;
341}
342
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700343void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700344 DCHECK(object != nullptr);
345 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800346
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800347 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700348 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700349 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700350 DCHECK(IsImageOffsetAssigned(object));
351}
352
Mathieu Chartiere401d142015-04-22 13:56:20 -0700353void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
354 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
355 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
356 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
357}
358
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800359void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700360 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800361 DCHECK_NE(image_objects_offset_begin_, 0u);
362
Vladimir Marko944da602016-02-19 12:27:55 +0000363 size_t oat_index = GetOatIndex(object);
364 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800365 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100366 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800367 DCHECK_ALIGNED(new_offset, kObjectAlignment);
368
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700369 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800370 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700371}
372
Ian Rogersef7d42f2014-01-06 12:55:46 -0800373bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800374 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700375 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700376 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700377}
378
Ian Rogersef7d42f2014-01-06 12:55:46 -0800379size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700380 DCHECK(object != nullptr);
381 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700382 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700383 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000384 size_t oat_index = GetOatIndex(object);
385 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800386 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700387 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700388}
389
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800390void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
391 DCHECK(object != nullptr);
392 DCHECK(!IsImageOffsetAssigned(object));
393 DCHECK(!IsImageBinSlotAssigned(object));
394
395 // Before we stomp over the lock word, save the hash code for later.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800396 LockWord lw(object->GetLockWord(false));
397 switch (lw.GetState()) {
398 case LockWord::kFatLocked: {
399 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
400 break;
401 }
402 case LockWord::kThinLocked: {
403 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
404 break;
405 }
406 case LockWord::kUnlocked:
407 // No hash, don't need to save it.
408 break;
409 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700410 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
411 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800412 break;
413 default:
414 LOG(FATAL) << "Unreachable.";
415 UNREACHABLE();
416 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700417 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700418 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800419 DCHECK(IsImageBinSlotAssigned(object));
420}
421
Vladimir Marko20f85592015-03-19 10:07:02 +0000422void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000423 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000424 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
425 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800426 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000427 auto it = dex_file_oat_index_map_.find(dex_file);
428 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800429 ImageInfo& image_info = GetImageInfo(it->second);
430 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
431 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
432 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
433 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000434
Vladimir Marko20f85592015-03-19 10:07:02 +0000435 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700436 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -0800437 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800438 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700439 ObjPtr<mirror::DexCache> dex_cache =
440 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
441 if (dex_cache == nullptr || IsInBootImage(dex_cache.Ptr())) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700442 continue;
443 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000444 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartier0b490842016-05-25 15:05:59 -0700445 CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
446 << "Dex cache should have been pruned " << dex_file->GetLocation()
447 << "; possibly in class path";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700448 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000449 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000450 size_t oat_index = GetOatIndexForDexCache(dex_cache);
451 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800452 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100453 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800454 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
455 start + layout.TypesOffset(),
456 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100457 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800458 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
459 start + layout.MethodsOffset(),
460 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100461 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800462 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
463 start + layout.FieldsOffset(),
464 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100465 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800466 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Narayan Kamath7fe56582016-10-14 18:49:12 +0100467
468 if (dex_cache->GetResolvedMethodTypes() != nullptr) {
469 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethodTypes(),
470 start + layout.MethodTypesOffset(),
471 dex_cache);
472 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000473 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000474}
475
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700476void ImageWriter::AddDexCacheArrayRelocation(void* array,
477 size_t offset,
478 ObjPtr<mirror::DexCache> dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100479 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800480 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000481 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800482 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000483 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100484 }
485}
486
Mathieu Chartiere401d142015-04-22 13:56:20 -0700487void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
488 DCHECK(arr != nullptr);
489 if (kIsDebugBuild) {
490 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800491 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700492 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800493 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800494 CHECK(klass == nullptr || KeepClass(klass))
David Sehr709b0702016-10-13 09:12:37 -0700495 << Class::PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700496 }
497 }
498 }
499 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
500 // ArtMethods.
501 pointer_arrays_.emplace(arr, kBinArtMethodClean);
502}
503
Mathieu Chartier496577f2016-09-20 15:33:31 -0700504void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800505 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800506 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800507
508 // The magic happens here. We segregate objects into different bins based
509 // on how likely they are to get dirty at runtime.
510 //
511 // Likely-to-dirty objects get packed together into the same bin so that
512 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
513 // maximized.
514 //
515 // This means more pages will stay either clean or shared dirty (with zygote) and
516 // the app will use less of its own (private) memory.
517 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000518 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800519
520 if (kBinObjects) {
521 //
522 // Changing the bin of an object is purely a memory-use tuning.
523 // It has no change on runtime correctness.
524 //
525 // Memory analysis has determined that the following types of objects get dirtied
526 // the most:
527 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000528 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
529 // a fixed layout which helps improve generated code (using PC-relative addressing),
530 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
531 // Since these arrays are huge, most pages do not overlap other objects and it's not
532 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100533 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800534 // * Class'es which are verified [their clinit runs only at runtime]
535 // - classes in general [because their static fields get overwritten]
536 // - initialized classes with all-final statics are unlikely to be ever dirty,
537 // so bin them separately
538 // * Art Methods that are:
539 // - native [their native entry point is not looked up until runtime]
540 // - have declaring classes that aren't initialized
541 // [their interpreter/quick entry points are trampolines until the class
542 // becomes initialized]
543 //
544 // We also assume the following objects get dirtied either never or extremely rarely:
545 // * Strings (they are immutable)
546 // * Art methods that aren't native and have initialized declared classes
547 //
548 // We assume that "regular" bin objects are highly unlikely to become dirtied,
549 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
550 //
551 if (object->IsClass()) {
552 bin = kBinClassVerified;
553 mirror::Class* klass = object->AsClass();
554
Mathieu Chartiere401d142015-04-22 13:56:20 -0700555 // Add non-embedded vtable to the pointer array table if there is one.
556 auto* vtable = klass->GetVTable();
557 if (vtable != nullptr) {
558 AddMethodPointerArray(vtable);
559 }
560 auto* iftable = klass->GetIfTable();
561 if (iftable != nullptr) {
562 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
563 if (iftable->GetMethodArrayCount(i) > 0) {
564 AddMethodPointerArray(iftable->GetMethodArray(i));
565 }
566 }
567 }
568
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800569 if (klass->GetStatus() == Class::kStatusInitialized) {
570 bin = kBinClassInitialized;
571
572 // If the class's static fields are all final, put it into a separate bin
573 // since it's very likely it will stay clean.
574 uint32_t num_static_fields = klass->NumStaticFields();
575 if (num_static_fields == 0) {
576 bin = kBinClassInitializedFinalStatics;
577 } else {
578 // Maybe all the statics are final?
579 bool all_final = true;
580 for (uint32_t i = 0; i < num_static_fields; ++i) {
581 ArtField* field = klass->GetStaticField(i);
582 if (!field->IsFinal()) {
583 all_final = false;
584 break;
585 }
586 }
587
588 if (all_final) {
589 bin = kBinClassInitializedFinalStatics;
590 }
591 }
592 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800593 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
594 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700595 } else if (object->GetClass<kVerifyNone>() ==
596 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
597 // Instance of java lang object, probably a lock object. This means it will be dirty when we
598 // synchronize on it.
599 bin = kBinMiscDirty;
600 } else if (object->IsDexCache()) {
601 // Dex file field becomes dirty when the image is loaded.
602 bin = kBinMiscDirty;
603 }
604 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800605 }
606
Mathieu Chartier496577f2016-09-20 15:33:31 -0700607 // Assign the oat index too.
608 DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
609 oat_index_map_.emplace(object, oat_index);
610
Vladimir Marko944da602016-02-19 12:27:55 +0000611 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800612
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800613 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800614 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
615 // Move the current bin size up to accommodate the object we just assigned a bin slot.
616 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800617
618 BinSlot new_bin_slot(bin, current_offset);
619 SetImageBinSlot(object, new_bin_slot);
620
Jeff Haodcdc85b2015-12-04 14:06:18 -0800621 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800622
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800623 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800624 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800625}
626
Mathieu Chartiere401d142015-04-22 13:56:20 -0700627bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
628 if (m->IsNative()) {
629 return true;
630 }
631 mirror::Class* declaring_class = m->GetDeclaringClass();
632 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
633 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
634}
635
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800636bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
637 DCHECK(object != nullptr);
638
639 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
640 // If it's in some other state, then we haven't yet assigned an image bin slot.
641 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
642 return false;
643 } else if (kIsDebugBuild) {
644 LockWord lock_word = object->GetLockWord(false);
645 size_t offset = lock_word.ForwardingAddress();
646 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000647 size_t oat_index = GetOatIndex(object);
648 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800649 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800650 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800651 }
652 return true;
653}
654
655ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
656 DCHECK(object != nullptr);
657 DCHECK(IsImageBinSlotAssigned(object));
658
659 LockWord lock_word = object->GetLockWord(false);
660 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
661 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
662
663 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000664 size_t oat_index = GetOatIndex(object);
665 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800666 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800667
668 return bin_slot;
669}
670
Brian Carlstrom7940e442013-07-12 13:46:57 -0700671bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000672 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800673 ImageSection unused_sections[ImageHeader::kSectionCount];
674 const size_t length = RoundUp(
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700675 image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800676
Jeff Haodcdc85b2015-12-04 14:06:18 -0800677 std::string error_msg;
678 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
679 nullptr,
680 length,
681 PROT_READ | PROT_WRITE,
682 false,
683 false,
684 &error_msg));
685 if (UNLIKELY(image_info.image_.get() == nullptr)) {
686 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
687 return false;
688 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700689
Jeff Haodcdc85b2015-12-04 14:06:18 -0800690 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
691 CHECK_LE(image_info.image_end_, length);
692 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
693 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
694 if (image_info.image_bitmap_.get() == nullptr) {
695 LOG(ERROR) << "Failed to allocate memory for image bitmap";
696 return false;
697 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700698 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700699 return true;
700}
701
Vladimir Markoad06b982016-11-17 16:38:59 +0000702class ImageWriter::ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700703 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700704 bool operator()(ObjPtr<Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700705 StackHandleScope<1> hs(Thread::Current());
706 mirror::Class::ComputeName(hs.NewHandle(c));
707 return true;
708 }
709};
710
Brian Carlstrom7940e442013-07-12 13:46:57 -0700711void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700712 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700713 ComputeLazyFieldsForClassesVisitor visitor;
714 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700715}
716
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700717static bool IsBootClassLoaderClass(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800718 return klass->GetClassLoader() == nullptr;
719}
720
721bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
722 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
723}
724
Mathieu Chartier901e0702016-02-19 13:42:48 -0800725bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800726 bool early_exit = false;
727 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800728 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800729}
730
Mathieu Chartier901e0702016-02-19 13:42:48 -0800731bool ImageWriter::PruneAppImageClassInternal(
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800732 mirror::Class* klass,
733 bool* early_exit,
734 std::unordered_set<mirror::Class*>* visited) {
735 DCHECK(early_exit != nullptr);
736 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800737 DCHECK(compile_app_image_);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800738 if (klass == nullptr || IsInBootImage(klass)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700739 return false;
740 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800741 auto found = prune_class_memo_.find(klass);
742 if (found != prune_class_memo_.end()) {
743 // Already computed, return the found value.
744 return found->second;
745 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800746 // Circular dependencies, return false but do not store the result in the memoization table.
747 if (visited->find(klass) != visited->end()) {
748 *early_exit = true;
749 return false;
750 }
751 visited->emplace(klass);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800752 bool result = IsBootClassLoaderClass(klass);
753 std::string temp;
754 // Prune if not an image class, this handles any broken sets of image classes such as having a
755 // class in the set but not it's superclass.
756 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800757 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800758 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
759 // app image.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000760 if (klass->IsErroneous()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800761 result = true;
762 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700763 ObjPtr<mirror::ClassExt> ext(klass->GetExtData());
764 CHECK(ext.IsNull() || ext->GetVerifyError() == nullptr) << klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800765 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800766 if (!result) {
767 // Check interfaces since these wont be visited through VisitReferences.)
768 mirror::IfTable* if_table = klass->GetIfTable();
769 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800770 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
771 &my_early_exit,
772 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800773 }
774 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800775 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800776 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
777 &my_early_exit,
778 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800779 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800780 // Check static fields and their classes.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000781 if (klass->IsResolved() && klass->NumReferenceStaticFields() != 0) {
782 size_t num_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800783 // Presumably GC can happen when we are cross compiling, it should not cause performance
784 // problems to do pointer size logic.
785 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
786 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
787 for (size_t i = 0u; i < num_static_fields; ++i) {
788 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
789 if (ref != nullptr) {
790 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800791 result = result || PruneAppImageClassInternal(ref->AsClass(),
792 &my_early_exit,
793 visited);
794 } else {
795 result = result || PruneAppImageClassInternal(ref->GetClass(),
796 &my_early_exit,
797 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800798 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800799 }
800 field_offset = MemberOffset(field_offset.Uint32Value() +
801 sizeof(mirror::HeapReference<mirror::Object>));
802 }
803 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800804 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
805 &my_early_exit,
806 visited);
Mathieu Chartierc27bc402016-08-05 16:09:09 -0700807 // Remove the class if the dex file is not in the set of dex files. This happens for classes that
808 // are from uses library if there is no profile. b/30688277
809 mirror::DexCache* dex_cache = klass->GetDexCache();
810 if (dex_cache != nullptr) {
811 result = result ||
812 dex_file_oat_index_map_.find(dex_cache->GetDexFile()) == dex_file_oat_index_map_.end();
813 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800814 // Erase the element we stored earlier since we are exiting the function.
815 auto it = visited->find(klass);
816 DCHECK(it != visited->end());
817 visited->erase(it);
818 // Only store result if it is true or none of the calls early exited due to circular
819 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
820 // a child call and we can remember the result.
821 if (result == true || !my_early_exit || visited->empty()) {
822 prune_class_memo_[klass] = result;
823 }
824 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800825 return result;
826}
827
828bool ImageWriter::KeepClass(Class* klass) {
829 if (klass == nullptr) {
830 return false;
831 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800832 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
833 // Already in boot image, return true.
834 return true;
835 }
836 std::string temp;
837 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
838 return false;
839 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800840 if (compile_app_image_) {
841 // For app images, we need to prune boot loader classes that are not in the boot image since
842 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800843 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800844 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800845 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800846 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700847}
848
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000849class ImageWriter::PruneClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700850 public:
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000851 PruneClassesVisitor(ImageWriter* image_writer, ObjPtr<mirror::ClassLoader> class_loader)
852 : image_writer_(image_writer),
853 class_loader_(class_loader),
854 classes_to_prune_(),
855 defined_class_count_(0u) { }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700856
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000857 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700858 if (!image_writer_->KeepClass(klass.Ptr())) {
859 classes_to_prune_.insert(klass.Ptr());
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000860 if (klass->GetClassLoader() == class_loader_) {
861 ++defined_class_count_;
862 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700863 }
864 return true;
865 }
866
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000867 size_t Prune() REQUIRES_SHARED(Locks::mutator_lock_) {
868 ClassTable* class_table =
869 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader_);
870 for (mirror::Class* klass : classes_to_prune_) {
871 std::string storage;
872 const char* descriptor = klass->GetDescriptor(&storage);
873 bool result = class_table->Remove(descriptor);
874 DCHECK(result);
875 DCHECK(!class_table->Remove(descriptor)) << descriptor;
876 }
877 return defined_class_count_;
878 }
879
880 private:
Vladimir Markocb5ab352016-11-30 15:31:13 +0000881 ImageWriter* const image_writer_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000882 const ObjPtr<mirror::ClassLoader> class_loader_;
883 std::unordered_set<mirror::Class*> classes_to_prune_;
884 size_t defined_class_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700885};
886
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000887class ImageWriter::PruneClassLoaderClassesVisitor : public ClassLoaderVisitor {
888 public:
889 explicit PruneClassLoaderClassesVisitor(ImageWriter* image_writer)
890 : image_writer_(image_writer), removed_class_count_(0) {}
891
892 virtual void Visit(ObjPtr<mirror::ClassLoader> class_loader) OVERRIDE
893 REQUIRES_SHARED(Locks::mutator_lock_) {
894 PruneClassesVisitor classes_visitor(image_writer_, class_loader);
895 ClassTable* class_table =
896 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader);
897 class_table->Visit(classes_visitor);
898 removed_class_count_ += classes_visitor.Prune();
899 }
900
901 size_t GetRemovedClassCount() const {
902 return removed_class_count_;
903 }
904
905 private:
906 ImageWriter* const image_writer_;
907 size_t removed_class_count_;
908};
909
910void ImageWriter::VisitClassLoaders(ClassLoaderVisitor* visitor) {
911 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
912 visitor->Visit(nullptr); // Visit boot class loader.
913 Runtime::Current()->GetClassLinker()->VisitClassLoaders(visitor);
914}
915
Brian Carlstrom7940e442013-07-12 13:46:57 -0700916void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700917 Runtime* runtime = Runtime::Current();
918 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700919 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700920
Mathieu Chartier696632e2016-06-03 17:47:32 -0700921 // Clear class table strong roots so that dex caches can get pruned. We require pruning the class
922 // path dex caches.
923 class_linker->ClearClassTableStrongRoots();
924
Brian Carlstrom7940e442013-07-12 13:46:57 -0700925 // Remove the undesired classes from the class roots.
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000926 {
927 PruneClassLoaderClassesVisitor class_loader_visitor(this);
928 VisitClassLoaders(&class_loader_visitor);
929 VLOG(compiler) << "Pruned " << class_loader_visitor.GetRemovedClassCount() << " classes";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700930 }
931
932 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100933 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700934
Mathieu Chartier268764d2016-09-13 12:09:38 -0700935 ScopedAssertNoThreadSuspension sa(__FUNCTION__);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700936 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
Andreas Gampecc1b5352016-12-01 16:58:38 -0800937 ReaderMutexLock mu2(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800938 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800939 if (self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700940 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700941 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700942 ObjPtr<mirror::DexCache> dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700943 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
Vladimir Markobfb80d22017-02-14 14:08:12 +0000944 mirror::TypeDexCachePair pair =
945 dex_cache->GetResolvedTypes()[i].load(std::memory_order_relaxed);
946 mirror::Class* klass = pair.object.Read();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800947 if (klass != nullptr && !KeepClass(klass)) {
Vladimir Markobfb80d22017-02-14 14:08:12 +0000948 dex_cache->ClearResolvedType(dex::TypeIndex(pair.index));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700949 }
950 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100951 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
952 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
953 ArtMethod* method =
954 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800955 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
956 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800957 // Copied methods may be held live by a class which was not an image class but have a
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800958 // declaring class which is an image class. Set it to the resolution method to be safe and
959 // prevent dangling pointers.
Alex Light36121492016-02-22 13:43:29 -0800960 if (method->IsCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800961 mirror::DexCache::SetElementPtrSize(resolved_methods,
962 i,
963 resolution_method,
964 target_ptr_size_);
965 } else {
966 // Check that the class is still in the classes table.
967 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
David Sehr709b0702016-10-13 09:12:37 -0700968 << Class::PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700969 }
970 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800971 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700972 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800973 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700974 if (field != nullptr && !KeepClass(field->GetDeclaringClass().Ptr())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700975 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700976 }
977 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700978 // Clean the dex field. It might have been populated during the initialization phase, but
979 // contains data only valid during a real run.
980 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700981 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700982
983 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
984 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800985
986 // Clear to save RAM.
Vladimir Marko2c8c6b62016-12-01 17:42:00 +0000987 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700988}
989
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800990void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700991 if (compiler_driver_.GetImageClasses() != nullptr) {
992 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700993 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700994 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700995}
996
997void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
998 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800999 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001000 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001001 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001002 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001003 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001004 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
David Sehr709b0702016-10-13 09:12:37 -07001005 << " " << klass->PrettyDescriptor();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001006 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001007 }
1008}
1009
1010void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001011 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001012 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001013 for (const std::string& image_class : *image_classes) {
1014 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001015 }
1016}
1017
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001018mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
1019 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +00001020 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001021 ObjPtr<mirror::String> const found = image_info.intern_table_->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001022 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
1023 << string->ToModifiedUtf8();
1024 if (found != nullptr) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001025 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001026 }
1027 }
1028 if (compile_app_image_) {
1029 Runtime* const runtime = Runtime::Current();
Mathieu Chartier9e868092016-10-31 14:58:04 -07001030 ObjPtr<mirror::String> found = runtime->GetInternTable()->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001031 // If we found it in the runtime intern table it could either be in the boot image or interned
1032 // during app image compilation. If it was in the boot image return that, otherwise return null
1033 // since it belongs to another image space.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001034 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found.Ptr())) {
1035 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001036 }
1037 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
1038 << string->ToModifiedUtf8();
1039 }
1040 return nullptr;
1041}
1042
Brian Carlstrom7940e442013-07-12 13:46:57 -07001043
Vladimir Marko944da602016-02-19 12:27:55 +00001044ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001045 Runtime* runtime = Runtime::Current();
1046 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001047 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001048 StackHandleScope<3> hs(self);
1049 Handle<Class> object_array_class(hs.NewHandle(
1050 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001051
Jeff Haodcdc85b2015-12-04 14:06:18 -08001052 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +00001053 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001054 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +00001055 size_t image_oat_index = pair.second;
1056 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001057 image_dex_files.insert(image_dex_file);
1058 }
1059 }
1060
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001061 // build an Object[] of all the DexCaches used in the source_space_.
1062 // Since we can't hold the dex lock when allocating the dex_caches
1063 // ObjectArray, we lock the dex lock twice, first to get the number
1064 // of dex caches first and then lock it again to copy the dex
1065 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001066 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001067 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001068 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001069 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001070 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001071 ObjPtr<mirror::DexCache> dex_cache =
1072 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001073 if (dex_cache == nullptr) {
1074 continue;
1075 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001076 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001077 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001078 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1079 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001080 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001081 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001082 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001083 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001084 CHECK(dex_caches != nullptr) << "Failed to allocate a dex cache array.";
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001085 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001086 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001087 size_t non_image_dex_caches = 0;
1088 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001089 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001090 ObjPtr<mirror::DexCache> dex_cache =
1091 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001092 if (dex_cache == nullptr) {
1093 continue;
1094 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001095 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001096 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001097 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1098 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001099 }
1100 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1101 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001102 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001103 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001104 ObjPtr<mirror::DexCache> dex_cache =
1105 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001106 if (dex_cache == nullptr) {
1107 continue;
1108 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001109 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001110 if (!IsInBootImage(dex_cache.Ptr()) &&
1111 image_dex_files.find(dex_file) != image_dex_files.end()) {
1112 dex_caches->Set<false>(i, dex_cache.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001113 ++i;
1114 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001115 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001116 }
1117
1118 // build an Object[] of the roots needed to restore the runtime
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001119 int32_t image_roots_size = ImageHeader::NumberOfImageRoots(compile_app_image_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001120 auto image_roots(hs.NewHandle(
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001121 ObjectArray<Object>::Alloc(self, object_array_class.Get(), image_roots_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001122 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001123 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001124 // image_roots[ImageHeader::kClassLoader] will be set later for app image.
1125 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1126 "Class loader should be the last image root.");
1127 for (int32_t i = 0; i < ImageHeader::kImageRootsMax - 1; ++i) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001128 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001129 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001130 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001131}
1132
Mathieu Chartier496577f2016-09-20 15:33:31 -07001133mirror::Object* ImageWriter::TryAssignBinSlot(WorkStack& work_stack,
1134 mirror::Object* obj,
1135 size_t oat_index) {
1136 if (obj == nullptr || IsInBootImage(obj)) {
1137 // Object is null or already in the image, there is no work to do.
1138 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001139 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001140 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001141 // We want to intern all strings but also assign offsets for the source string. Since the
1142 // pruning phase has already happened, if we intern a string to one in the image we still
1143 // end up copying an unreachable string.
1144 if (obj->IsString()) {
1145 // Need to check if the string is already interned in another image info so that we don't have
1146 // the intern tables of two different images contain the same string.
1147 mirror::String* interned = FindInternedString(obj->AsString());
1148 if (interned == nullptr) {
1149 // Not in another image space, insert to our table.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001150 interned =
1151 GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString()).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001152 DCHECK_EQ(interned, obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001153 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001154 } else if (obj->IsDexCache()) {
1155 oat_index = GetOatIndexForDexCache(obj->AsDexCache());
1156 } else if (obj->IsClass()) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001157 // Visit and assign offsets for fields and field arrays.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001158 mirror::Class* as_klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001159 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Vladimir Marko72ab6842017-01-20 19:32:50 +00001160 DCHECK(!as_klass->IsErroneous()) << as_klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001161 if (compile_app_image_) {
1162 // Extra sanity, no boot loader classes should be left!
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00001163 CHECK(!IsBootClassLoaderClass(as_klass)) << as_klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001164 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001165 LengthPrefixedArray<ArtField>* fields[] = {
1166 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1167 };
Mathieu Chartier496577f2016-09-20 15:33:31 -07001168 // Overwrite the oat index value since the class' dex cache is more accurate of where it
1169 // belongs.
1170 oat_index = GetOatIndexForDexCache(dex_cache);
Vladimir Marko944da602016-02-19 12:27:55 +00001171 ImageInfo& image_info = GetImageInfo(oat_index);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001172 if (!compile_app_image_) {
1173 // Note: Avoid locking to prevent lock order violations from root visiting;
1174 // image_info.class_table_ is only accessed from the image writer.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001175 image_info.class_table_->InsertWithoutLocks(as_klass);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001176 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001177 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1178 // Total array length including header.
1179 if (cur_fields != nullptr) {
1180 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1181 // Forward the entire array at once.
1182 auto it = native_object_relocations_.find(cur_fields);
1183 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1184 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001185 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001186 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001187 native_object_relocations_.emplace(
1188 cur_fields,
1189 NativeObjectRelocation {
1190 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1191 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001192 offset += header_size;
1193 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001194 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001195 // Need to forward arrays separate of fields.
1196 ArtField* field = &cur_fields->At(i);
1197 auto it2 = native_object_relocations_.find(field);
1198 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
David Sehr709b0702016-10-13 09:12:37 -07001199 << " already assigned " << field->PrettyField() << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001200 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001201 native_object_relocations_.emplace(
1202 field,
1203 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001204 offset += sizeof(ArtField);
1205 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001206 }
1207 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001208 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001209 size_t num_methods = as_klass->NumMethods();
1210 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001211 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001212 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1213 if (WillMethodBeDirty(&m)) {
1214 any_dirty = true;
1215 break;
1216 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001217 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001218 NativeObjectRelocationType type = any_dirty
1219 ? kNativeObjectRelocationTypeArtMethodDirty
1220 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001221 Bin bin_type = BinTypeForNativeRelocationType(type);
1222 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001223 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1224 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001225 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1226 method_size,
1227 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001228 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001229 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001230 CHECK(it == native_object_relocations_.end())
1231 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001232 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001233 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001234 native_object_relocations_.emplace(array,
1235 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001236 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001237 offset,
1238 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1239 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001240 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001241 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001242 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001243 }
Alex Lighte64300b2015-12-15 15:02:47 -08001244 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001245 }
1246 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1247 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001248 if (as_klass->ShouldHaveImt()) {
1249 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1250 for (size_t i = 0; i < ImTable::kSize; ++i) {
1251 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001252 DCHECK(imt_method != nullptr);
1253 if (imt_method->IsRuntimeMethod() &&
1254 !IsInBootImage(imt_method) &&
1255 !NativeRelocationAssigned(imt_method)) {
1256 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001257 }
1258 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001259 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001260
1261 if (as_klass->ShouldHaveImt()) {
1262 ImTable* imt = as_klass->GetImt(target_ptr_size_);
1263 TryAssignImTableOffset(imt, oat_index);
1264 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001265 } else if (obj->IsClassLoader()) {
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001266 // Register the class loader if it has a class table.
1267 // The fake boot class loader should not get registered and we should end up with only one
1268 // class loader.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001269 mirror::ClassLoader* class_loader = obj->AsClassLoader();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001270 if (class_loader->GetClassTable() != nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001271 DCHECK(compile_app_image_);
1272 DCHECK(class_loaders_.empty());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001273 class_loaders_.insert(class_loader);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001274 ImageInfo& image_info = GetImageInfo(oat_index);
1275 // Note: Avoid locking to prevent lock order violations from root visiting;
1276 // image_info.class_table_ table is only accessed from the image writer
1277 // and class_loader->GetClassTable() is iterated but not modified.
1278 image_info.class_table_->CopyWithoutLocks(*class_loader->GetClassTable());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001279 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001280 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001281 AssignImageBinSlot(obj, oat_index);
1282 work_stack.emplace(obj, oat_index);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001283 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001284 if (obj->IsString()) {
1285 // Always return the interned string if there exists one.
1286 mirror::String* interned = FindInternedString(obj->AsString());
1287 if (interned != nullptr) {
1288 return interned;
1289 }
1290 }
1291 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001292}
1293
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001294bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1295 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1296}
1297
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001298void ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
1299 // No offset, or already assigned.
1300 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
1301 return;
1302 }
1303 // If the method is a conflict method we also want to assign the conflict table offset.
1304 ImageInfo& image_info = GetImageInfo(oat_index);
1305 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1306 native_object_relocations_.emplace(
1307 imt,
1308 NativeObjectRelocation {
1309 oat_index,
1310 image_info.bin_slot_sizes_[kBinImTable],
1311 kNativeObjectRelocationTypeIMTable});
1312 image_info.bin_slot_sizes_[kBinImTable] += size;
1313}
1314
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001315void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1316 // No offset, or already assigned.
1317 if (table == nullptr || NativeRelocationAssigned(table)) {
1318 return;
1319 }
1320 CHECK(!IsInBootImage(table));
1321 // If the method is a conflict method we also want to assign the conflict table offset.
1322 ImageInfo& image_info = GetImageInfo(oat_index);
1323 const size_t size = table->ComputeSize(target_ptr_size_);
1324 native_object_relocations_.emplace(
1325 table,
1326 NativeObjectRelocation {
1327 oat_index,
1328 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1329 kNativeObjectRelocationTypeIMTConflictTable});
1330 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1331}
1332
Jeff Haodcdc85b2015-12-04 14:06:18 -08001333void ImageWriter::AssignMethodOffset(ArtMethod* method,
1334 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001335 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001336 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001337 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
David Sehr709b0702016-10-13 09:12:37 -07001338 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001339 if (method->IsRuntimeMethod()) {
1340 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1341 }
Vladimir Marko944da602016-02-19 12:27:55 +00001342 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001343 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001344 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001345 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001346}
1347
Mathieu Chartier496577f2016-09-20 15:33:31 -07001348void ImageWriter::EnsureBinSlotAssignedCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001349 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1350 DCHECK(writer != nullptr);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001351 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) {
David Sehr709b0702016-10-13 09:12:37 -07001352 CHECK(writer->IsImageBinSlotAssigned(obj)) << mirror::Object::PrettyTypeOf(obj) << " " << obj;
Mathieu Chartier496577f2016-09-20 15:33:31 -07001353 }
1354}
1355
1356void ImageWriter::DeflateMonitorCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED) {
1357 Monitor::Deflate(Thread::Current(), obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001358}
1359
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001360void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1361 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1362 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001363 if (!writer->IsInBootImage(obj)) {
1364 writer->UnbinObjectsIntoOffset(obj);
1365 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001366}
1367
1368void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001369 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001370 CHECK(obj != nullptr);
1371
1372 // We know the bin slot, and the total bin sizes for all objects by now,
1373 // so calculate the object's final image offset.
1374
1375 DCHECK(IsImageBinSlotAssigned(obj));
1376 BinSlot bin_slot = GetImageBinSlot(obj);
1377 // Change the lockword from a bin slot into an offset
1378 AssignImageOffset(obj, bin_slot);
1379}
1380
Mathieu Chartier496577f2016-09-20 15:33:31 -07001381class ImageWriter::VisitReferencesVisitor {
1382 public:
1383 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index)
1384 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {}
1385
1386 // Fix up separately since we also need to fix up method entrypoints.
1387 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1388 REQUIRES_SHARED(Locks::mutator_lock_) {
1389 if (!root->IsNull()) {
1390 VisitRoot(root);
1391 }
1392 }
1393
1394 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1395 REQUIRES_SHARED(Locks::mutator_lock_) {
1396 root->Assign(VisitReference(root->AsMirrorPtr()));
1397 }
1398
Mathieu Chartier31e88222016-10-14 18:43:19 -07001399 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
Mathieu Chartier496577f2016-09-20 15:33:31 -07001400 MemberOffset offset,
1401 bool is_static ATTRIBUTE_UNUSED) const
1402 REQUIRES_SHARED(Locks::mutator_lock_) {
1403 mirror::Object* ref =
1404 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1405 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1406 }
1407
Mathieu Chartier31e88222016-10-14 18:43:19 -07001408 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1409 ObjPtr<mirror::Reference> ref) const
Mathieu Chartier496577f2016-09-20 15:33:31 -07001410 REQUIRES_SHARED(Locks::mutator_lock_) {
1411 ref->SetReferent</*kTransactionActive*/false>(
1412 VisitReference(ref->GetReferent<kWithoutReadBarrier>()));
1413 }
1414
1415 private:
1416 mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1417 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_);
1418 }
1419
1420 ImageWriter* const image_writer_;
1421 WorkStack* const work_stack_;
1422 const size_t oat_index_;
1423};
1424
1425class ImageWriter::GetRootsVisitor : public RootVisitor {
1426 public:
1427 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {}
1428
1429 void VisitRoots(mirror::Object*** roots,
1430 size_t count,
1431 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1432 REQUIRES_SHARED(Locks::mutator_lock_) {
1433 for (size_t i = 0; i < count; ++i) {
1434 roots_->push_back(*roots[i]);
1435 }
1436 }
1437
1438 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1439 size_t count,
1440 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1441 REQUIRES_SHARED(Locks::mutator_lock_) {
1442 for (size_t i = 0; i < count; ++i) {
1443 roots_->push_back(roots[i]->AsMirrorPtr());
1444 }
1445 }
1446
1447 private:
1448 std::vector<mirror::Object*>* const roots_;
1449};
1450
1451void ImageWriter::ProcessWorkStack(WorkStack* work_stack) {
1452 while (!work_stack->empty()) {
1453 std::pair<mirror::Object*, size_t> pair(work_stack->top());
1454 work_stack->pop();
1455 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second);
1456 // Walk references and assign bin slots for them.
1457 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1458 visitor,
1459 visitor);
1460 }
1461}
1462
Vladimir Markof4da6752014-08-01 19:04:18 +01001463void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001464 Thread* const self = Thread::Current();
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07001465 VariableSizedHandleScope handles(self);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001466 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001467 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1468 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001469 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001470
Mathieu Chartier496577f2016-09-20 15:33:31 -07001471 Runtime* const runtime = Runtime::Current();
1472 gc::Heap* const heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001473
Mathieu Chartier31e89252013-08-28 11:29:12 -07001474 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001475 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001476 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001477
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001478 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001479 // Write the image runtime methods.
1480 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1481 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1482 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001483 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
1484 runtime->GetCalleeSaveMethod(Runtime::kSaveAllCalleeSaves);
1485 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
1486 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsOnly);
1487 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
1488 runtime->GetCalleeSaveMethod(Runtime::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001489 image_methods_[ImageHeader::kSaveEverythingMethod] =
1490 runtime->GetCalleeSaveMethod(Runtime::kSaveEverything);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001491 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001492 for (auto* m : image_methods_) {
1493 CHECK(m != nullptr);
1494 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001495 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1496 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001497 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001498 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001499 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001500
Mathieu Chartier496577f2016-09-20 15:33:31 -07001501 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
1502 // this lock while holding other locks may cause lock order violations.
1503 heap->VisitObjects(DeflateMonitorCallback, this);
1504
1505 // Work list of <object, oat_index> for objects. Everything on the stack must already be
1506 // assigned a bin slot.
1507 WorkStack work_stack;
1508
1509 // Special case interned strings to put them in the image they are likely to be resolved from.
1510 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
1511 auto it = dex_file_oat_index_map_.find(dex_file);
1512 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1513 const size_t oat_index = it->second;
1514 InternTable* const intern_table = runtime->GetInternTable();
1515 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
1516 uint32_t utf16_length;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001517 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(dex::StringIndex(i),
1518 &utf16_length);
Mathieu Chartier9e868092016-10-31 14:58:04 -07001519 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001520 TryAssignBinSlot(work_stack, string, oat_index);
1521 }
1522 }
1523
1524 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor
1525 // visits roots while holding various locks.
1526 {
1527 std::vector<mirror::Object*> roots;
1528 GetRootsVisitor root_visitor(&roots);
1529 runtime->VisitRoots(&root_visitor);
1530 for (mirror::Object* obj : roots) {
1531 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex());
1532 }
1533 }
1534 ProcessWorkStack(&work_stack);
1535
1536 // For app images, there may be objects that are only held live by the by the boot image. One
1537 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback
1538 // does not fail any checks. TODO: We should probably avoid copying these objects.
1539 if (compile_app_image_) {
1540 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) {
1541 DCHECK(space->IsImageSpace());
1542 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1543 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1544 reinterpret_cast<uintptr_t>(space->Limit()),
1545 [this, &work_stack](mirror::Object* obj)
1546 REQUIRES_SHARED(Locks::mutator_lock_) {
1547 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex());
1548 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot).
1549 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1550 visitor,
1551 visitor);
1552 });
1553 }
1554 // Process the work stack in case anything was added by TryAssignBinSlot.
1555 ProcessWorkStack(&work_stack);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001556
1557 // Store the class loader in the class roots.
1558 CHECK_EQ(class_loaders_.size(), 1u);
1559 CHECK_EQ(image_roots.size(), 1u);
1560 CHECK(*class_loaders_.begin() != nullptr);
1561 image_roots[0]->Set<false>(ImageHeader::kClassLoader, *class_loaders_.begin());
Mathieu Chartier496577f2016-09-20 15:33:31 -07001562 }
1563
1564 // Verify that all objects have assigned image bin slots.
1565 heap->VisitObjects(EnsureBinSlotAssignedCallback, this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001566
Vladimir Marko05792b92015-08-03 11:56:49 +01001567 // Calculate size of the dex cache arrays slot and prepare offsets.
1568 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001569
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001570 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001571 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001572 // Calculate how big the intern table will be after being serialized.
1573 InternTable* const intern_table = image_info.intern_table_.get();
1574 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
Vladimir Marko1a1de672016-10-13 12:53:15 +01001575 if (intern_table->StrongSize() != 0u) {
1576 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1577 }
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001578 // Calculate the size of the class table.
1579 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001580 CHECK_EQ(class_loaders_.size(), compile_app_image_ ? 1u : 0u);
1581 mirror::ClassLoader* class_loader = compile_app_image_ ? *class_loaders_.begin() : nullptr;
1582 DCHECK_EQ(image_info.class_table_->NumZygoteClasses(class_loader), 0u);
1583 if (image_info.class_table_->NumNonZygoteClasses(class_loader) != 0u) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001584 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
1585 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001586 }
1587
Vladimir Markocf36d492015-08-12 19:27:26 +01001588 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001589 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001590 size_t bin_offset = image_objects_offset_begin_;
1591 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001592 switch (i) {
1593 case kBinArtMethodClean:
1594 case kBinArtMethodDirty: {
1595 bin_offset = RoundUp(bin_offset, method_alignment);
1596 break;
1597 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001598 case kBinDexCacheArray:
1599 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment());
1600 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001601 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001602 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001603 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001604 break;
1605 }
1606 default: {
1607 // Normal alignment.
1608 }
1609 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001610 image_info.bin_slot_offsets_[i] = bin_offset;
1611 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001612 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001613 // NOTE: There may be additional padding between the bin slots and the intern table.
1614 DCHECK_EQ(image_info.image_end_,
1615 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001616 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001617
Jeff Haodcdc85b2015-12-04 14:06:18 -08001618 // Calculate image offsets.
1619 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001620 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001621 image_info.image_begin_ = global_image_begin_ + image_offset;
1622 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001623 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001624 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001625 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001626 image_offset += image_info.image_size_;
1627 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001628
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001629 // Transform each object's bin slot into an offset which will be used to do the final copy.
1630 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001631
Jeff Haodcdc85b2015-12-04 14:06:18 -08001632 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001633
Jeff Haodcdc85b2015-12-04 14:06:18 -08001634 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001635 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001636 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1637 i++;
1638 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001639
Mathieu Chartiere401d142015-04-22 13:56:20 -07001640 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001641 for (auto& pair : native_object_relocations_) {
1642 NativeObjectRelocation& relocation = pair.second;
1643 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001644 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001645 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001646 }
1647
Jeff Haodcdc85b2015-12-04 14:06:18 -08001648 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001649}
1650
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001651size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001652 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001653
1654 // Do not round up any sections here that are represented by the bins since it will break
1655 // offsets.
1656
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001657 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001658 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001659 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001660
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001661 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001662 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1663 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001664 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001665
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001666 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001667 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1668 *methods_section = ImageSection(
1669 bin_slot_offsets_[kBinArtMethodClean],
1670 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1671
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001672 // IMT section.
1673 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1674 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1675
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001676 // Conflict tables section.
1677 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1678 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1679 bin_slot_sizes_[kBinIMTConflictTable]);
1680
1681 // Runtime methods section.
1682 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1683 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1684 bin_slot_sizes_[kBinRuntimeMethod]);
1685
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001686 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001687 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1688 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1689 bin_slot_sizes_[kBinDexCacheArray]);
1690
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001691 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001692 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001693 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001694 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001695 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1696 cur_pos = interned_strings_section->End();
1697 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1698 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1699 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001700 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001701 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001702 cur_pos = class_table_section->End();
1703 // Image end goes right before the start of the image bitmap.
1704 return cur_pos;
1705}
1706
Vladimir Marko944da602016-02-19 12:27:55 +00001707void ImageWriter::CreateHeader(size_t oat_index) {
1708 ImageInfo& image_info = GetImageInfo(oat_index);
1709 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1710 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1711 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001712
1713 // Create the image sections.
1714 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001715 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001716
Mathieu Chartiere401d142015-04-22 13:56:20 -07001717 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001718 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001719 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001720 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001721 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001722 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001723 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001724 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001725 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1726 ++idx;
1727 }
1728 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001729 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1730 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1731 << " Image offset=" << image_info.image_offset_ << std::dec;
1732 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1733 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1734 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1735 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001736 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001737 // Store boot image info for app image so that we can relocate.
1738 uint32_t boot_image_begin = 0;
1739 uint32_t boot_image_end = 0;
1740 uint32_t boot_oat_begin = 0;
1741 uint32_t boot_oat_end = 0;
1742 gc::Heap* const heap = Runtime::Current()->GetHeap();
1743 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001744
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001745 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1746 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001747 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1748 image_end,
1749 sections,
1750 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001751 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001752 PointerToLowMemUInt32(oat_file_begin),
1753 PointerToLowMemUInt32(image_info.oat_data_begin_),
1754 PointerToLowMemUInt32(oat_data_end),
1755 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001756 boot_image_begin,
1757 boot_image_end - boot_image_begin,
1758 boot_oat_begin,
1759 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001760 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001761 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001762 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001763 image_storage_mode_,
1764 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001765}
1766
1767ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001768 auto it = native_object_relocations_.find(method);
David Sehr709b0702016-10-13 09:12:37 -07001769 CHECK(it != native_object_relocations_.end()) << ArtMethod::PrettyMethod(method) << " @ "
1770 << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001771 size_t oat_index = GetOatIndex(method->GetDexCache());
1772 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001773 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1774 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001775}
1776
Vladimir Markoad06b982016-11-17 16:38:59 +00001777class ImageWriter::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001778 public:
1779 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1780 }
1781
1782 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001783 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001784 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001785 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001786 }
1787 }
1788
1789 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1790 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001791 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001792 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001793 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001794 }
1795 }
1796
1797 private:
1798 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001799};
1800
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001801void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
1802 for (size_t i = 0; i < ImTable::kSize; ++i) {
1803 ArtMethod* method = orig->Get(i, target_ptr_size_);
1804 copy->Set(i, NativeLocationInImage(method), target_ptr_size_);
1805 }
1806}
1807
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001808void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
1809 const size_t count = orig->NumEntries(target_ptr_size_);
1810 for (size_t i = 0; i < count; ++i) {
1811 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
1812 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
1813 copy->SetInterfaceMethod(i, target_ptr_size_, NativeLocationInImage(interface_method));
1814 copy->SetImplementationMethod(i,
1815 target_ptr_size_,
1816 NativeLocationInImage(implementation_method));
1817 }
1818}
1819
Vladimir Marko944da602016-02-19 12:27:55 +00001820void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001821 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001822 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001823 for (auto& pair : native_object_relocations_) {
1824 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001825 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001826 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001827 continue;
1828 }
1829 auto* dest = image_info.image_->Begin() + relocation.offset;
1830 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001831 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001832 switch (relocation.type) {
1833 case kNativeObjectRelocationTypeArtField: {
1834 memcpy(dest, pair.first, sizeof(ArtField));
1835 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
Mathieu Chartier1cc62e42016-10-03 18:01:28 -07001836 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass().Ptr()));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001837 break;
1838 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001839 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001840 case kNativeObjectRelocationTypeArtMethodClean:
1841 case kNativeObjectRelocationTypeArtMethodDirty: {
1842 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001843 reinterpret_cast<ArtMethod*>(dest),
1844 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001845 break;
1846 }
1847 // For arrays, copy just the header since the elements will get copied by their corresponding
1848 // relocations.
1849 case kNativeObjectRelocationTypeArtFieldArray: {
1850 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1851 break;
1852 }
1853 case kNativeObjectRelocationTypeArtMethodArrayClean:
1854 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00001855 size_t size = ArtMethod::Size(target_ptr_size_);
1856 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1857 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1858 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1859 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001860 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00001861 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001862 case kNativeObjectRelocationTypeDexCacheArray:
1863 // Nothing to copy here, everything is done in FixupDexCache().
1864 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001865 case kNativeObjectRelocationTypeIMTable: {
1866 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
1867 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
1868 CopyAndFixupImTable(orig_imt, dest_imt);
1869 break;
1870 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001871 case kNativeObjectRelocationTypeIMTConflictTable: {
1872 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
1873 CopyAndFixupImtConflictTable(
1874 orig_table,
1875 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
1876 break;
1877 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001878 }
1879 }
1880 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001881 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001882 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001883 ArtMethod* method = image_methods_[i];
1884 CHECK(method != nullptr);
1885 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001886 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001887 }
1888 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001889 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001890 FixupRootVisitor root_visitor(this);
1891
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001892 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001893 if (image_info.intern_table_bytes_ > 0) {
1894 const ImageSection& intern_table_section = image_header->GetImageSection(
1895 ImageHeader::kSectionInternedStrings);
1896 InternTable* const intern_table = image_info.intern_table_.get();
1897 uint8_t* const intern_table_memory_ptr =
1898 image_info.image_->Begin() + intern_table_section.Offset();
1899 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1900 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1901 // Fixup the pointers in the newly written intern table to contain image addresses.
1902 InternTable temp_intern_table;
1903 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1904 // the VisitRoots() will update the memory directly rather than the copies.
1905 // This also relies on visit roots not doing any verification which could fail after we update
1906 // the roots to be the image addresses.
1907 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1908 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1909 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1910 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001911 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1912 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001913 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001914 const ImageSection& class_table_section = image_header->GetImageSection(
1915 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001916 uint8_t* const class_table_memory_ptr =
1917 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001918 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001919
1920 ClassTable* table = image_info.class_table_.get();
1921 CHECK(table != nullptr);
1922 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1923 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1924 // Fixup the pointers in the newly written class table to contain image addresses. See
1925 // above comment for intern tables.
1926 ClassTable temp_class_table;
1927 temp_class_table.ReadFromMemory(class_table_memory_ptr);
Vladimir Markobfb80d22017-02-14 14:08:12 +00001928 ObjPtr<mirror::ClassLoader> class_loader = GetClassLoader();
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001929 CHECK_EQ(temp_class_table.NumZygoteClasses(class_loader),
1930 table->NumNonZygoteClasses(class_loader) + table->NumZygoteClasses(class_loader));
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08001931 UnbufferedRootVisitor visitor(&root_visitor, RootInfo(kRootUnknown));
1932 temp_class_table.VisitRoots(visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001933 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001934}
1935
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001936void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001937 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001938 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1939 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001940 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001941 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001942 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1943 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001944 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001945 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001946}
1947
Mathieu Chartier590fee92013-09-13 13:46:47 -07001948void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001949 DCHECK(obj != nullptr);
1950 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001951 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1952}
1953
Mathieu Chartiere401d142015-04-22 13:56:20 -07001954void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1955 mirror::Class* klass, Bin array_type) {
1956 CHECK(klass->IsArrayClass());
David Sehr709b0702016-10-13 09:12:37 -07001957 CHECK(arr->IsIntArray() || arr->IsLongArray()) << klass->PrettyClass() << " " << arr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001958 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001959 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001960 dst->SetClass(GetImageAddress(arr->GetClass()));
1961 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001962 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001963 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1964 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001965 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001966 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001967 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001968 auto* method = reinterpret_cast<ArtMethod*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07001969 LOG(FATAL) << "No relocation entry for ArtMethod " << method->PrettyMethod() << " @ "
1970 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1971 << Class::PrettyClass(method->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001972 } else {
1973 CHECK_EQ(array_type, kBinArtField);
1974 auto* field = reinterpret_cast<ArtField*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07001975 LOG(FATAL) << "No relocation entry for ArtField " << field->PrettyField() << " @ "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001976 << field << " idx=" << i << "/" << num_elements << " with declaring class "
David Sehr709b0702016-10-13 09:12:37 -07001977 << Class::PrettyClass(field->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001978 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001979 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001980 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001981 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001982 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001983 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001984 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001985 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001986 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001987}
1988
1989void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001990 if (IsInBootImage(obj)) {
1991 return;
1992 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001993 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001994 size_t oat_index = GetOatIndex(obj);
1995 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001996 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1997 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001998 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001999
Jeff Haodcdc85b2015-12-04 14:06:18 -08002000 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002001
2002 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002003 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002004 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002005
Mathieu Chartierad2541a2013-10-25 10:05:23 -07002006 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
2007 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002008 const auto it = saved_hashcode_map_.find(obj);
2009 dst->SetLockWord(it != saved_hashcode_map_.end() ?
2010 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002011 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
2012 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
2013 // safe since we mark all of the objects that may reference non immune objects as gray.
2014 CHECK(dst->AtomicSetMarkBit(0, 1));
2015 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002016 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002017}
2018
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002019// Rewrite all the references in the copied object to point to their image address equivalent
Vladimir Markoad06b982016-11-17 16:38:59 +00002020class ImageWriter::FixupVisitor {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002021 public:
2022 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
2023 }
2024
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002025 // Ignore class roots since we don't have a way to map them to the destination. These are handled
2026 // with other logic.
2027 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
2028 const {}
2029 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
2030
2031
Mathieu Chartier31e88222016-10-14 18:43:19 -07002032 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07002033 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07002034 ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002035 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
2036 // image.
2037 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08002038 offset,
Mathieu Chartier31e88222016-10-14 18:43:19 -07002039 image_writer_->GetImageAddress(ref.Ptr()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002040 }
2041
2042 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07002043 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2044 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002045 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002046 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08002047 mirror::Reference::ReferentOffset(),
2048 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002049 }
2050
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002051 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002052 ImageWriter* const image_writer_;
2053 mirror::Object* const copy_;
2054};
2055
Vladimir Markoad06b982016-11-17 16:38:59 +00002056class ImageWriter::FixupClassVisitor FINAL : public FixupVisitor {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002057 public:
2058 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
2059 }
2060
Mathieu Chartier31e88222016-10-14 18:43:19 -07002061 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07002062 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002063 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002064 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002065 }
2066
Mathieu Chartier31e88222016-10-14 18:43:19 -07002067 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2068 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002069 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002070 LOG(FATAL) << "Reference not expected here.";
2071 }
2072};
2073
Vladimir Marko05792b92015-08-03 11:56:49 +01002074uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
2075 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002076 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002077 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002078 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
2079 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002080 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01002081 return relocation.offset;
2082}
2083
2084template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002085std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002086 std::ostringstream oss;
2087 oss << ptr;
2088 return oss.str();
2089}
2090
2091template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002092std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07002093 return ArtMethod::PrettyMethod(method);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002094}
2095
2096template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002097T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002098 if (obj == nullptr || IsInBootImage(obj)) {
2099 return obj;
2100 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002101 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002102 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
2103 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002104 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00002105 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002106 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002107 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002108}
2109
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002110template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08002111T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
2112 if (obj == nullptr || IsInBootImage(obj)) {
2113 return obj;
2114 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002115 size_t oat_index = GetOatIndexForDexCache(dex_cache);
2116 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002117 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
2118 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002119}
2120
Vladimir Markoad06b982016-11-17 16:38:59 +00002121class ImageWriter::NativeLocationVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002122 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002123 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002124
2125 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002126 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002127 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002128 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002129
2130 private:
2131 ImageWriter* const image_writer_;
2132};
2133
2134void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002135 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002136 FixupClassVisitor visitor(this, copy);
Mathieu Chartier31e88222016-10-14 18:43:19 -07002137 ObjPtr<mirror::Object>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002138
2139 // Remove the clinitThreadId. This is required for image determinism.
2140 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002141}
2142
Ian Rogersef7d42f2014-01-06 12:55:46 -08002143void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002144 DCHECK(orig != nullptr);
2145 DCHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002146 if (kUseBakerReadBarrier) {
2147 orig->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002148 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002149 auto* klass = orig->GetClass();
2150 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002151 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07002152 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
2153 if (it != pointer_arrays_.end()) {
2154 // Should only need to fixup every pointer array exactly once.
2155 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
2156 pointer_arrays_.erase(it);
2157 return;
2158 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002159 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002160 if (orig->IsClass()) {
2161 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002162 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002163 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
2164 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01002165 auto* dest = down_cast<mirror::Executable*>(copy);
2166 auto* src = down_cast<mirror::Executable*>(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002167 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05002168 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01002169 } else if (!klass->IsArrayClass()) {
2170 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2171 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
2172 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002173 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002174 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002175 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2176 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002177 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002178 // Also set allocator to null to be safe. The allocator is created when we create the class
2179 // table. We also never expect to unload things in the image since they are held live as
2180 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002181 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002182 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002183 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002184 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002185 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002186 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002187}
2188
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002189
2190class ImageAddressVisitor {
2191 public:
2192 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
2193
2194 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002195 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002196 return image_writer_->GetImageAddress(ptr);
2197 }
2198
2199 private:
2200 ImageWriter* const image_writer_;
2201};
2202
2203
Vladimir Marko05792b92015-08-03 11:56:49 +01002204void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2205 mirror::DexCache* copy_dex_cache) {
2206 // Though the DexCache array fields are usually treated as native pointers, we set the full
2207 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2208 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2209 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002210 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002211 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002212 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002213 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002214 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002215 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
2216 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002217 }
Vladimir Markobfb80d22017-02-14 14:08:12 +00002218 mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
Vladimir Marko05792b92015-08-03 11:56:49 +01002219 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002220 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002221 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002222 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002223 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
2224 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01002225 }
2226 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
2227 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002228 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002229 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002230 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002231 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002232 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
2233 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002234 // NativeLocationInImage also handles runtime methods since these have relocation info.
2235 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002236 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
2237 }
2238 }
2239 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
2240 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002241 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002242 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002243 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002244 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002245 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
2246 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002247 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002248 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
2249 }
2250 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01002251 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
2252 if (orig_method_types != nullptr) {
2253 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodTypesOffset(),
2254 NativeLocationInImage(orig_method_types),
2255 PointerSize::k64);
2256 orig_dex_cache->FixupResolvedMethodTypes(NativeCopyLocation(orig_method_types, orig_dex_cache),
2257 ImageAddressVisitor(this));
2258 }
Orion Hodsonc069a302017-01-18 09:23:12 +00002259 GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
2260 if (orig_call_sites != nullptr) {
2261 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedCallSitesOffset(),
2262 NativeLocationInImage(orig_call_sites),
2263 PointerSize::k64);
2264 orig_dex_cache->FixupResolvedCallSites(NativeCopyLocation(orig_call_sites, orig_dex_cache),
2265 ImageAddressVisitor(this));
2266 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002267
2268 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2269 // compiler pointers in here will make the output non-deterministic.
2270 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002271}
2272
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002273const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2274 DCHECK_LT(type, kOatAddressCount);
2275 // If we are compiling an app image, we need to use the stubs of the boot image.
2276 if (compile_app_image_) {
2277 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002278 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002279 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2280 DCHECK(!image_spaces.empty());
2281 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002282 CHECK(oat_file != nullptr);
2283 const OatHeader& header = oat_file->GetOatHeader();
2284 switch (type) {
2285 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2286 case kOatAddressQuickGenericJNITrampoline:
2287 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2288 case kOatAddressInterpreterToInterpreterBridge:
2289 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2290 case kOatAddressInterpreterToCompiledCodeBridge:
2291 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2292 case kOatAddressJNIDlsymLookup:
2293 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2294 case kOatAddressQuickIMTConflictTrampoline:
2295 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2296 case kOatAddressQuickResolutionTrampoline:
2297 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2298 case kOatAddressQuickToInterpreterBridge:
2299 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2300 default:
2301 UNREACHABLE();
2302 }
2303 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002304 const ImageInfo& primary_image_info = GetImageInfo(0);
2305 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002306}
2307
Jeff Haodcdc85b2015-12-04 14:06:18 -08002308const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2309 const ImageInfo& image_info,
2310 bool* quick_is_interpreted) {
David Sehr709b0702016-10-13 09:12:37 -07002311 DCHECK(!method->IsResolutionMethod()) << method->PrettyMethod();
2312 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << method->PrettyMethod();
2313 DCHECK(!method->IsImtUnimplementedMethod()) << method->PrettyMethod();
2314 DCHECK(method->IsInvokable()) << method->PrettyMethod();
2315 DCHECK(!IsInBootImage(method)) << method->PrettyMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002316
2317 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2318 // trampoline.
2319
2320 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002321 const void* quick_oat_entry_point =
2322 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2323 const uint8_t* quick_code;
2324
2325 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2326 DCHECK(method->IsCopied());
2327 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2328 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2329 } else {
2330 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2331 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2332 }
2333
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002334 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002335 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2336 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002337 // We have code for a non-static or initialized method, just use the code.
2338 } else if (quick_code == nullptr && method->IsNative() &&
2339 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2340 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002341 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002342 } else if (quick_code == nullptr && !method->IsNative()) {
2343 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002344 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002345 *quick_is_interpreted = true;
2346 } else {
2347 CHECK(!method->GetDeclaringClass()->IsInitialized());
2348 // We have code for a static method, but need to go through the resolution stub for class
2349 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002350 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2351 }
2352 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002353 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002354 }
2355 return quick_code;
2356}
2357
Jeff Haodcdc85b2015-12-04 14:06:18 -08002358void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2359 ArtMethod* copy,
2360 const ImageInfo& image_info) {
Mingyao Yange8fcd012017-01-20 10:43:30 -08002361 if (orig->IsAbstract()) {
2362 // Ignore the single-implementation info for abstract method.
2363 // Do this on orig instead of copy, otherwise there is a crash due to methods
2364 // are copied before classes.
2365 // TODO: handle fixup of single-implementation method for abstract method.
2366 orig->SetHasSingleImplementation(false);
2367 orig->SetSingleImplementation(
2368 nullptr, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
2369 }
2370
Vladimir Marko14632852015-08-17 12:07:23 +01002371 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002372
2373 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002374 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002375 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002376
Ian Rogers848871b2013-08-05 10:56:33 -07002377 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2378 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002379
Ian Rogers848871b2013-08-05 10:56:33 -07002380 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002381 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002382 if (orig->IsRuntimeMethod()) {
2383 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2384 if (orig_table != nullptr) {
2385 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2386 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2387 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2388 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2389 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2390 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2391 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2392 } else {
2393 bool found_one = false;
2394 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2395 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2396 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2397 found_one = true;
2398 break;
2399 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002400 }
David Sehr709b0702016-10-13 09:12:37 -07002401 CHECK(found_one) << "Expected to find callee save method but got " << orig->PrettyMethod();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002402 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002403 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002404 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002405 // We assume all methods have code. If they don't currently then we set them to the use the
2406 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2407 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002408 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002409 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002410 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002411 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002412 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002413 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002414 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002415
Sebastien Hertze1d07812014-05-21 15:44:09 +02002416 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002417 if (orig->IsNative()) {
2418 // The native method's pointer is set to a stub to lookup via dlsym.
2419 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002420 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002421 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002422 }
2423 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002424 }
2425}
2426
Jeff Haodcdc85b2015-12-04 14:06:18 -08002427size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002428 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002429 return std::accumulate(&image_info.bin_slot_sizes_[0],
2430 &image_info.bin_slot_sizes_[up_to],
2431 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002432}
2433
2434ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2435 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002436 static_assert(kBinBits == 3, "wrong number of bin bits");
2437 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002438 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2439
2440 DCHECK_LT(GetBin(), kBinSize);
2441 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2442}
2443
2444ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2445 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2446 DCHECK_EQ(index, GetIndex());
2447}
2448
2449ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2450 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2451}
2452
2453uint32_t ImageWriter::BinSlot::GetIndex() const {
2454 return lockword_ & ~kBinMask;
2455}
2456
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002457ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2458 switch (type) {
2459 case kNativeObjectRelocationTypeArtField:
2460 case kNativeObjectRelocationTypeArtFieldArray:
2461 return kBinArtField;
2462 case kNativeObjectRelocationTypeArtMethodClean:
2463 case kNativeObjectRelocationTypeArtMethodArrayClean:
2464 return kBinArtMethodClean;
2465 case kNativeObjectRelocationTypeArtMethodDirty:
2466 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2467 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002468 case kNativeObjectRelocationTypeDexCacheArray:
2469 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002470 case kNativeObjectRelocationTypeRuntimeMethod:
2471 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002472 case kNativeObjectRelocationTypeIMTable:
2473 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002474 case kNativeObjectRelocationTypeIMTConflictTable:
2475 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002476 }
2477 UNREACHABLE();
2478}
2479
Vladimir Marko944da602016-02-19 12:27:55 +00002480size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002481 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002482 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002483 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002484 auto it = oat_index_map_.find(obj);
2485 DCHECK(it != oat_index_map_.end());
2486 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002487}
2488
Vladimir Marko944da602016-02-19 12:27:55 +00002489size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002490 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002491 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002492 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002493 auto it = dex_file_oat_index_map_.find(dex_file);
2494 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2495 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002496}
2497
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002498size_t ImageWriter::GetOatIndexForDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
2499 return (dex_cache == nullptr)
2500 ? GetDefaultOatIndex()
2501 : GetOatIndexForDexFile(dex_cache->GetDexFile());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002502}
2503
Vladimir Marko944da602016-02-19 12:27:55 +00002504void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2505 size_t oat_loaded_size,
2506 size_t oat_data_offset,
2507 size_t oat_data_size) {
2508 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2509 for (const ImageInfo& info : image_infos_) {
2510 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2511 }
2512 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002513
Vladimir Marko944da602016-02-19 12:27:55 +00002514 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2515 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2516 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2517 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2518 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002519
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002520 if (compile_app_image_) {
2521 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2522 return;
2523 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002524
2525 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002526 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002527 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002528 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002529 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2530 }
2531}
2532
Vladimir Marko944da602016-02-19 12:27:55 +00002533void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2534 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2535 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2536
2537 if (oat_index == GetDefaultOatIndex()) {
2538 // Primary oat file, read the trampolines.
2539 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2540 oat_header.GetInterpreterToInterpreterBridgeOffset();
2541 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2542 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2543 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2544 oat_header.GetJniDlsymLookupOffset();
2545 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2546 oat_header.GetQuickGenericJniTrampolineOffset();
2547 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2548 oat_header.GetQuickImtConflictTrampolineOffset();
2549 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2550 oat_header.GetQuickResolutionTrampolineOffset();
2551 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2552 oat_header.GetQuickToInterpreterBridgeOffset();
2553 }
2554}
2555
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002556ImageWriter::ImageWriter(
2557 const CompilerDriver& compiler_driver,
2558 uintptr_t image_begin,
2559 bool compile_pic,
2560 bool compile_app_image,
2561 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002562 const std::vector<const char*>& oat_filenames,
2563 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002564 : compiler_driver_(compiler_driver),
2565 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2566 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002567 compile_pic_(compile_pic),
2568 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002569 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002570 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002571 dirty_methods_(0u),
2572 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002573 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002574 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002575 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002576 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002577 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002578 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2579 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002580}
2581
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002582ImageWriter::ImageInfo::ImageInfo()
2583 : intern_table_(new InternTable),
2584 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002585
Brian Carlstrom7940e442013-07-12 13:46:57 -07002586} // namespace art