blob: fc7cd016b288125af530f22740c39aa6441b20fd [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
Mathieu Chartierceb07b32015-12-10 09:33:21 -080019#include <lz4.h>
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -080020#include <lz4hc.h>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070021#include <sys/stat.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"
Andreas Gampe8228cdf2017-05-30 15:03:54 -070030#include "base/callee_save_type.h"
31#include "base/enums.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "base/logging.h"
33#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010034#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070035#include "compiled_method.h"
36#include "dex_file-inl.h"
Andreas Gampea5b09a62016-11-17 15:21:22 -080037#include "dex_file_types.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070039#include "elf_file.h"
40#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "elf_writer.h"
42#include "gc/accounting/card_table-inl.h"
43#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070044#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier36a270a2016-07-28 18:08:51 -070045#include "gc/collector/concurrent_copying.h"
Andreas Gampe1c158a02017-07-13 17:26:19 -070046#include "gc/heap-visit-objects-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070047#include "gc/heap.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070048#include "gc/space/large_object_space.h"
49#include "gc/space/space-inl.h"
Mathieu Chartier4f5e3cb2017-06-12 13:10:01 -070050#include "gc/verification.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "globals.h"
Mathieu Chartier4f5e3cb2017-06-12 13:10:01 -070052#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070053#include "image.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070054#include "imt_conflict_table.h"
Mathieu Chartier3738e982017-05-12 16:07:28 -070055#include "jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070056#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070057#include "lock_word.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "mirror/array-inl.h"
59#include "mirror/class-inl.h"
Alex Lightd6251582016-10-31 11:12:30 -070060#include "mirror/class_ext.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "mirror/class_loader.h"
62#include "mirror/dex_cache-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070063#include "mirror/dex_cache.h"
Neil Fuller0e844392016-09-08 13:43:31 +010064#include "mirror/executable.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070065#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080067#include "mirror/object-refvisitor-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070069#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070070#include "oat.h"
71#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070072#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070074#include "scoped_thread_state_change-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000075#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070076
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070077using ::art::mirror::Class;
78using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070079using ::art::mirror::Object;
80using ::art::mirror::ObjectArray;
81using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070082
83namespace art {
84
Igor Murashkinf5b4c502014-11-14 15:01:59 -080085// Separate objects into multiple bins to optimize dirty memory use.
86static constexpr bool kBinObjects = true;
87
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080088// Return true if an object is already in an image space.
89bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080090 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080091 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080092 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080093 return false;
94 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080095 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
96 const uint8_t* image_begin = boot_image_space->Begin();
97 // Real image end including ArtMethods and ArtField sections.
98 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
99 if (image_begin <= obj && obj < image_end) {
100 return true;
101 }
102 }
103 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800104}
105
106bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800107 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800108 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800109 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800110 return false;
111 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800112 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
113 const ImageHeader& image_header = boot_image_space->GetImageHeader();
114 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
115 return true;
116 }
117 }
118 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800119}
120
Mathieu Chartier3738e982017-05-12 16:07:28 -0700121static void ClearDexFileCookies() REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampe1c158a02017-07-13 17:26:19 -0700122 auto visitor = [](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
123 DCHECK(obj != nullptr);
124 Class* klass = obj->GetClass();
125 if (klass == WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_DexFile)) {
126 ArtField* field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
127 // Null out the cookie to enable determinism. b/34090128
128 field->SetObject</*kTransactionActive*/false>(obj, nullptr);
129 }
130 };
131 Runtime::Current()->GetHeap()->VisitObjects(visitor);
Andreas Gampedd9d0552015-03-09 12:57:41 -0700132}
133
Vladimir Markof4da6752014-08-01 19:04:18 +0100134bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800135 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800136 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100137 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700138 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100139 PruneNonImageClasses(); // Remove junk
Mathieu Chartier3738e982017-05-12 16:07:28 -0700140 if (compile_app_image_) {
141 // Clear dex file cookies for app images to enable app image determinism. This is required
142 // since the cookie field contains long pointers to DexFiles which are not deterministic.
143 // b/34090128
144 ClearDexFileCookies();
145 } else {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800146 // Avoid for app image since this may increase RAM and image size.
147 ComputeLazyFieldsForImageClasses(); // Add useful information
148 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100149 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100150 heap->CollectGarbage(false); // Remove garbage.
151
Vladimir Markof4da6752014-08-01 19:04:18 +0100152 if (kIsDebugBuild) {
153 ScopedObjectAccess soa(Thread::Current());
154 CheckNonImageClassesRemoved();
155 }
156
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700157 {
158 ScopedObjectAccess soa(Thread::Current());
159 CalculateNewObjectOffsets();
160 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100161
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700162 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
163 // bin size sums being calculated.
164 if (!AllocMemory()) {
165 return false;
166 }
167
Vladimir Markof4da6752014-08-01 19:04:18 +0100168 return true;
169}
170
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700171bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800172 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000173 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800174 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
175 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800176 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800177 if (image_fd != kInvalidFd) {
178 CHECK_EQ(image_filenames.size(), 1u);
179 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800180 CHECK(!oat_filenames.empty());
181 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700182
Vladimir Marko944da602016-02-19 12:27:55 +0000183 {
184 ScopedObjectAccess soa(Thread::Current());
185 for (size_t i = 0; i < oat_filenames.size(); ++i) {
186 CreateHeader(i);
187 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800188 }
189 }
Alex Light53cb16b2014-06-12 11:26:29 -0700190
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700191 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700192 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800193 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700194 Runtime::Current()->GetHeap()->DisableObjectValidation();
195 CopyAndFixupObjects();
196 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700197
Jeff Haodcdc85b2015-12-04 14:06:18 -0800198 for (size_t i = 0; i < image_filenames.size(); ++i) {
199 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000200 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800201 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800202 if (image_fd != kInvalidFd) {
203 if (strlen(image_filename) == 0u) {
204 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800205 // Empty the file in case it already exists.
206 if (image_file != nullptr) {
207 TEMP_FAILURE_RETRY(image_file->SetLength(0));
208 TEMP_FAILURE_RETRY(image_file->Flush());
209 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800210 } else {
211 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
212 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800213 } else {
214 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800215 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800216
Jeff Haodcdc85b2015-12-04 14:06:18 -0800217 if (image_file == nullptr) {
218 LOG(ERROR) << "Failed to open image file " << image_filename;
219 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800220 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800221
222 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800223 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
224 image_file->Erase();
225 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800226 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800227
Jeff Haodcdc85b2015-12-04 14:06:18 -0800228 std::unique_ptr<char[]> compressed_data;
229 // Image data size excludes the bitmap and the header.
230 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
231 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
232 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
233 size_t data_size;
234 const char* image_data_to_write;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800235 const uint64_t compress_start_time = NanoTime();
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000236
Jeff Haodcdc85b2015-12-04 14:06:18 -0800237 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
238 switch (image_storage_mode_) {
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700239 case ImageHeader::kStorageModeLZ4HC: // Fall-through.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800240 case ImageHeader::kStorageModeLZ4: {
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800241 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800242 compressed_data.reset(new char[compressed_max_size]);
David Lin915ec552017-02-23 15:36:06 -0800243 data_size = LZ4_compress_default(
Jeff Haodcdc85b2015-12-04 14:06:18 -0800244 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
245 &compressed_data[0],
David Lin915ec552017-02-23 15:36:06 -0800246 image_data_size,
247 compressed_max_size);
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800248
249 break;
250 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700251 /*
252 * Disabled due to image_test64 flakyness. Both use same decompression. b/27560444
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800253 case ImageHeader::kStorageModeLZ4HC: {
254 // Bound is same as non HC.
255 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
256 compressed_data.reset(new char[compressed_max_size]);
257 data_size = LZ4_compressHC(
258 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
259 &compressed_data[0],
260 image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800261 break;
262 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700263 */
Jeff Haodcdc85b2015-12-04 14:06:18 -0800264 case ImageHeader::kStorageModeUncompressed: {
265 data_size = image_data_size;
266 image_data_to_write = image_data;
267 break;
268 }
269 default: {
270 LOG(FATAL) << "Unsupported";
271 UNREACHABLE();
272 }
273 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800274
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800275 if (compressed_data != nullptr) {
276 image_data_to_write = &compressed_data[0];
277 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
278 << PrettyDuration(NanoTime() - compress_start_time);
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700279 if (kIsDebugBuild) {
280 std::unique_ptr<uint8_t[]> temp(new uint8_t[image_data_size]);
281 const size_t decompressed_size = LZ4_decompress_safe(
282 reinterpret_cast<char*>(&compressed_data[0]),
283 reinterpret_cast<char*>(&temp[0]),
284 data_size,
285 image_data_size);
286 CHECK_EQ(decompressed_size, image_data_size);
287 CHECK_EQ(memcmp(image_data, &temp[0], image_data_size), 0) << image_storage_mode_;
288 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800289 }
290
Jeff Haodcdc85b2015-12-04 14:06:18 -0800291 // Write out the image + fields + methods.
292 const bool is_compressed = compressed_data != nullptr;
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800293 if (!image_file->PwriteFully(image_data_to_write, data_size, sizeof(ImageHeader))) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800294 PLOG(ERROR) << "Failed to write image file data " << image_filename;
295 image_file->Erase();
296 return false;
297 }
298
299 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
300 // convenience.
301 const ImageSection& bitmap_section = image_header->GetImageSection(
302 ImageHeader::kSectionImageBitmap);
303 // Align up since data size may be unaligned if the image is compressed.
304 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
305 if (!is_compressed) {
306 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
307 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800308 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
309 bitmap_section.Size(),
310 bitmap_position_in_file)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800311 PLOG(ERROR) << "Failed to write image file " << image_filename;
312 image_file->Erase();
313 return false;
314 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800315
316 int err = image_file->Flush();
317 if (err < 0) {
318 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
319 image_file->Erase();
320 return false;
321 }
322
323 // Write header last in case the compiler gets killed in the middle of image writing.
324 // We do not want to have a corrupted image with a valid header.
325 // The header is uncompressed since it contains whether the image is compressed or not.
326 image_header->data_size_ = data_size;
327 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
328 sizeof(ImageHeader),
329 0)) {
330 PLOG(ERROR) << "Failed to write image file header " << image_filename;
331 image_file->Erase();
332 return false;
333 }
334
Jeff Haodcdc85b2015-12-04 14:06:18 -0800335 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
336 static_cast<size_t>(image_file->GetLength()));
337 if (image_file->FlushCloseOrErase() != 0) {
338 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
339 return false;
340 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800341 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700342 return true;
343}
344
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700345void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700346 DCHECK(object != nullptr);
347 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800348
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800349 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700350 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700351 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700352 DCHECK(IsImageOffsetAssigned(object));
353}
354
Mathieu Chartiere401d142015-04-22 13:56:20 -0700355void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
356 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
357 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
358 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
359}
360
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800361void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700362 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800363 DCHECK_NE(image_objects_offset_begin_, 0u);
364
Vladimir Marko944da602016-02-19 12:27:55 +0000365 size_t oat_index = GetOatIndex(object);
366 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800367 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100368 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800369 DCHECK_ALIGNED(new_offset, kObjectAlignment);
370
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700371 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800372 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700373}
374
Ian Rogersef7d42f2014-01-06 12:55:46 -0800375bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800376 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700377 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700378 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700379}
380
Ian Rogersef7d42f2014-01-06 12:55:46 -0800381size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700382 DCHECK(object != nullptr);
383 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700384 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700385 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000386 size_t oat_index = GetOatIndex(object);
387 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800388 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700389 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700390}
391
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800392void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
393 DCHECK(object != nullptr);
394 DCHECK(!IsImageOffsetAssigned(object));
395 DCHECK(!IsImageBinSlotAssigned(object));
396
397 // Before we stomp over the lock word, save the hash code for later.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800398 LockWord lw(object->GetLockWord(false));
399 switch (lw.GetState()) {
Ian Rogers23e81a12017-07-05 09:36:27 -0700400 case LockWord::kFatLocked:
401 FALLTHROUGH_INTENDED;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800402 case LockWord::kThinLocked: {
Ian Rogers23e81a12017-07-05 09:36:27 -0700403 std::ostringstream oss;
404 bool thin = (lw.GetState() == LockWord::kThinLocked);
405 oss << (thin ? "Thin" : "Fat")
406 << " locked object " << object << "(" << object->PrettyTypeOf()
407 << ") found during object copy";
408 if (thin) {
409 oss << ". Lock owner:" << lw.ThinLockOwner();
410 }
411 LOG(FATAL) << oss.str();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800412 break;
413 }
414 case LockWord::kUnlocked:
415 // No hash, don't need to save it.
416 break;
417 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700418 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
419 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800420 break;
421 default:
422 LOG(FATAL) << "Unreachable.";
423 UNREACHABLE();
424 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700425 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700426 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800427 DCHECK(IsImageBinSlotAssigned(object));
428}
429
Vladimir Marko20f85592015-03-19 10:07:02 +0000430void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000431 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000432 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
433 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800434 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000435 auto it = dex_file_oat_index_map_.find(dex_file);
436 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800437 ImageInfo& image_info = GetImageInfo(it->second);
438 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
439 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
440 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
441 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000442
Vladimir Marko20f85592015-03-19 10:07:02 +0000443 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700444 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -0800445 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800446 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700447 ObjPtr<mirror::DexCache> dex_cache =
448 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
449 if (dex_cache == nullptr || IsInBootImage(dex_cache.Ptr())) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700450 continue;
451 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000452 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartier0b490842016-05-25 15:05:59 -0700453 CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
454 << "Dex cache should have been pruned " << dex_file->GetLocation()
455 << "; possibly in class path";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700456 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000457 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000458 size_t oat_index = GetOatIndexForDexCache(dex_cache);
459 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800460 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100461 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800462 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
463 start + layout.TypesOffset(),
464 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100465 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800466 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
467 start + layout.MethodsOffset(),
468 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100469 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800470 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
471 start + layout.FieldsOffset(),
472 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100473 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800474 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Narayan Kamath7fe56582016-10-14 18:49:12 +0100475
476 if (dex_cache->GetResolvedMethodTypes() != nullptr) {
477 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethodTypes(),
478 start + layout.MethodTypesOffset(),
479 dex_cache);
480 }
Orion Hodson631827d2017-04-10 14:53:47 +0100481 if (dex_cache->GetResolvedCallSites() != nullptr) {
482 AddDexCacheArrayRelocation(dex_cache->GetResolvedCallSites(),
483 start + layout.CallSitesOffset(),
484 dex_cache);
485 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000486 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000487}
488
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700489void ImageWriter::AddDexCacheArrayRelocation(void* array,
490 size_t offset,
491 ObjPtr<mirror::DexCache> dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100492 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800493 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000494 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800495 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000496 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100497 }
498}
499
Mathieu Chartiere401d142015-04-22 13:56:20 -0700500void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
501 DCHECK(arr != nullptr);
502 if (kIsDebugBuild) {
503 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800504 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700505 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800506 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800507 CHECK(klass == nullptr || KeepClass(klass))
David Sehr709b0702016-10-13 09:12:37 -0700508 << Class::PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700509 }
510 }
511 }
512 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
513 // ArtMethods.
514 pointer_arrays_.emplace(arr, kBinArtMethodClean);
515}
516
Mathieu Chartier496577f2016-09-20 15:33:31 -0700517void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800518 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800519 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800520
521 // The magic happens here. We segregate objects into different bins based
522 // on how likely they are to get dirty at runtime.
523 //
524 // Likely-to-dirty objects get packed together into the same bin so that
525 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
526 // maximized.
527 //
528 // This means more pages will stay either clean or shared dirty (with zygote) and
529 // the app will use less of its own (private) memory.
530 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000531 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800532
533 if (kBinObjects) {
534 //
535 // Changing the bin of an object is purely a memory-use tuning.
536 // It has no change on runtime correctness.
537 //
538 // Memory analysis has determined that the following types of objects get dirtied
539 // the most:
540 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000541 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
542 // a fixed layout which helps improve generated code (using PC-relative addressing),
543 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
544 // Since these arrays are huge, most pages do not overlap other objects and it's not
545 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100546 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800547 // * Class'es which are verified [their clinit runs only at runtime]
548 // - classes in general [because their static fields get overwritten]
549 // - initialized classes with all-final statics are unlikely to be ever dirty,
550 // so bin them separately
551 // * Art Methods that are:
552 // - native [their native entry point is not looked up until runtime]
553 // - have declaring classes that aren't initialized
554 // [their interpreter/quick entry points are trampolines until the class
555 // becomes initialized]
556 //
557 // We also assume the following objects get dirtied either never or extremely rarely:
558 // * Strings (they are immutable)
559 // * Art methods that aren't native and have initialized declared classes
560 //
561 // We assume that "regular" bin objects are highly unlikely to become dirtied,
562 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
563 //
564 if (object->IsClass()) {
565 bin = kBinClassVerified;
566 mirror::Class* klass = object->AsClass();
567
Mathieu Chartiere401d142015-04-22 13:56:20 -0700568 // Add non-embedded vtable to the pointer array table if there is one.
569 auto* vtable = klass->GetVTable();
570 if (vtable != nullptr) {
571 AddMethodPointerArray(vtable);
572 }
573 auto* iftable = klass->GetIfTable();
574 if (iftable != nullptr) {
575 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
576 if (iftable->GetMethodArrayCount(i) > 0) {
577 AddMethodPointerArray(iftable->GetMethodArray(i));
578 }
579 }
580 }
581
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800582 if (klass->GetStatus() == Class::kStatusInitialized) {
583 bin = kBinClassInitialized;
584
585 // If the class's static fields are all final, put it into a separate bin
586 // since it's very likely it will stay clean.
587 uint32_t num_static_fields = klass->NumStaticFields();
588 if (num_static_fields == 0) {
589 bin = kBinClassInitializedFinalStatics;
590 } else {
591 // Maybe all the statics are final?
592 bool all_final = true;
593 for (uint32_t i = 0; i < num_static_fields; ++i) {
594 ArtField* field = klass->GetStaticField(i);
595 if (!field->IsFinal()) {
596 all_final = false;
597 break;
598 }
599 }
600
601 if (all_final) {
602 bin = kBinClassInitializedFinalStatics;
603 }
604 }
605 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800606 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
607 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700608 } else if (object->GetClass<kVerifyNone>() ==
609 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
610 // Instance of java lang object, probably a lock object. This means it will be dirty when we
611 // synchronize on it.
612 bin = kBinMiscDirty;
613 } else if (object->IsDexCache()) {
614 // Dex file field becomes dirty when the image is loaded.
615 bin = kBinMiscDirty;
616 }
617 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800618 }
619
Mathieu Chartier496577f2016-09-20 15:33:31 -0700620 // Assign the oat index too.
621 DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
622 oat_index_map_.emplace(object, oat_index);
623
Vladimir Marko944da602016-02-19 12:27:55 +0000624 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800625
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800626 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800627 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
628 // Move the current bin size up to accommodate the object we just assigned a bin slot.
629 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800630
631 BinSlot new_bin_slot(bin, current_offset);
632 SetImageBinSlot(object, new_bin_slot);
633
Jeff Haodcdc85b2015-12-04 14:06:18 -0800634 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800635
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800636 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800637 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800638}
639
Mathieu Chartiere401d142015-04-22 13:56:20 -0700640bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
641 if (m->IsNative()) {
642 return true;
643 }
644 mirror::Class* declaring_class = m->GetDeclaringClass();
645 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
646 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
647}
648
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800649bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
650 DCHECK(object != nullptr);
651
652 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
653 // If it's in some other state, then we haven't yet assigned an image bin slot.
654 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
655 return false;
656 } else if (kIsDebugBuild) {
657 LockWord lock_word = object->GetLockWord(false);
658 size_t offset = lock_word.ForwardingAddress();
659 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000660 size_t oat_index = GetOatIndex(object);
661 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800662 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800663 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800664 }
665 return true;
666}
667
668ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
669 DCHECK(object != nullptr);
670 DCHECK(IsImageBinSlotAssigned(object));
671
672 LockWord lock_word = object->GetLockWord(false);
673 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
674 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
675
676 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000677 size_t oat_index = GetOatIndex(object);
678 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800679 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800680
681 return bin_slot;
682}
683
Brian Carlstrom7940e442013-07-12 13:46:57 -0700684bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000685 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800686 ImageSection unused_sections[ImageHeader::kSectionCount];
687 const size_t length = RoundUp(
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700688 image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800689
Jeff Haodcdc85b2015-12-04 14:06:18 -0800690 std::string error_msg;
691 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
692 nullptr,
693 length,
694 PROT_READ | PROT_WRITE,
695 false,
696 false,
697 &error_msg));
698 if (UNLIKELY(image_info.image_.get() == nullptr)) {
699 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
700 return false;
701 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700702
Jeff Haodcdc85b2015-12-04 14:06:18 -0800703 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
704 CHECK_LE(image_info.image_end_, length);
705 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
706 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
707 if (image_info.image_bitmap_.get() == nullptr) {
708 LOG(ERROR) << "Failed to allocate memory for image bitmap";
709 return false;
710 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700711 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700712 return true;
713}
714
Vladimir Markoad06b982016-11-17 16:38:59 +0000715class ImageWriter::ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700716 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700717 bool operator()(ObjPtr<Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700718 StackHandleScope<1> hs(Thread::Current());
719 mirror::Class::ComputeName(hs.NewHandle(c));
720 return true;
721 }
722};
723
Brian Carlstrom7940e442013-07-12 13:46:57 -0700724void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700725 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700726 ComputeLazyFieldsForClassesVisitor visitor;
727 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700728}
729
Vladimir Markof25cc732017-03-16 16:18:15 +0000730static bool IsBootClassLoaderClass(ObjPtr<mirror::Class> klass)
731 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800732 return klass->GetClassLoader() == nullptr;
733}
734
735bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
736 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
737}
738
Chang Xingb2e8adc2017-07-07 17:35:37 -0700739// This visitor follows the references of an instance, recursively then prune this class
740// if a type of any field is pruned.
741class ImageWriter::PruneObjectReferenceVisitor {
742 public:
743 PruneObjectReferenceVisitor(ImageWriter* image_writer,
744 bool* early_exit,
745 std::unordered_set<mirror::Object*>* visited,
746 bool* result)
747 : image_writer_(image_writer), early_exit_(early_exit), visited_(visited), result_(result) {}
748
749 ALWAYS_INLINE void VisitRootIfNonNull(
750 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const
751 REQUIRES_SHARED(Locks::mutator_lock_) { }
752
753 ALWAYS_INLINE void VisitRoot(
754 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const
755 REQUIRES_SHARED(Locks::mutator_lock_) { }
756
757 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
758 MemberOffset offset,
759 bool is_static ATTRIBUTE_UNUSED) const
760 REQUIRES_SHARED(Locks::mutator_lock_) {
761 mirror::Object* ref =
762 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
763 if (ref == nullptr || visited_->find(ref) != visited_->end()) {
764 return;
765 }
766
767 ObjPtr<mirror::Class> klass = ref->IsClass() ? ref->AsClass() : ref->GetClass();
768 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
769 // Prune all classes using reflection because the content they held will not be fixup.
770 *result_ = true;
771 }
772
773 // Record the object visited in case of circular reference.
774 visited_->emplace(ref);
775 if (ref->IsClass()) {
776 *result_ = *result_ ||
777 image_writer_->PruneAppImageClassInternal(ref->AsClass(), early_exit_, visited_);
778 } else {
779 *result_ = *result_ ||
780 image_writer_->PruneAppImageClassInternal(klass, early_exit_, visited_);
781 ref->VisitReferences(*this, *this);
782 }
783 // Clean up before exit for next call of this function.
784 visited_->erase(ref);
785 }
786
787 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
788 ObjPtr<mirror::Reference> ref) const
789 REQUIRES_SHARED(Locks::mutator_lock_) {
790 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
791 }
792
793 ALWAYS_INLINE bool GetResult() const {
794 return result_;
795 }
796
797 private:
798 ImageWriter* image_writer_;
799 bool* early_exit_;
800 std::unordered_set<mirror::Object*>* visited_;
801 bool* const result_;
802};
803
804
Vladimir Markof25cc732017-03-16 16:18:15 +0000805bool ImageWriter::PruneAppImageClass(ObjPtr<mirror::Class> klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800806 bool early_exit = false;
Chang Xingb2e8adc2017-07-07 17:35:37 -0700807 std::unordered_set<mirror::Object*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800808 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800809}
810
Mathieu Chartier901e0702016-02-19 13:42:48 -0800811bool ImageWriter::PruneAppImageClassInternal(
Vladimir Markof25cc732017-03-16 16:18:15 +0000812 ObjPtr<mirror::Class> klass,
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800813 bool* early_exit,
Chang Xingb2e8adc2017-07-07 17:35:37 -0700814 std::unordered_set<mirror::Object*>* visited) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800815 DCHECK(early_exit != nullptr);
816 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800817 DCHECK(compile_app_image_);
Vladimir Markof25cc732017-03-16 16:18:15 +0000818 if (klass == nullptr || IsInBootImage(klass.Ptr())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700819 return false;
820 }
Vladimir Markof25cc732017-03-16 16:18:15 +0000821 auto found = prune_class_memo_.find(klass.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800822 if (found != prune_class_memo_.end()) {
823 // Already computed, return the found value.
824 return found->second;
825 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800826 // Circular dependencies, return false but do not store the result in the memoization table.
Vladimir Markof25cc732017-03-16 16:18:15 +0000827 if (visited->find(klass.Ptr()) != visited->end()) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800828 *early_exit = true;
829 return false;
830 }
Vladimir Markof25cc732017-03-16 16:18:15 +0000831 visited->emplace(klass.Ptr());
Mathieu Chartier901e0702016-02-19 13:42:48 -0800832 bool result = IsBootClassLoaderClass(klass);
833 std::string temp;
834 // Prune if not an image class, this handles any broken sets of image classes such as having a
835 // class in the set but not it's superclass.
836 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800837 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800838 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
839 // app image.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000840 if (klass->IsErroneous()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800841 result = true;
842 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700843 ObjPtr<mirror::ClassExt> ext(klass->GetExtData());
844 CHECK(ext.IsNull() || ext->GetVerifyError() == nullptr) << klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800845 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800846 if (!result) {
847 // Check interfaces since these wont be visited through VisitReferences.)
848 mirror::IfTable* if_table = klass->GetIfTable();
849 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800850 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
851 &my_early_exit,
852 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800853 }
854 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800855 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800856 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
857 &my_early_exit,
858 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800859 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800860 // Check static fields and their classes.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000861 if (klass->IsResolved() && klass->NumReferenceStaticFields() != 0) {
862 size_t num_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800863 // Presumably GC can happen when we are cross compiling, it should not cause performance
864 // problems to do pointer size logic.
865 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
866 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
867 for (size_t i = 0u; i < num_static_fields; ++i) {
868 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
869 if (ref != nullptr) {
870 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800871 result = result || PruneAppImageClassInternal(ref->AsClass(),
872 &my_early_exit,
873 visited);
874 } else {
Chang Xingb2e8adc2017-07-07 17:35:37 -0700875 mirror::Class* type = ref->GetClass();
876 result = result || PruneAppImageClassInternal(type,
Mathieu Chartier901e0702016-02-19 13:42:48 -0800877 &my_early_exit,
878 visited);
Chang Xingb2e8adc2017-07-07 17:35:37 -0700879 if (!result) {
880 // For non-class case, also go through all the types mentioned by it's fields'
881 // references recursively to decide whether to keep this class.
882 bool tmp = false;
883 PruneObjectReferenceVisitor visitor(this, &my_early_exit, visited, &tmp);
884 ref->VisitReferences(visitor, visitor);
885 result = result || tmp;
886 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800887 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800888 }
889 field_offset = MemberOffset(field_offset.Uint32Value() +
890 sizeof(mirror::HeapReference<mirror::Object>));
891 }
892 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800893 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
894 &my_early_exit,
895 visited);
Mathieu Chartierc27bc402016-08-05 16:09:09 -0700896 // Remove the class if the dex file is not in the set of dex files. This happens for classes that
Mathieu Chartier72041a02017-07-14 18:23:25 -0700897 // are from uses-library if there is no profile. b/30688277
Mathieu Chartierc27bc402016-08-05 16:09:09 -0700898 mirror::DexCache* dex_cache = klass->GetDexCache();
899 if (dex_cache != nullptr) {
900 result = result ||
901 dex_file_oat_index_map_.find(dex_cache->GetDexFile()) == dex_file_oat_index_map_.end();
902 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800903 // Erase the element we stored earlier since we are exiting the function.
Vladimir Markof25cc732017-03-16 16:18:15 +0000904 auto it = visited->find(klass.Ptr());
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800905 DCHECK(it != visited->end());
906 visited->erase(it);
907 // Only store result if it is true or none of the calls early exited due to circular
908 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
909 // a child call and we can remember the result.
910 if (result == true || !my_early_exit || visited->empty()) {
Vladimir Markof25cc732017-03-16 16:18:15 +0000911 prune_class_memo_[klass.Ptr()] = result;
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800912 }
913 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800914 return result;
915}
916
Vladimir Markof25cc732017-03-16 16:18:15 +0000917bool ImageWriter::KeepClass(ObjPtr<mirror::Class> klass) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800918 if (klass == nullptr) {
919 return false;
920 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800921 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
922 // Already in boot image, return true.
923 return true;
924 }
925 std::string temp;
926 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
927 return false;
928 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800929 if (compile_app_image_) {
930 // For app images, we need to prune boot loader classes that are not in the boot image since
931 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800932 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800933 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800934 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800935 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700936}
937
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000938class ImageWriter::PruneClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700939 public:
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000940 PruneClassesVisitor(ImageWriter* image_writer, ObjPtr<mirror::ClassLoader> class_loader)
941 : image_writer_(image_writer),
942 class_loader_(class_loader),
943 classes_to_prune_(),
944 defined_class_count_(0u) { }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700945
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000946 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700947 if (!image_writer_->KeepClass(klass.Ptr())) {
948 classes_to_prune_.insert(klass.Ptr());
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000949 if (klass->GetClassLoader() == class_loader_) {
950 ++defined_class_count_;
951 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700952 }
953 return true;
954 }
955
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000956 size_t Prune() REQUIRES_SHARED(Locks::mutator_lock_) {
957 ClassTable* class_table =
958 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader_);
959 for (mirror::Class* klass : classes_to_prune_) {
960 std::string storage;
961 const char* descriptor = klass->GetDescriptor(&storage);
962 bool result = class_table->Remove(descriptor);
963 DCHECK(result);
964 DCHECK(!class_table->Remove(descriptor)) << descriptor;
965 }
966 return defined_class_count_;
967 }
968
969 private:
Vladimir Markocb5ab352016-11-30 15:31:13 +0000970 ImageWriter* const image_writer_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000971 const ObjPtr<mirror::ClassLoader> class_loader_;
972 std::unordered_set<mirror::Class*> classes_to_prune_;
973 size_t defined_class_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700974};
975
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000976class ImageWriter::PruneClassLoaderClassesVisitor : public ClassLoaderVisitor {
977 public:
978 explicit PruneClassLoaderClassesVisitor(ImageWriter* image_writer)
979 : image_writer_(image_writer), removed_class_count_(0) {}
980
981 virtual void Visit(ObjPtr<mirror::ClassLoader> class_loader) OVERRIDE
982 REQUIRES_SHARED(Locks::mutator_lock_) {
983 PruneClassesVisitor classes_visitor(image_writer_, class_loader);
984 ClassTable* class_table =
985 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader);
986 class_table->Visit(classes_visitor);
987 removed_class_count_ += classes_visitor.Prune();
Vladimir Markof25cc732017-03-16 16:18:15 +0000988
989 // Record app image class loader. The fake boot class loader should not get registered
990 // and we should end up with only one class loader for an app and none for boot image.
991 if (class_loader != nullptr && class_table != nullptr) {
992 DCHECK(class_loader_ == nullptr);
993 class_loader_ = class_loader;
994 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000995 }
996
997 size_t GetRemovedClassCount() const {
998 return removed_class_count_;
999 }
1000
Vladimir Markof25cc732017-03-16 16:18:15 +00001001 ObjPtr<mirror::ClassLoader> GetClassLoader() const REQUIRES_SHARED(Locks::mutator_lock_) {
1002 return class_loader_;
1003 }
1004
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001005 private:
1006 ImageWriter* const image_writer_;
1007 size_t removed_class_count_;
Vladimir Markof25cc732017-03-16 16:18:15 +00001008 ObjPtr<mirror::ClassLoader> class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001009};
1010
1011void ImageWriter::VisitClassLoaders(ClassLoaderVisitor* visitor) {
1012 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1013 visitor->Visit(nullptr); // Visit boot class loader.
1014 Runtime::Current()->GetClassLinker()->VisitClassLoaders(visitor);
1015}
1016
Vladimir Markof25cc732017-03-16 16:18:15 +00001017void ImageWriter::PruneAndPreloadDexCache(ObjPtr<mirror::DexCache> dex_cache,
1018 ObjPtr<mirror::ClassLoader> class_loader) {
1019 // To ensure deterministic contents of the hash-based arrays, each slot shall contain
1020 // the candidate with the lowest index. As we're processing entries in increasing index
1021 // order, this means trying to look up the entry for the current index if the slot is
1022 // empty or if it contains a higher index.
1023
1024 Runtime* runtime = Runtime::Current();
1025 ClassLinker* class_linker = runtime->GetClassLinker();
Vladimir Markof25cc732017-03-16 16:18:15 +00001026 const DexFile& dex_file = *dex_cache->GetDexFile();
1027 // Prune methods.
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001028 mirror::MethodDexCacheType* resolved_methods = dex_cache->GetResolvedMethods();
1029 dex::TypeIndex last_class_idx; // Initialized to invalid index.
1030 ObjPtr<mirror::Class> last_class = nullptr;
1031 for (size_t i = 0, num = dex_cache->GetDexFile()->NumMethodIds(); i != num; ++i) {
1032 uint32_t slot_idx = dex_cache->MethodSlotIndex(i);
1033 auto pair =
1034 mirror::DexCache::GetNativePairPtrSize(resolved_methods, slot_idx, target_ptr_size_);
1035 uint32_t stored_index = pair.index;
1036 ArtMethod* method = pair.object;
1037 if (method != nullptr && i > stored_index) {
1038 continue; // Already checked.
1039 }
Vladimir Marko3b155452017-07-05 11:41:33 +01001040 // Check if the referenced class is in the image. Note that we want to check the referenced
1041 // class rather than the declaring class to preserve the semantics, i.e. using a MethodId
1042 // results in resolving the referenced class and that can for example throw OOME.
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001043 const DexFile::MethodId& method_id = dex_file.GetMethodId(i);
1044 if (method_id.class_idx_ != last_class_idx) {
1045 last_class_idx = method_id.class_idx_;
1046 last_class = class_linker->LookupResolvedType(
1047 dex_file, last_class_idx, dex_cache, class_loader);
1048 if (last_class != nullptr && !KeepClass(last_class)) {
1049 last_class = nullptr;
1050 }
1051 }
1052 if (method == nullptr || i < stored_index) {
1053 if (last_class != nullptr) {
1054 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
1055 Signature signature = dex_file.GetMethodSignature(method_id);
1056 if (last_class->IsInterface()) {
1057 method = last_class->FindInterfaceMethod(name, signature, target_ptr_size_);
1058 } else {
1059 method = last_class->FindClassMethod(name, signature, target_ptr_size_);
1060 }
1061 if (method != nullptr) {
1062 // If the referenced class is in the image, the defining class must also be there.
1063 DCHECK(KeepClass(method->GetDeclaringClass()));
1064 dex_cache->SetResolvedMethod(i, method, target_ptr_size_);
1065 }
1066 }
1067 } else {
1068 DCHECK_EQ(i, stored_index);
1069 if (last_class == nullptr) {
1070 dex_cache->ClearResolvedMethod(stored_index, target_ptr_size_);
1071 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001072 }
1073 }
1074 // Prune fields and make the contents of the field array deterministic.
1075 mirror::FieldDexCacheType* resolved_fields = dex_cache->GetResolvedFields();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001076 last_class_idx = dex::TypeIndex(); // Initialized to invalid index.
1077 last_class = nullptr;
Vladimir Markof25cc732017-03-16 16:18:15 +00001078 for (size_t i = 0, end = dex_file.NumFieldIds(); i < end; ++i) {
1079 uint32_t slot_idx = dex_cache->FieldSlotIndex(i);
1080 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_fields, slot_idx, target_ptr_size_);
1081 uint32_t stored_index = pair.index;
1082 ArtField* field = pair.object;
1083 if (field != nullptr && i > stored_index) {
1084 continue; // Already checked.
1085 }
1086 // Check if the referenced class is in the image. Note that we want to check the referenced
1087 // class rather than the declaring class to preserve the semantics, i.e. using a FieldId
1088 // results in resolving the referenced class and that can for example throw OOME.
1089 const DexFile::FieldId& field_id = dex_file.GetFieldId(i);
1090 if (field_id.class_idx_ != last_class_idx) {
1091 last_class_idx = field_id.class_idx_;
1092 last_class = class_linker->LookupResolvedType(
1093 dex_file, last_class_idx, dex_cache, class_loader);
1094 if (last_class != nullptr && !KeepClass(last_class)) {
1095 last_class = nullptr;
1096 }
1097 }
1098 if (field == nullptr || i < stored_index) {
1099 if (last_class != nullptr) {
1100 const char* name = dex_file.StringDataByIdx(field_id.name_idx_);
1101 const char* type = dex_file.StringByTypeIdx(field_id.type_idx_);
1102 field = mirror::Class::FindField(Thread::Current(), last_class, name, type);
1103 if (field != nullptr) {
1104 // If the referenced class is in the image, the defining class must also be there.
1105 DCHECK(KeepClass(field->GetDeclaringClass()));
1106 dex_cache->SetResolvedField(i, field, target_ptr_size_);
1107 }
1108 }
1109 } else {
1110 DCHECK_EQ(i, stored_index);
1111 if (last_class == nullptr) {
1112 dex_cache->ClearResolvedField(stored_index, target_ptr_size_);
1113 }
1114 }
1115 }
1116 // Prune types and make the contents of the type array deterministic.
1117 // This is done after fields and methods as their lookup can touch the types array.
1118 for (size_t i = 0, end = dex_cache->GetDexFile()->NumTypeIds(); i < end; ++i) {
1119 dex::TypeIndex type_idx(i);
1120 uint32_t slot_idx = dex_cache->TypeSlotIndex(type_idx);
1121 mirror::TypeDexCachePair pair =
1122 dex_cache->GetResolvedTypes()[slot_idx].load(std::memory_order_relaxed);
1123 uint32_t stored_index = pair.index;
1124 ObjPtr<mirror::Class> klass = pair.object.Read();
1125 if (klass == nullptr || i < stored_index) {
1126 klass = class_linker->LookupResolvedType(dex_file, type_idx, dex_cache, class_loader);
1127 if (klass != nullptr) {
1128 DCHECK_EQ(dex_cache->GetResolvedType(type_idx), klass);
1129 stored_index = i; // For correct clearing below if not keeping the `klass`.
1130 }
1131 } else if (i == stored_index && !KeepClass(klass)) {
1132 dex_cache->ClearResolvedType(dex::TypeIndex(stored_index));
1133 }
1134 }
1135 // Strings do not need pruning, but the contents of the string array must be deterministic.
1136 for (size_t i = 0, end = dex_cache->GetDexFile()->NumStringIds(); i < end; ++i) {
1137 dex::StringIndex string_idx(i);
1138 uint32_t slot_idx = dex_cache->StringSlotIndex(string_idx);
1139 mirror::StringDexCachePair pair =
1140 dex_cache->GetStrings()[slot_idx].load(std::memory_order_relaxed);
1141 uint32_t stored_index = pair.index;
1142 ObjPtr<mirror::String> string = pair.object.Read();
1143 if (string == nullptr || i < stored_index) {
1144 string = class_linker->LookupString(dex_file, string_idx, dex_cache);
1145 DCHECK(string == nullptr || dex_cache->GetResolvedString(string_idx) == string);
1146 }
1147 }
1148}
1149
Brian Carlstrom7940e442013-07-12 13:46:57 -07001150void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001151 Runtime* runtime = Runtime::Current();
1152 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001153 Thread* self = Thread::Current();
Vladimir Markof25cc732017-03-16 16:18:15 +00001154 ScopedAssertNoThreadSuspension sa(__FUNCTION__);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001155
Mathieu Chartier72041a02017-07-14 18:23:25 -07001156 // Prune uses-library dex caches. Only prune the uses-library dex caches since we want to make
1157 // sure the other ones don't get unloaded before the OatWriter runs.
1158 class_linker->VisitClassTables(
1159 [&](ClassTable* table) REQUIRES_SHARED(Locks::mutator_lock_) {
1160 table->RemoveStrongRoots(
1161 [&](GcRoot<mirror::Object> root) REQUIRES_SHARED(Locks::mutator_lock_) {
1162 ObjPtr<mirror::Object> obj = root.Read();
1163 if (obj->IsDexCache()) {
1164 // Return true if the dex file is not one of the ones in the map.
1165 return dex_file_oat_index_map_.find(obj->AsDexCache()->GetDexFile()) ==
1166 dex_file_oat_index_map_.end();
1167 }
1168 // Return false to avoid removing.
1169 return false;
1170 });
1171 });
Mathieu Chartier696632e2016-06-03 17:47:32 -07001172
Brian Carlstrom7940e442013-07-12 13:46:57 -07001173 // Remove the undesired classes from the class roots.
Vladimir Markof25cc732017-03-16 16:18:15 +00001174 ObjPtr<mirror::ClassLoader> class_loader;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001175 {
1176 PruneClassLoaderClassesVisitor class_loader_visitor(this);
1177 VisitClassLoaders(&class_loader_visitor);
1178 VLOG(compiler) << "Pruned " << class_loader_visitor.GetRemovedClassCount() << " classes";
Vladimir Markof25cc732017-03-16 16:18:15 +00001179 class_loader = class_loader_visitor.GetClassLoader();
1180 DCHECK_EQ(class_loader != nullptr, compile_app_image_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001181 }
1182
1183 // Clear references to removed classes from the DexCaches.
Vladimir Markof25cc732017-03-16 16:18:15 +00001184 std::vector<ObjPtr<mirror::DexCache>> dex_caches;
1185 {
1186 ReaderMutexLock mu2(self, *Locks::dex_lock_);
1187 dex_caches.reserve(class_linker->GetDexCachesData().size());
1188 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1189 if (self->IsJWeakCleared(data.weak_root)) {
1190 continue;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001191 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001192 dex_caches.push_back(self->DecodeJObject(data.weak_root)->AsDexCache());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001193 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001194 }
1195 for (ObjPtr<mirror::DexCache> dex_cache : dex_caches) {
1196 PruneAndPreloadDexCache(dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001197 }
Andreas Gampe8ac75952015-06-02 21:01:45 -07001198
1199 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
1200 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001201
1202 // Clear to save RAM.
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00001203 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001204}
1205
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001206void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001207 if (compiler_driver_.GetImageClasses() != nullptr) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001208 auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1209 if (obj->IsClass() && !IsInBootImage(obj)) {
1210 Class* klass = obj->AsClass();
1211 if (!KeepClass(klass)) {
1212 DumpImageClasses();
1213 std::string temp;
1214 CHECK(KeepClass(klass))
1215 << Runtime::Current()->GetHeap()->GetVerification()->FirstPathFromRootSet(klass);
1216 }
1217 }
1218 };
Mathieu Chartier590fee92013-09-13 13:46:47 -07001219 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001220 heap->VisitObjects(visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001221 }
1222}
1223
1224void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001225 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001226 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001227 for (const std::string& image_class : *image_classes) {
1228 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001229 }
1230}
1231
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001232mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
1233 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +00001234 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001235 ObjPtr<mirror::String> const found = image_info.intern_table_->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001236 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
1237 << string->ToModifiedUtf8();
1238 if (found != nullptr) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001239 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001240 }
1241 }
1242 if (compile_app_image_) {
1243 Runtime* const runtime = Runtime::Current();
Mathieu Chartier9e868092016-10-31 14:58:04 -07001244 ObjPtr<mirror::String> found = runtime->GetInternTable()->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001245 // If we found it in the runtime intern table it could either be in the boot image or interned
1246 // during app image compilation. If it was in the boot image return that, otherwise return null
1247 // since it belongs to another image space.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001248 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found.Ptr())) {
1249 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001250 }
1251 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
1252 << string->ToModifiedUtf8();
1253 }
1254 return nullptr;
1255}
1256
Brian Carlstrom7940e442013-07-12 13:46:57 -07001257
Vladimir Marko944da602016-02-19 12:27:55 +00001258ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001259 Runtime* runtime = Runtime::Current();
1260 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001261 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001262 StackHandleScope<3> hs(self);
1263 Handle<Class> object_array_class(hs.NewHandle(
1264 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001265
Jeff Haodcdc85b2015-12-04 14:06:18 -08001266 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +00001267 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001268 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +00001269 size_t image_oat_index = pair.second;
1270 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001271 image_dex_files.insert(image_dex_file);
1272 }
1273 }
1274
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001275 // build an Object[] of all the DexCaches used in the source_space_.
1276 // Since we can't hold the dex lock when allocating the dex_caches
1277 // ObjectArray, we lock the dex lock twice, first to get the number
1278 // of dex caches first and then lock it again to copy the dex
1279 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001280 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001281 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001282 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001283 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001284 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001285 ObjPtr<mirror::DexCache> dex_cache =
1286 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001287 if (dex_cache == nullptr) {
1288 continue;
1289 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001290 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001291 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001292 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1293 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001294 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001295 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001296 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001297 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001298 CHECK(dex_caches != nullptr) << "Failed to allocate a dex cache array.";
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001299 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001300 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001301 size_t non_image_dex_caches = 0;
1302 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001303 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001304 ObjPtr<mirror::DexCache> dex_cache =
1305 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001306 if (dex_cache == nullptr) {
1307 continue;
1308 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001309 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001310 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001311 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1312 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001313 }
1314 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1315 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001316 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001317 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001318 ObjPtr<mirror::DexCache> dex_cache =
1319 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001320 if (dex_cache == nullptr) {
1321 continue;
1322 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001323 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001324 if (!IsInBootImage(dex_cache.Ptr()) &&
1325 image_dex_files.find(dex_file) != image_dex_files.end()) {
1326 dex_caches->Set<false>(i, dex_cache.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001327 ++i;
1328 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001329 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001330 }
1331
1332 // build an Object[] of the roots needed to restore the runtime
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001333 int32_t image_roots_size = ImageHeader::NumberOfImageRoots(compile_app_image_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001334 auto image_roots(hs.NewHandle(
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001335 ObjectArray<Object>::Alloc(self, object_array_class.Get(), image_roots_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001336 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001337 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001338 // image_roots[ImageHeader::kClassLoader] will be set later for app image.
1339 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1340 "Class loader should be the last image root.");
1341 for (int32_t i = 0; i < ImageHeader::kImageRootsMax - 1; ++i) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001342 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001343 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001344 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001345}
1346
Mathieu Chartier496577f2016-09-20 15:33:31 -07001347mirror::Object* ImageWriter::TryAssignBinSlot(WorkStack& work_stack,
1348 mirror::Object* obj,
1349 size_t oat_index) {
1350 if (obj == nullptr || IsInBootImage(obj)) {
1351 // Object is null or already in the image, there is no work to do.
1352 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001353 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001354 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001355 // We want to intern all strings but also assign offsets for the source string. Since the
1356 // pruning phase has already happened, if we intern a string to one in the image we still
1357 // end up copying an unreachable string.
1358 if (obj->IsString()) {
1359 // Need to check if the string is already interned in another image info so that we don't have
1360 // the intern tables of two different images contain the same string.
1361 mirror::String* interned = FindInternedString(obj->AsString());
1362 if (interned == nullptr) {
1363 // Not in another image space, insert to our table.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001364 interned =
1365 GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString()).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001366 DCHECK_EQ(interned, obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001367 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001368 } else if (obj->IsDexCache()) {
1369 oat_index = GetOatIndexForDexCache(obj->AsDexCache());
1370 } else if (obj->IsClass()) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001371 // Visit and assign offsets for fields and field arrays.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001372 mirror::Class* as_klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001373 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Vladimir Marko72ab6842017-01-20 19:32:50 +00001374 DCHECK(!as_klass->IsErroneous()) << as_klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001375 if (compile_app_image_) {
1376 // Extra sanity, no boot loader classes should be left!
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00001377 CHECK(!IsBootClassLoaderClass(as_klass)) << as_klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001378 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001379 LengthPrefixedArray<ArtField>* fields[] = {
1380 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1381 };
Mathieu Chartier496577f2016-09-20 15:33:31 -07001382 // Overwrite the oat index value since the class' dex cache is more accurate of where it
1383 // belongs.
1384 oat_index = GetOatIndexForDexCache(dex_cache);
Vladimir Marko944da602016-02-19 12:27:55 +00001385 ImageInfo& image_info = GetImageInfo(oat_index);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001386 if (!compile_app_image_) {
1387 // Note: Avoid locking to prevent lock order violations from root visiting;
1388 // image_info.class_table_ is only accessed from the image writer.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001389 image_info.class_table_->InsertWithoutLocks(as_klass);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001390 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001391 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1392 // Total array length including header.
1393 if (cur_fields != nullptr) {
1394 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1395 // Forward the entire array at once.
1396 auto it = native_object_relocations_.find(cur_fields);
1397 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1398 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001399 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001400 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001401 native_object_relocations_.emplace(
1402 cur_fields,
1403 NativeObjectRelocation {
1404 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1405 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001406 offset += header_size;
1407 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001408 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001409 // Need to forward arrays separate of fields.
1410 ArtField* field = &cur_fields->At(i);
1411 auto it2 = native_object_relocations_.find(field);
1412 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
David Sehr709b0702016-10-13 09:12:37 -07001413 << " already assigned " << field->PrettyField() << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001414 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001415 native_object_relocations_.emplace(
1416 field,
1417 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001418 offset += sizeof(ArtField);
1419 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001420 }
1421 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001422 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001423 size_t num_methods = as_klass->NumMethods();
1424 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001425 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001426 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1427 if (WillMethodBeDirty(&m)) {
1428 any_dirty = true;
1429 break;
1430 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001431 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001432 NativeObjectRelocationType type = any_dirty
1433 ? kNativeObjectRelocationTypeArtMethodDirty
1434 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001435 Bin bin_type = BinTypeForNativeRelocationType(type);
1436 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001437 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1438 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001439 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1440 method_size,
1441 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001442 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001443 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001444 CHECK(it == native_object_relocations_.end())
1445 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001446 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001447 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001448 native_object_relocations_.emplace(array,
1449 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001450 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001451 offset,
1452 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1453 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001454 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001455 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001456 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001457 }
Alex Lighte64300b2015-12-15 15:02:47 -08001458 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001459 }
1460 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1461 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001462 if (as_klass->ShouldHaveImt()) {
1463 ImTable* imt = as_klass->GetImt(target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001464 if (TryAssignImTableOffset(imt, oat_index)) {
1465 // Since imt's can be shared only do this the first time to not double count imt method
1466 // fixups.
1467 for (size_t i = 0; i < ImTable::kSize; ++i) {
1468 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
1469 DCHECK(imt_method != nullptr);
1470 if (imt_method->IsRuntimeMethod() &&
1471 !IsInBootImage(imt_method) &&
1472 !NativeRelocationAssigned(imt_method)) {
1473 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
1474 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001475 }
1476 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001477 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001478 } else if (obj->IsClassLoader()) {
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001479 // Register the class loader if it has a class table.
1480 // The fake boot class loader should not get registered and we should end up with only one
1481 // class loader.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001482 mirror::ClassLoader* class_loader = obj->AsClassLoader();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001483 if (class_loader->GetClassTable() != nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001484 DCHECK(compile_app_image_);
1485 DCHECK(class_loaders_.empty());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001486 class_loaders_.insert(class_loader);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001487 ImageInfo& image_info = GetImageInfo(oat_index);
1488 // Note: Avoid locking to prevent lock order violations from root visiting;
1489 // image_info.class_table_ table is only accessed from the image writer
1490 // and class_loader->GetClassTable() is iterated but not modified.
1491 image_info.class_table_->CopyWithoutLocks(*class_loader->GetClassTable());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001492 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001493 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001494 AssignImageBinSlot(obj, oat_index);
1495 work_stack.emplace(obj, oat_index);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001496 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001497 if (obj->IsString()) {
1498 // Always return the interned string if there exists one.
1499 mirror::String* interned = FindInternedString(obj->AsString());
1500 if (interned != nullptr) {
1501 return interned;
1502 }
1503 }
1504 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001505}
1506
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001507bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1508 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1509}
1510
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001511bool ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001512 // No offset, or already assigned.
1513 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001514 return false;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001515 }
1516 // If the method is a conflict method we also want to assign the conflict table offset.
1517 ImageInfo& image_info = GetImageInfo(oat_index);
1518 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1519 native_object_relocations_.emplace(
1520 imt,
1521 NativeObjectRelocation {
1522 oat_index,
1523 image_info.bin_slot_sizes_[kBinImTable],
1524 kNativeObjectRelocationTypeIMTable});
1525 image_info.bin_slot_sizes_[kBinImTable] += size;
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001526 return true;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001527}
1528
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001529void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1530 // No offset, or already assigned.
1531 if (table == nullptr || NativeRelocationAssigned(table)) {
1532 return;
1533 }
1534 CHECK(!IsInBootImage(table));
1535 // If the method is a conflict method we also want to assign the conflict table offset.
1536 ImageInfo& image_info = GetImageInfo(oat_index);
1537 const size_t size = table->ComputeSize(target_ptr_size_);
1538 native_object_relocations_.emplace(
1539 table,
1540 NativeObjectRelocation {
1541 oat_index,
1542 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1543 kNativeObjectRelocationTypeIMTConflictTable});
1544 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1545}
1546
Jeff Haodcdc85b2015-12-04 14:06:18 -08001547void ImageWriter::AssignMethodOffset(ArtMethod* method,
1548 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001549 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001550 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001551 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
David Sehr709b0702016-10-13 09:12:37 -07001552 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001553 if (method->IsRuntimeMethod()) {
1554 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1555 }
Vladimir Marko944da602016-02-19 12:27:55 +00001556 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001557 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001558 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001559 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001560}
1561
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001562void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001563 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001564 CHECK(obj != nullptr);
1565
1566 // We know the bin slot, and the total bin sizes for all objects by now,
1567 // so calculate the object's final image offset.
1568
1569 DCHECK(IsImageBinSlotAssigned(obj));
1570 BinSlot bin_slot = GetImageBinSlot(obj);
1571 // Change the lockword from a bin slot into an offset
1572 AssignImageOffset(obj, bin_slot);
1573}
1574
Mathieu Chartier496577f2016-09-20 15:33:31 -07001575class ImageWriter::VisitReferencesVisitor {
1576 public:
1577 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index)
1578 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {}
1579
1580 // Fix up separately since we also need to fix up method entrypoints.
1581 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1582 REQUIRES_SHARED(Locks::mutator_lock_) {
1583 if (!root->IsNull()) {
1584 VisitRoot(root);
1585 }
1586 }
1587
1588 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1589 REQUIRES_SHARED(Locks::mutator_lock_) {
1590 root->Assign(VisitReference(root->AsMirrorPtr()));
1591 }
1592
Mathieu Chartier31e88222016-10-14 18:43:19 -07001593 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
Mathieu Chartier496577f2016-09-20 15:33:31 -07001594 MemberOffset offset,
1595 bool is_static ATTRIBUTE_UNUSED) const
1596 REQUIRES_SHARED(Locks::mutator_lock_) {
1597 mirror::Object* ref =
1598 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1599 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1600 }
1601
Mathieu Chartier31e88222016-10-14 18:43:19 -07001602 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1603 ObjPtr<mirror::Reference> ref) const
Mathieu Chartier496577f2016-09-20 15:33:31 -07001604 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001605 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001606 }
1607
1608 private:
1609 mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1610 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_);
1611 }
1612
1613 ImageWriter* const image_writer_;
1614 WorkStack* const work_stack_;
1615 const size_t oat_index_;
1616};
1617
1618class ImageWriter::GetRootsVisitor : public RootVisitor {
1619 public:
1620 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {}
1621
1622 void VisitRoots(mirror::Object*** roots,
1623 size_t count,
1624 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1625 REQUIRES_SHARED(Locks::mutator_lock_) {
1626 for (size_t i = 0; i < count; ++i) {
1627 roots_->push_back(*roots[i]);
1628 }
1629 }
1630
1631 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1632 size_t count,
1633 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1634 REQUIRES_SHARED(Locks::mutator_lock_) {
1635 for (size_t i = 0; i < count; ++i) {
1636 roots_->push_back(roots[i]->AsMirrorPtr());
1637 }
1638 }
1639
1640 private:
1641 std::vector<mirror::Object*>* const roots_;
1642};
1643
1644void ImageWriter::ProcessWorkStack(WorkStack* work_stack) {
1645 while (!work_stack->empty()) {
1646 std::pair<mirror::Object*, size_t> pair(work_stack->top());
1647 work_stack->pop();
1648 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second);
1649 // Walk references and assign bin slots for them.
1650 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1651 visitor,
1652 visitor);
1653 }
1654}
1655
Vladimir Markof4da6752014-08-01 19:04:18 +01001656void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001657 Thread* const self = Thread::Current();
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07001658 VariableSizedHandleScope handles(self);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001659 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001660 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1661 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001662 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001663
Mathieu Chartier496577f2016-09-20 15:33:31 -07001664 Runtime* const runtime = Runtime::Current();
1665 gc::Heap* const heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001666
Mathieu Chartier31e89252013-08-28 11:29:12 -07001667 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001668 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001669 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001670
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001671 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001672 // Write the image runtime methods.
1673 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1674 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1675 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001676 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001677 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves);
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001678 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001679 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly);
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001680 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001681 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001682 image_methods_[ImageHeader::kSaveEverythingMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001683 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001684 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001685 for (auto* m : image_methods_) {
1686 CHECK(m != nullptr);
1687 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001688 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1689 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001690 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001691 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001692 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001693
Mathieu Chartier496577f2016-09-20 15:33:31 -07001694 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
1695 // this lock while holding other locks may cause lock order violations.
Andreas Gampe1c158a02017-07-13 17:26:19 -07001696 {
1697 auto deflate_monitor = [](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1698 Monitor::Deflate(Thread::Current(), obj);
1699 };
1700 heap->VisitObjects(deflate_monitor);
1701 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001702
1703 // Work list of <object, oat_index> for objects. Everything on the stack must already be
1704 // assigned a bin slot.
1705 WorkStack work_stack;
1706
1707 // Special case interned strings to put them in the image they are likely to be resolved from.
1708 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
1709 auto it = dex_file_oat_index_map_.find(dex_file);
1710 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1711 const size_t oat_index = it->second;
1712 InternTable* const intern_table = runtime->GetInternTable();
1713 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
1714 uint32_t utf16_length;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001715 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(dex::StringIndex(i),
1716 &utf16_length);
Mathieu Chartier9e868092016-10-31 14:58:04 -07001717 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001718 TryAssignBinSlot(work_stack, string, oat_index);
1719 }
1720 }
1721
1722 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor
1723 // visits roots while holding various locks.
1724 {
1725 std::vector<mirror::Object*> roots;
1726 GetRootsVisitor root_visitor(&roots);
1727 runtime->VisitRoots(&root_visitor);
1728 for (mirror::Object* obj : roots) {
1729 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex());
1730 }
1731 }
1732 ProcessWorkStack(&work_stack);
1733
1734 // For app images, there may be objects that are only held live by the by the boot image. One
1735 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback
1736 // does not fail any checks. TODO: We should probably avoid copying these objects.
1737 if (compile_app_image_) {
1738 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) {
1739 DCHECK(space->IsImageSpace());
1740 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1741 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1742 reinterpret_cast<uintptr_t>(space->Limit()),
1743 [this, &work_stack](mirror::Object* obj)
1744 REQUIRES_SHARED(Locks::mutator_lock_) {
1745 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex());
1746 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot).
1747 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1748 visitor,
1749 visitor);
1750 });
1751 }
1752 // Process the work stack in case anything was added by TryAssignBinSlot.
1753 ProcessWorkStack(&work_stack);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001754
1755 // Store the class loader in the class roots.
1756 CHECK_EQ(class_loaders_.size(), 1u);
1757 CHECK_EQ(image_roots.size(), 1u);
1758 CHECK(*class_loaders_.begin() != nullptr);
1759 image_roots[0]->Set<false>(ImageHeader::kClassLoader, *class_loaders_.begin());
Mathieu Chartier496577f2016-09-20 15:33:31 -07001760 }
1761
1762 // Verify that all objects have assigned image bin slots.
Andreas Gampe1c158a02017-07-13 17:26:19 -07001763 {
1764 auto ensure_bin_slots_assigned = [&](mirror::Object* obj)
1765 REQUIRES_SHARED(Locks::mutator_lock_) {
1766 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) {
1767 CHECK(IsImageBinSlotAssigned(obj)) << mirror::Object::PrettyTypeOf(obj) << " " << obj;
1768 }
1769 };
1770 heap->VisitObjects(ensure_bin_slots_assigned);
1771 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001772
Vladimir Marko05792b92015-08-03 11:56:49 +01001773 // Calculate size of the dex cache arrays slot and prepare offsets.
1774 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001775
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001776 // Calculate the sizes of the intern tables, class tables, and fixup tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001777 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001778 // Calculate how big the intern table will be after being serialized.
1779 InternTable* const intern_table = image_info.intern_table_.get();
1780 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
Vladimir Marko1a1de672016-10-13 12:53:15 +01001781 if (intern_table->StrongSize() != 0u) {
1782 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1783 }
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001784
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001785 // Calculate the size of the class table.
1786 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001787 DCHECK_EQ(image_info.class_table_->NumReferencedZygoteClasses(), 0u);
1788 if (image_info.class_table_->NumReferencedNonZygoteClasses() != 0u) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001789 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
1790 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001791 }
1792
Vladimir Markocf36d492015-08-12 19:27:26 +01001793 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001794 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001795 size_t bin_offset = image_objects_offset_begin_;
1796 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001797 switch (i) {
1798 case kBinArtMethodClean:
1799 case kBinArtMethodDirty: {
1800 bin_offset = RoundUp(bin_offset, method_alignment);
1801 break;
1802 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001803 case kBinDexCacheArray:
Vladimir Markof44d36c2017-03-14 14:18:46 +00001804 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment(target_ptr_size_));
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001805 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001806 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001807 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001808 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001809 break;
1810 }
1811 default: {
1812 // Normal alignment.
1813 }
1814 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001815 image_info.bin_slot_offsets_[i] = bin_offset;
1816 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001817 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001818 // NOTE: There may be additional padding between the bin slots and the intern table.
1819 DCHECK_EQ(image_info.image_end_,
1820 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001821 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001822
Jeff Haodcdc85b2015-12-04 14:06:18 -08001823 // Calculate image offsets.
1824 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001825 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001826 image_info.image_begin_ = global_image_begin_ + image_offset;
1827 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001828 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001829 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001830 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001831 image_offset += image_info.image_size_;
1832 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001833
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001834 // Transform each object's bin slot into an offset which will be used to do the final copy.
Andreas Gampe1c158a02017-07-13 17:26:19 -07001835 {
1836 auto unbin_objects_into_offset = [&](mirror::Object* obj)
1837 REQUIRES_SHARED(Locks::mutator_lock_) {
1838 if (!IsInBootImage(obj)) {
1839 UnbinObjectsIntoOffset(obj);
1840 }
1841 };
1842 heap->VisitObjects(unbin_objects_into_offset);
1843 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001844
Jeff Haodcdc85b2015-12-04 14:06:18 -08001845 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001846 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001847 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1848 i++;
1849 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001850
Mathieu Chartiere401d142015-04-22 13:56:20 -07001851 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001852 for (auto& pair : native_object_relocations_) {
1853 NativeObjectRelocation& relocation = pair.second;
1854 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001855 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001856 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001857 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001858}
1859
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001860size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001861 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001862
1863 // Do not round up any sections here that are represented by the bins since it will break
1864 // offsets.
1865
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001866 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001867 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001868 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001869
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001870 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001871 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1872 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001873 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001874
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001875 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001876 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1877 *methods_section = ImageSection(
1878 bin_slot_offsets_[kBinArtMethodClean],
1879 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1880
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001881 // IMT section.
1882 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1883 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1884
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001885 // Conflict tables section.
1886 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1887 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1888 bin_slot_sizes_[kBinIMTConflictTable]);
1889
1890 // Runtime methods section.
1891 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1892 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1893 bin_slot_sizes_[kBinRuntimeMethod]);
1894
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001895 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001896 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1897 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1898 bin_slot_sizes_[kBinDexCacheArray]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001899 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001900 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001901 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001902 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001903 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1904 cur_pos = interned_strings_section->End();
1905 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1906 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1907 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001908 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001909 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001910 cur_pos = class_table_section->End();
1911 // Image end goes right before the start of the image bitmap.
1912 return cur_pos;
1913}
1914
Vladimir Marko944da602016-02-19 12:27:55 +00001915void ImageWriter::CreateHeader(size_t oat_index) {
1916 ImageInfo& image_info = GetImageInfo(oat_index);
1917 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1918 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1919 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001920
1921 // Create the image sections.
1922 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001923 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001924
Mathieu Chartiere401d142015-04-22 13:56:20 -07001925 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001926 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001927 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001928 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001929 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001930 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001931 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001932 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001933 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1934 ++idx;
1935 }
1936 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001937 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1938 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1939 << " Image offset=" << image_info.image_offset_ << std::dec;
1940 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1941 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1942 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1943 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001944 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001945 // Store boot image info for app image so that we can relocate.
1946 uint32_t boot_image_begin = 0;
1947 uint32_t boot_image_end = 0;
1948 uint32_t boot_oat_begin = 0;
1949 uint32_t boot_oat_end = 0;
1950 gc::Heap* const heap = Runtime::Current()->GetHeap();
1951 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001952
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001953 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1954 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001955 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1956 image_end,
1957 sections,
1958 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001959 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001960 PointerToLowMemUInt32(oat_file_begin),
1961 PointerToLowMemUInt32(image_info.oat_data_begin_),
1962 PointerToLowMemUInt32(oat_data_end),
1963 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001964 boot_image_begin,
1965 boot_image_end - boot_image_begin,
1966 boot_oat_begin,
1967 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001968 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001969 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001970 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001971 image_storage_mode_,
1972 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001973}
1974
1975ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001976 auto it = native_object_relocations_.find(method);
David Sehr709b0702016-10-13 09:12:37 -07001977 CHECK(it != native_object_relocations_.end()) << ArtMethod::PrettyMethod(method) << " @ "
1978 << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001979 size_t oat_index = GetOatIndex(method->GetDexCache());
1980 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001981 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1982 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001983}
1984
Vladimir Markoad06b982016-11-17 16:38:59 +00001985class ImageWriter::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001986 public:
1987 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1988 }
1989
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001990 void VisitRoots(mirror::Object*** roots ATTRIBUTE_UNUSED,
1991 size_t count ATTRIBUTE_UNUSED,
1992 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001993 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001994 LOG(FATAL) << "Unsupported";
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001995 }
1996
1997 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1998 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001999 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002000 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002001 image_writer_->CopyReference(roots[i], roots[i]->AsMirrorPtr());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002002 }
2003 }
2004
2005 private:
2006 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002007};
2008
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002009void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
2010 for (size_t i = 0; i < ImTable::kSize; ++i) {
2011 ArtMethod* method = orig->Get(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002012 void** address = reinterpret_cast<void**>(copy->AddressOfElement(i, target_ptr_size_));
2013 CopyAndFixupPointer(address, method);
2014 DCHECK_EQ(copy->Get(i, target_ptr_size_), NativeLocationInImage(method));
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002015 }
2016}
2017
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002018void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
2019 const size_t count = orig->NumEntries(target_ptr_size_);
2020 for (size_t i = 0; i < count; ++i) {
2021 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
2022 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002023 CopyAndFixupPointer(copy->AddressOfInterfaceMethod(i, target_ptr_size_), interface_method);
2024 CopyAndFixupPointer(copy->AddressOfImplementationMethod(i, target_ptr_size_),
2025 implementation_method);
2026 DCHECK_EQ(copy->GetInterfaceMethod(i, target_ptr_size_),
2027 NativeLocationInImage(interface_method));
2028 DCHECK_EQ(copy->GetImplementationMethod(i, target_ptr_size_),
2029 NativeLocationInImage(implementation_method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002030 }
2031}
2032
Vladimir Marko944da602016-02-19 12:27:55 +00002033void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002034 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002035 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002036 for (auto& pair : native_object_relocations_) {
2037 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002038 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00002039 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002040 continue;
2041 }
2042 auto* dest = image_info.image_->Begin() + relocation.offset;
2043 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002044 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002045 switch (relocation.type) {
2046 case kNativeObjectRelocationTypeArtField: {
2047 memcpy(dest, pair.first, sizeof(ArtField));
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002048 CopyReference(
2049 reinterpret_cast<ArtField*>(dest)->GetDeclaringClassAddressWithoutBarrier(),
2050 reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass().Ptr());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002051 break;
2052 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002053 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002054 case kNativeObjectRelocationTypeArtMethodClean:
2055 case kNativeObjectRelocationTypeArtMethodDirty: {
2056 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08002057 reinterpret_cast<ArtMethod*>(dest),
2058 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002059 break;
2060 }
2061 // For arrays, copy just the header since the elements will get copied by their corresponding
2062 // relocations.
2063 case kNativeObjectRelocationTypeArtFieldArray: {
2064 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
2065 break;
2066 }
2067 case kNativeObjectRelocationTypeArtMethodArrayClean:
2068 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00002069 size_t size = ArtMethod::Size(target_ptr_size_);
2070 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
2071 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
2072 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
2073 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002074 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00002075 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002076 case kNativeObjectRelocationTypeDexCacheArray:
2077 // Nothing to copy here, everything is done in FixupDexCache().
2078 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002079 case kNativeObjectRelocationTypeIMTable: {
2080 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
2081 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
2082 CopyAndFixupImTable(orig_imt, dest_imt);
2083 break;
2084 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002085 case kNativeObjectRelocationTypeIMTConflictTable: {
2086 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
2087 CopyAndFixupImtConflictTable(
2088 orig_table,
2089 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
2090 break;
2091 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002092 }
2093 }
2094 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002095 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002096 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002097 ArtMethod* method = image_methods_[i];
2098 CHECK(method != nullptr);
2099 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002100 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002101 }
2102 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002103 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002104 FixupRootVisitor root_visitor(this);
2105
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002106 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002107 if (image_info.intern_table_bytes_ > 0) {
2108 const ImageSection& intern_table_section = image_header->GetImageSection(
2109 ImageHeader::kSectionInternedStrings);
2110 InternTable* const intern_table = image_info.intern_table_.get();
2111 uint8_t* const intern_table_memory_ptr =
2112 image_info.image_->Begin() + intern_table_section.Offset();
2113 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
2114 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
2115 // Fixup the pointers in the newly written intern table to contain image addresses.
2116 InternTable temp_intern_table;
2117 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
2118 // the VisitRoots() will update the memory directly rather than the copies.
2119 // This also relies on visit roots not doing any verification which could fail after we update
2120 // the roots to be the image addresses.
2121 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
2122 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
2123 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
2124 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002125 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
2126 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002127 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002128 const ImageSection& class_table_section = image_header->GetImageSection(
2129 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002130 uint8_t* const class_table_memory_ptr =
2131 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002132 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002133
2134 ClassTable* table = image_info.class_table_.get();
2135 CHECK(table != nullptr);
2136 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
2137 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
2138 // Fixup the pointers in the newly written class table to contain image addresses. See
2139 // above comment for intern tables.
2140 ClassTable temp_class_table;
2141 temp_class_table.ReadFromMemory(class_table_memory_ptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002142 CHECK_EQ(temp_class_table.NumReferencedZygoteClasses(),
2143 table->NumReferencedNonZygoteClasses() + table->NumReferencedZygoteClasses());
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002144 UnbufferedRootVisitor visitor(&root_visitor, RootInfo(kRootUnknown));
2145 temp_class_table.VisitRoots(visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002146 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002147}
2148
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08002149void ImageWriter::CopyAndFixupObjects() {
Andreas Gampe1c158a02017-07-13 17:26:19 -07002150 auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2151 DCHECK(obj != nullptr);
2152 CopyAndFixupObject(obj);
2153 };
2154 Runtime::Current()->GetHeap()->VisitObjects(visitor);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002155 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002156 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08002157 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07002158 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
2159 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002160 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002161 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002162}
2163
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002164void ImageWriter::FixupPointerArray(mirror::Object* dst,
2165 mirror::PointerArray* arr,
2166 mirror::Class* klass,
2167 Bin array_type) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002168 CHECK(klass->IsArrayClass());
David Sehr709b0702016-10-13 09:12:37 -07002169 CHECK(arr->IsIntArray() || arr->IsLongArray()) << klass->PrettyClass() << " " << arr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002170 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07002171 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002172 dst->SetClass(GetImageAddress(arr->GetClass()));
2173 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002174 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002175 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002176 if (kIsDebugBuild && elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002177 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01002178 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002179 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002180 auto* method = reinterpret_cast<ArtMethod*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07002181 LOG(FATAL) << "No relocation entry for ArtMethod " << method->PrettyMethod() << " @ "
2182 << method << " idx=" << i << "/" << num_elements << " with declaring class "
2183 << Class::PrettyClass(method->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002184 } else {
2185 CHECK_EQ(array_type, kBinArtField);
2186 auto* field = reinterpret_cast<ArtField*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07002187 LOG(FATAL) << "No relocation entry for ArtField " << field->PrettyField() << " @ "
Mathieu Chartiere401d142015-04-22 13:56:20 -07002188 << field << " idx=" << i << "/" << num_elements << " with declaring class "
David Sehr709b0702016-10-13 09:12:37 -07002189 << Class::PrettyClass(field->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002190 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002191 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002192 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002193 }
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002194 CopyAndFixupPointer(dest_array->ElementAddress(i, target_ptr_size_), elem);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002195 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002196}
2197
2198void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002199 if (IsInBootImage(obj)) {
2200 return;
2201 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002202 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00002203 size_t oat_index = GetOatIndex(obj);
2204 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002205 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
2206 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002207 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002208
Jeff Haodcdc85b2015-12-04 14:06:18 -08002209 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002210
2211 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002212 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002213 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002214
Mathieu Chartierad2541a2013-10-25 10:05:23 -07002215 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
2216 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002217 const auto it = saved_hashcode_map_.find(obj);
2218 dst->SetLockWord(it != saved_hashcode_map_.end() ?
2219 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002220 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
2221 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
2222 // safe since we mark all of the objects that may reference non immune objects as gray.
2223 CHECK(dst->AtomicSetMarkBit(0, 1));
2224 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002225 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002226}
2227
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002228// Rewrite all the references in the copied object to point to their image address equivalent
Vladimir Markoad06b982016-11-17 16:38:59 +00002229class ImageWriter::FixupVisitor {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002230 public:
2231 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
2232 }
2233
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002234 // Ignore class roots since we don't have a way to map them to the destination. These are handled
2235 // with other logic.
2236 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
2237 const {}
2238 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
2239
2240
Mathieu Chartier31e88222016-10-14 18:43:19 -07002241 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002242 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07002243 ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002244 // Copy the reference and record the fixup if necessary.
2245 image_writer_->CopyReference(
2246 copy_->GetFieldObjectReferenceAddr<kVerifyNone>(offset),
2247 ref.Ptr());
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002248 }
2249
2250 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07002251 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2252 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002253 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002254 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002255 }
2256
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002257 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002258 ImageWriter* const image_writer_;
2259 mirror::Object* const copy_;
2260};
2261
Vladimir Markoad06b982016-11-17 16:38:59 +00002262class ImageWriter::FixupClassVisitor FINAL : public FixupVisitor {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002263 public:
2264 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
2265 }
2266
Mathieu Chartier31e88222016-10-14 18:43:19 -07002267 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07002268 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002269 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002270 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002271 }
2272
Mathieu Chartier31e88222016-10-14 18:43:19 -07002273 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2274 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002275 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002276 LOG(FATAL) << "Reference not expected here.";
2277 }
2278};
2279
Vladimir Marko05792b92015-08-03 11:56:49 +01002280uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
2281 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002282 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002283 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002284 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
2285 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002286 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01002287 return relocation.offset;
2288}
2289
2290template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002291std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002292 std::ostringstream oss;
2293 oss << ptr;
2294 return oss.str();
2295}
2296
2297template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002298std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07002299 return ArtMethod::PrettyMethod(method);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002300}
2301
2302template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002303T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002304 if (obj == nullptr || IsInBootImage(obj)) {
2305 return obj;
2306 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002307 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002308 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
2309 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002310 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00002311 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002312 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002313 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002314}
2315
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002316template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08002317T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
2318 if (obj == nullptr || IsInBootImage(obj)) {
2319 return obj;
2320 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002321 size_t oat_index = GetOatIndexForDexCache(dex_cache);
2322 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002323 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
2324 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002325}
2326
Vladimir Markoad06b982016-11-17 16:38:59 +00002327class ImageWriter::NativeLocationVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002328 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002329 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002330
2331 template <typename T>
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002332 T* operator()(T* ptr, void** dest_addr = nullptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
2333 if (dest_addr != nullptr) {
2334 image_writer_->CopyAndFixupPointer(dest_addr, ptr);
2335 }
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002336 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002337 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002338
2339 private:
2340 ImageWriter* const image_writer_;
2341};
2342
2343void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002344 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002345 FixupClassVisitor visitor(this, copy);
Mathieu Chartier31e88222016-10-14 18:43:19 -07002346 ObjPtr<mirror::Object>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002347
2348 // Remove the clinitThreadId. This is required for image determinism.
2349 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002350}
2351
Ian Rogersef7d42f2014-01-06 12:55:46 -08002352void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002353 DCHECK(orig != nullptr);
2354 DCHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002355 if (kUseBakerReadBarrier) {
2356 orig->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002357 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002358 auto* klass = orig->GetClass();
2359 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002360 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07002361 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
2362 if (it != pointer_arrays_.end()) {
2363 // Should only need to fixup every pointer array exactly once.
2364 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
2365 pointer_arrays_.erase(it);
2366 return;
2367 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002368 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002369 if (orig->IsClass()) {
2370 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002371 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002372 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
2373 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01002374 auto* dest = down_cast<mirror::Executable*>(copy);
2375 auto* src = down_cast<mirror::Executable*>(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002376 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05002377 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01002378 } else if (!klass->IsArrayClass()) {
2379 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2380 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
2381 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002382 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002383 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002384 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2385 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002386 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002387 // Also set allocator to null to be safe. The allocator is created when we create the class
2388 // table. We also never expect to unload things in the image since they are held live as
2389 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002390 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002391 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002392 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002393 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002394 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002395 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002396}
2397
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002398class ImageWriter::ImageAddressVisitorForDexCacheArray {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002399 public:
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002400 explicit ImageAddressVisitorForDexCacheArray(ImageWriter* image_writer)
2401 : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002402
2403 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002404 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002405 return image_writer_->GetImageAddress(ptr);
2406 }
2407
2408 private:
2409 ImageWriter* const image_writer_;
2410};
2411
Vladimir Marko05792b92015-08-03 11:56:49 +01002412void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2413 mirror::DexCache* copy_dex_cache) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002414 ImageAddressVisitorForDexCacheArray fixup_visitor(this);
Vladimir Marko05792b92015-08-03 11:56:49 +01002415 // Though the DexCache array fields are usually treated as native pointers, we set the full
2416 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2417 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2418 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002419 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002420 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002421 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002422 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002423 PointerSize::k64);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002424 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache), fixup_visitor);
Vladimir Marko05792b92015-08-03 11:56:49 +01002425 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002426 mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
Vladimir Marko05792b92015-08-03 11:56:49 +01002427 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002428 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002429 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002430 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002431 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002432 fixup_visitor);
Vladimir Marko05792b92015-08-03 11:56:49 +01002433 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002434 mirror::MethodDexCacheType* orig_methods = orig_dex_cache->GetResolvedMethods();
Vladimir Marko05792b92015-08-03 11:56:49 +01002435 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002436 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002437 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002438 PointerSize::k64);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002439 mirror::MethodDexCacheType* copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002440 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002441 mirror::MethodDexCachePair orig_pair =
2442 mirror::DexCache::GetNativePairPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002443 // NativeLocationInImage also handles runtime methods since these have relocation info.
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002444 mirror::MethodDexCachePair copy_pair(NativeLocationInImage(orig_pair.object),
2445 orig_pair.index);
2446 mirror::DexCache::SetNativePairPtrSize(copy_methods, i, copy_pair, target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002447 }
2448 }
Vladimir Markof44d36c2017-03-14 14:18:46 +00002449 mirror::FieldDexCacheType* orig_fields = orig_dex_cache->GetResolvedFields();
Vladimir Marko05792b92015-08-03 11:56:49 +01002450 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002451 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002452 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002453 PointerSize::k64);
Vladimir Markof44d36c2017-03-14 14:18:46 +00002454 mirror::FieldDexCacheType* copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002455 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00002456 mirror::FieldDexCachePair orig =
2457 mirror::DexCache::GetNativePairPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002458 mirror::FieldDexCachePair copy = orig;
2459 copy.object = NativeLocationInImage(orig.object);
Vladimir Markof44d36c2017-03-14 14:18:46 +00002460 mirror::DexCache::SetNativePairPtrSize(copy_fields, i, copy, target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002461 }
2462 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01002463 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
2464 if (orig_method_types != nullptr) {
2465 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodTypesOffset(),
2466 NativeLocationInImage(orig_method_types),
2467 PointerSize::k64);
2468 orig_dex_cache->FixupResolvedMethodTypes(NativeCopyLocation(orig_method_types, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002469 fixup_visitor);
Narayan Kamath7fe56582016-10-14 18:49:12 +01002470 }
Orion Hodsonc069a302017-01-18 09:23:12 +00002471 GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
2472 if (orig_call_sites != nullptr) {
2473 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedCallSitesOffset(),
2474 NativeLocationInImage(orig_call_sites),
2475 PointerSize::k64);
2476 orig_dex_cache->FixupResolvedCallSites(NativeCopyLocation(orig_call_sites, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002477 fixup_visitor);
Orion Hodsonc069a302017-01-18 09:23:12 +00002478 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002479
2480 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2481 // compiler pointers in here will make the output non-deterministic.
2482 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002483}
2484
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002485const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2486 DCHECK_LT(type, kOatAddressCount);
2487 // If we are compiling an app image, we need to use the stubs of the boot image.
2488 if (compile_app_image_) {
2489 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002490 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002491 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2492 DCHECK(!image_spaces.empty());
2493 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002494 CHECK(oat_file != nullptr);
2495 const OatHeader& header = oat_file->GetOatHeader();
2496 switch (type) {
2497 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2498 case kOatAddressQuickGenericJNITrampoline:
2499 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2500 case kOatAddressInterpreterToInterpreterBridge:
2501 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2502 case kOatAddressInterpreterToCompiledCodeBridge:
2503 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2504 case kOatAddressJNIDlsymLookup:
2505 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2506 case kOatAddressQuickIMTConflictTrampoline:
2507 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2508 case kOatAddressQuickResolutionTrampoline:
2509 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2510 case kOatAddressQuickToInterpreterBridge:
2511 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2512 default:
2513 UNREACHABLE();
2514 }
2515 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002516 const ImageInfo& primary_image_info = GetImageInfo(0);
2517 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002518}
2519
Jeff Haodcdc85b2015-12-04 14:06:18 -08002520const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2521 const ImageInfo& image_info,
2522 bool* quick_is_interpreted) {
David Sehr709b0702016-10-13 09:12:37 -07002523 DCHECK(!method->IsResolutionMethod()) << method->PrettyMethod();
2524 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << method->PrettyMethod();
2525 DCHECK(!method->IsImtUnimplementedMethod()) << method->PrettyMethod();
2526 DCHECK(method->IsInvokable()) << method->PrettyMethod();
2527 DCHECK(!IsInBootImage(method)) << method->PrettyMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002528
2529 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2530 // trampoline.
2531
2532 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002533 const void* quick_oat_entry_point =
2534 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2535 const uint8_t* quick_code;
2536
2537 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2538 DCHECK(method->IsCopied());
2539 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2540 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2541 } else {
2542 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2543 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2544 }
2545
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002546 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002547 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2548 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002549 // We have code for a non-static or initialized method, just use the code.
2550 } else if (quick_code == nullptr && method->IsNative() &&
2551 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2552 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002553 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002554 } else if (quick_code == nullptr && !method->IsNative()) {
2555 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002556 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002557 *quick_is_interpreted = true;
2558 } else {
2559 CHECK(!method->GetDeclaringClass()->IsInitialized());
2560 // We have code for a static method, but need to go through the resolution stub for class
2561 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002562 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2563 }
2564 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002565 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002566 }
2567 return quick_code;
2568}
2569
Jeff Haodcdc85b2015-12-04 14:06:18 -08002570void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2571 ArtMethod* copy,
2572 const ImageInfo& image_info) {
Mingyao Yange8fcd012017-01-20 10:43:30 -08002573 if (orig->IsAbstract()) {
2574 // Ignore the single-implementation info for abstract method.
2575 // Do this on orig instead of copy, otherwise there is a crash due to methods
2576 // are copied before classes.
2577 // TODO: handle fixup of single-implementation method for abstract method.
2578 orig->SetHasSingleImplementation(false);
2579 orig->SetSingleImplementation(
2580 nullptr, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
2581 }
2582
Vladimir Marko14632852015-08-17 12:07:23 +01002583 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002584
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002585 CopyReference(copy->GetDeclaringClassAddressWithoutBarrier(), orig->GetDeclaringClassUnchecked());
2586
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002587 mirror::MethodDexCacheType* orig_resolved_methods =
2588 orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002589 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002590
Ian Rogers848871b2013-08-05 10:56:33 -07002591 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2592 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002593
Ian Rogers848871b2013-08-05 10:56:33 -07002594 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002595 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002596 if (orig->IsRuntimeMethod()) {
2597 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2598 if (orig_table != nullptr) {
2599 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2600 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2601 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2602 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2603 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2604 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2605 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2606 } else {
2607 bool found_one = false;
Andreas Gampe8228cdf2017-05-30 15:03:54 -07002608 for (size_t i = 0; i < static_cast<size_t>(CalleeSaveType::kLastCalleeSaveType); ++i) {
2609 auto idx = static_cast<CalleeSaveType>(i);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002610 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2611 found_one = true;
2612 break;
2613 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002614 }
David Sehr709b0702016-10-13 09:12:37 -07002615 CHECK(found_one) << "Expected to find callee save method but got " << orig->PrettyMethod();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002616 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002617 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002618 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002619 // We assume all methods have code. If they don't currently then we set them to the use the
2620 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2621 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002622 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002623 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002624 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002625 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002626 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002627 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002628 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002629
Sebastien Hertze1d07812014-05-21 15:44:09 +02002630 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002631 if (orig->IsNative()) {
2632 // The native method's pointer is set to a stub to lookup via dlsym.
2633 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002634 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002635 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002636 }
2637 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002638 }
2639}
2640
Jeff Haodcdc85b2015-12-04 14:06:18 -08002641size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002642 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002643 return std::accumulate(&image_info.bin_slot_sizes_[0],
2644 &image_info.bin_slot_sizes_[up_to],
2645 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002646}
2647
2648ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2649 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002650 static_assert(kBinBits == 3, "wrong number of bin bits");
2651 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002652 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2653
2654 DCHECK_LT(GetBin(), kBinSize);
2655 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2656}
2657
2658ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2659 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2660 DCHECK_EQ(index, GetIndex());
2661}
2662
2663ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2664 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2665}
2666
2667uint32_t ImageWriter::BinSlot::GetIndex() const {
2668 return lockword_ & ~kBinMask;
2669}
2670
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002671ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2672 switch (type) {
2673 case kNativeObjectRelocationTypeArtField:
2674 case kNativeObjectRelocationTypeArtFieldArray:
2675 return kBinArtField;
2676 case kNativeObjectRelocationTypeArtMethodClean:
2677 case kNativeObjectRelocationTypeArtMethodArrayClean:
2678 return kBinArtMethodClean;
2679 case kNativeObjectRelocationTypeArtMethodDirty:
2680 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2681 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002682 case kNativeObjectRelocationTypeDexCacheArray:
2683 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002684 case kNativeObjectRelocationTypeRuntimeMethod:
2685 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002686 case kNativeObjectRelocationTypeIMTable:
2687 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002688 case kNativeObjectRelocationTypeIMTConflictTable:
2689 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002690 }
2691 UNREACHABLE();
2692}
2693
Vladimir Marko944da602016-02-19 12:27:55 +00002694size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002695 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002696 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002697 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002698 auto it = oat_index_map_.find(obj);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002699 DCHECK(it != oat_index_map_.end()) << obj;
Mathieu Chartier496577f2016-09-20 15:33:31 -07002700 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002701}
2702
Vladimir Marko944da602016-02-19 12:27:55 +00002703size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002704 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002705 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002706 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002707 auto it = dex_file_oat_index_map_.find(dex_file);
2708 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2709 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002710}
2711
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002712size_t ImageWriter::GetOatIndexForDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
2713 return (dex_cache == nullptr)
2714 ? GetDefaultOatIndex()
2715 : GetOatIndexForDexFile(dex_cache->GetDexFile());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002716}
2717
Vladimir Marko944da602016-02-19 12:27:55 +00002718void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2719 size_t oat_loaded_size,
2720 size_t oat_data_offset,
2721 size_t oat_data_size) {
2722 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2723 for (const ImageInfo& info : image_infos_) {
2724 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2725 }
2726 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002727
Vladimir Marko944da602016-02-19 12:27:55 +00002728 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2729 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2730 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2731 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2732 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002733
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002734 if (compile_app_image_) {
2735 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2736 return;
2737 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002738
2739 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002740 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002741 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002742 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002743 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2744 }
2745}
2746
Vladimir Marko944da602016-02-19 12:27:55 +00002747void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2748 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2749 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2750
2751 if (oat_index == GetDefaultOatIndex()) {
2752 // Primary oat file, read the trampolines.
2753 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2754 oat_header.GetInterpreterToInterpreterBridgeOffset();
2755 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2756 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2757 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2758 oat_header.GetJniDlsymLookupOffset();
2759 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2760 oat_header.GetQuickGenericJniTrampolineOffset();
2761 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2762 oat_header.GetQuickImtConflictTrampolineOffset();
2763 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2764 oat_header.GetQuickResolutionTrampolineOffset();
2765 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2766 oat_header.GetQuickToInterpreterBridgeOffset();
2767 }
2768}
2769
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002770ImageWriter::ImageWriter(
2771 const CompilerDriver& compiler_driver,
2772 uintptr_t image_begin,
2773 bool compile_pic,
2774 bool compile_app_image,
2775 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002776 const std::vector<const char*>& oat_filenames,
2777 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002778 : compiler_driver_(compiler_driver),
2779 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2780 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002781 compile_pic_(compile_pic),
2782 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002783 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002784 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002785 dirty_methods_(0u),
2786 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002787 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002788 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002789 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002790 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002791 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002792 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2793 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002794}
2795
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002796ImageWriter::ImageInfo::ImageInfo()
2797 : intern_table_(new InternTable),
2798 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002799
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002800void ImageWriter::CopyReference(mirror::HeapReference<mirror::Object>* dest,
2801 ObjPtr<mirror::Object> src) {
2802 dest->Assign(GetImageAddress(src.Ptr()));
2803}
2804
2805void ImageWriter::CopyReference(mirror::CompressedReference<mirror::Object>* dest,
2806 ObjPtr<mirror::Object> src) {
2807 dest->Assign(GetImageAddress(src.Ptr()));
2808}
2809
2810void ImageWriter::CopyAndFixupPointer(void** target, void* value) {
2811 void* new_value = value;
2812 if (value != nullptr && !IsInBootImage(value)) {
2813 auto it = native_object_relocations_.find(value);
2814 CHECK(it != native_object_relocations_.end()) << value;
2815 const NativeObjectRelocation& relocation = it->second;
2816 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2817 new_value = reinterpret_cast<void*>(image_info.image_begin_ + relocation.offset);
2818 }
2819 if (target_ptr_size_ == PointerSize::k32) {
2820 *reinterpret_cast<uint32_t*>(target) = PointerToLowMemUInt32(new_value);
2821 } else {
2822 *reinterpret_cast<uint64_t*>(target) = reinterpret_cast<uintptr_t>(new_value);
2823 }
2824}
2825
2826
Brian Carlstrom7940e442013-07-12 13:46:57 -07002827} // namespace art