blob: 115e722a755cd657470156239efe7a37e8032f33 [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
Jeff Haoc23b0c02017-07-27 18:19:38 -0700582 // Move known dirty objects into their own sections. This includes:
583 // - classes with dirty static fields.
584 if (dirty_image_objects_ != nullptr &&
585 dirty_image_objects_->find(klass->PrettyDescriptor()) != dirty_image_objects_->end()) {
586 bin = kBinKnownDirty;
587 } else if (klass->GetStatus() == Class::kStatusInitialized) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800588 bin = kBinClassInitialized;
589
590 // If the class's static fields are all final, put it into a separate bin
591 // since it's very likely it will stay clean.
592 uint32_t num_static_fields = klass->NumStaticFields();
593 if (num_static_fields == 0) {
594 bin = kBinClassInitializedFinalStatics;
595 } else {
596 // Maybe all the statics are final?
597 bool all_final = true;
598 for (uint32_t i = 0; i < num_static_fields; ++i) {
599 ArtField* field = klass->GetStaticField(i);
600 if (!field->IsFinal()) {
601 all_final = false;
602 break;
603 }
604 }
605
606 if (all_final) {
607 bin = kBinClassInitializedFinalStatics;
608 }
609 }
610 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800611 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
612 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700613 } else if (object->GetClass<kVerifyNone>() ==
614 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
615 // Instance of java lang object, probably a lock object. This means it will be dirty when we
616 // synchronize on it.
617 bin = kBinMiscDirty;
618 } else if (object->IsDexCache()) {
619 // Dex file field becomes dirty when the image is loaded.
620 bin = kBinMiscDirty;
621 }
622 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800623 }
624
Mathieu Chartier496577f2016-09-20 15:33:31 -0700625 // Assign the oat index too.
626 DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
627 oat_index_map_.emplace(object, oat_index);
628
Vladimir Marko944da602016-02-19 12:27:55 +0000629 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800630
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800631 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800632 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
633 // Move the current bin size up to accommodate the object we just assigned a bin slot.
634 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800635
636 BinSlot new_bin_slot(bin, current_offset);
637 SetImageBinSlot(object, new_bin_slot);
638
Jeff Haodcdc85b2015-12-04 14:06:18 -0800639 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800640
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800641 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800642 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800643}
644
Mathieu Chartiere401d142015-04-22 13:56:20 -0700645bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
646 if (m->IsNative()) {
647 return true;
648 }
649 mirror::Class* declaring_class = m->GetDeclaringClass();
650 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
651 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
652}
653
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800654bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
655 DCHECK(object != nullptr);
656
657 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
658 // If it's in some other state, then we haven't yet assigned an image bin slot.
659 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
660 return false;
661 } else if (kIsDebugBuild) {
662 LockWord lock_word = object->GetLockWord(false);
663 size_t offset = lock_word.ForwardingAddress();
664 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000665 size_t oat_index = GetOatIndex(object);
666 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800667 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800668 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800669 }
670 return true;
671}
672
673ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
674 DCHECK(object != nullptr);
675 DCHECK(IsImageBinSlotAssigned(object));
676
677 LockWord lock_word = object->GetLockWord(false);
678 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
679 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
680
681 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000682 size_t oat_index = GetOatIndex(object);
683 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800684 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800685
686 return bin_slot;
687}
688
Brian Carlstrom7940e442013-07-12 13:46:57 -0700689bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000690 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800691 ImageSection unused_sections[ImageHeader::kSectionCount];
692 const size_t length = RoundUp(
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700693 image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800694
Jeff Haodcdc85b2015-12-04 14:06:18 -0800695 std::string error_msg;
696 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
697 nullptr,
698 length,
699 PROT_READ | PROT_WRITE,
700 false,
701 false,
702 &error_msg));
703 if (UNLIKELY(image_info.image_.get() == nullptr)) {
704 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
705 return false;
706 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700707
Jeff Haodcdc85b2015-12-04 14:06:18 -0800708 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
709 CHECK_LE(image_info.image_end_, length);
710 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
711 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
712 if (image_info.image_bitmap_.get() == nullptr) {
713 LOG(ERROR) << "Failed to allocate memory for image bitmap";
714 return false;
715 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700716 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700717 return true;
718}
719
Vladimir Markoad06b982016-11-17 16:38:59 +0000720class ImageWriter::ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700721 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700722 bool operator()(ObjPtr<Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700723 StackHandleScope<1> hs(Thread::Current());
724 mirror::Class::ComputeName(hs.NewHandle(c));
725 return true;
726 }
727};
728
Brian Carlstrom7940e442013-07-12 13:46:57 -0700729void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700730 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700731 ComputeLazyFieldsForClassesVisitor visitor;
732 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700733}
734
Vladimir Markof25cc732017-03-16 16:18:15 +0000735static bool IsBootClassLoaderClass(ObjPtr<mirror::Class> klass)
736 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800737 return klass->GetClassLoader() == nullptr;
738}
739
740bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
741 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
742}
743
Chang Xingb2e8adc2017-07-07 17:35:37 -0700744// This visitor follows the references of an instance, recursively then prune this class
745// if a type of any field is pruned.
746class ImageWriter::PruneObjectReferenceVisitor {
747 public:
748 PruneObjectReferenceVisitor(ImageWriter* image_writer,
749 bool* early_exit,
750 std::unordered_set<mirror::Object*>* visited,
751 bool* result)
752 : image_writer_(image_writer), early_exit_(early_exit), visited_(visited), result_(result) {}
753
754 ALWAYS_INLINE void VisitRootIfNonNull(
755 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const
756 REQUIRES_SHARED(Locks::mutator_lock_) { }
757
758 ALWAYS_INLINE void VisitRoot(
759 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const
760 REQUIRES_SHARED(Locks::mutator_lock_) { }
761
762 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
763 MemberOffset offset,
764 bool is_static ATTRIBUTE_UNUSED) const
765 REQUIRES_SHARED(Locks::mutator_lock_) {
766 mirror::Object* ref =
767 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
768 if (ref == nullptr || visited_->find(ref) != visited_->end()) {
769 return;
770 }
771
772 ObjPtr<mirror::Class> klass = ref->IsClass() ? ref->AsClass() : ref->GetClass();
773 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
774 // Prune all classes using reflection because the content they held will not be fixup.
775 *result_ = true;
776 }
777
Chang Xingb2e8adc2017-07-07 17:35:37 -0700778 if (ref->IsClass()) {
779 *result_ = *result_ ||
780 image_writer_->PruneAppImageClassInternal(ref->AsClass(), early_exit_, visited_);
781 } else {
Chang Xingec373252017-07-13 17:51:52 -0700782 // Record the object visited in case of circular reference.
783 visited_->emplace(ref);
Chang Xingb2e8adc2017-07-07 17:35:37 -0700784 *result_ = *result_ ||
785 image_writer_->PruneAppImageClassInternal(klass, early_exit_, visited_);
786 ref->VisitReferences(*this, *this);
Chang Xingec373252017-07-13 17:51:52 -0700787 // Clean up before exit for next call of this function.
788 visited_->erase(ref);
Chang Xingb2e8adc2017-07-07 17:35:37 -0700789 }
Chang Xingb2e8adc2017-07-07 17:35:37 -0700790 }
791
792 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
793 ObjPtr<mirror::Reference> ref) const
794 REQUIRES_SHARED(Locks::mutator_lock_) {
795 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
796 }
797
798 ALWAYS_INLINE bool GetResult() const {
799 return result_;
800 }
801
802 private:
803 ImageWriter* image_writer_;
804 bool* early_exit_;
805 std::unordered_set<mirror::Object*>* visited_;
806 bool* const result_;
807};
808
809
Vladimir Markof25cc732017-03-16 16:18:15 +0000810bool ImageWriter::PruneAppImageClass(ObjPtr<mirror::Class> klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800811 bool early_exit = false;
Chang Xingb2e8adc2017-07-07 17:35:37 -0700812 std::unordered_set<mirror::Object*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800813 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800814}
815
Mathieu Chartier901e0702016-02-19 13:42:48 -0800816bool ImageWriter::PruneAppImageClassInternal(
Vladimir Markof25cc732017-03-16 16:18:15 +0000817 ObjPtr<mirror::Class> klass,
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800818 bool* early_exit,
Chang Xingb2e8adc2017-07-07 17:35:37 -0700819 std::unordered_set<mirror::Object*>* visited) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800820 DCHECK(early_exit != nullptr);
821 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800822 DCHECK(compile_app_image_);
Vladimir Markof25cc732017-03-16 16:18:15 +0000823 if (klass == nullptr || IsInBootImage(klass.Ptr())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700824 return false;
825 }
Vladimir Markof25cc732017-03-16 16:18:15 +0000826 auto found = prune_class_memo_.find(klass.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800827 if (found != prune_class_memo_.end()) {
828 // Already computed, return the found value.
829 return found->second;
830 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800831 // Circular dependencies, return false but do not store the result in the memoization table.
Vladimir Markof25cc732017-03-16 16:18:15 +0000832 if (visited->find(klass.Ptr()) != visited->end()) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800833 *early_exit = true;
834 return false;
835 }
Vladimir Markof25cc732017-03-16 16:18:15 +0000836 visited->emplace(klass.Ptr());
Mathieu Chartier901e0702016-02-19 13:42:48 -0800837 bool result = IsBootClassLoaderClass(klass);
838 std::string temp;
839 // Prune if not an image class, this handles any broken sets of image classes such as having a
840 // class in the set but not it's superclass.
841 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800842 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800843 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
844 // app image.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000845 if (klass->IsErroneous()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800846 result = true;
847 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700848 ObjPtr<mirror::ClassExt> ext(klass->GetExtData());
849 CHECK(ext.IsNull() || ext->GetVerifyError() == nullptr) << klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800850 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800851 if (!result) {
852 // Check interfaces since these wont be visited through VisitReferences.)
853 mirror::IfTable* if_table = klass->GetIfTable();
854 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800855 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
856 &my_early_exit,
857 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800858 }
859 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800860 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800861 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
862 &my_early_exit,
863 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800864 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800865 // Check static fields and their classes.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000866 if (klass->IsResolved() && klass->NumReferenceStaticFields() != 0) {
867 size_t num_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800868 // Presumably GC can happen when we are cross compiling, it should not cause performance
869 // problems to do pointer size logic.
870 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
871 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
872 for (size_t i = 0u; i < num_static_fields; ++i) {
873 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
874 if (ref != nullptr) {
875 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800876 result = result || PruneAppImageClassInternal(ref->AsClass(),
877 &my_early_exit,
878 visited);
879 } else {
Chang Xingb2e8adc2017-07-07 17:35:37 -0700880 mirror::Class* type = ref->GetClass();
881 result = result || PruneAppImageClassInternal(type,
Mathieu Chartier901e0702016-02-19 13:42:48 -0800882 &my_early_exit,
883 visited);
Chang Xingb2e8adc2017-07-07 17:35:37 -0700884 if (!result) {
885 // For non-class case, also go through all the types mentioned by it's fields'
886 // references recursively to decide whether to keep this class.
887 bool tmp = false;
888 PruneObjectReferenceVisitor visitor(this, &my_early_exit, visited, &tmp);
889 ref->VisitReferences(visitor, visitor);
890 result = result || tmp;
891 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800892 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800893 }
894 field_offset = MemberOffset(field_offset.Uint32Value() +
895 sizeof(mirror::HeapReference<mirror::Object>));
896 }
897 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800898 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
899 &my_early_exit,
900 visited);
Mathieu Chartierc27bc402016-08-05 16:09:09 -0700901 // 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 -0700902 // are from uses-library if there is no profile. b/30688277
Mathieu Chartierc27bc402016-08-05 16:09:09 -0700903 mirror::DexCache* dex_cache = klass->GetDexCache();
904 if (dex_cache != nullptr) {
905 result = result ||
906 dex_file_oat_index_map_.find(dex_cache->GetDexFile()) == dex_file_oat_index_map_.end();
907 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800908 // Erase the element we stored earlier since we are exiting the function.
Vladimir Markof25cc732017-03-16 16:18:15 +0000909 auto it = visited->find(klass.Ptr());
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800910 DCHECK(it != visited->end());
911 visited->erase(it);
912 // Only store result if it is true or none of the calls early exited due to circular
913 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
914 // a child call and we can remember the result.
915 if (result == true || !my_early_exit || visited->empty()) {
Vladimir Markof25cc732017-03-16 16:18:15 +0000916 prune_class_memo_[klass.Ptr()] = result;
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800917 }
918 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800919 return result;
920}
921
Vladimir Markof25cc732017-03-16 16:18:15 +0000922bool ImageWriter::KeepClass(ObjPtr<mirror::Class> klass) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800923 if (klass == nullptr) {
924 return false;
925 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800926 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
927 // Already in boot image, return true.
928 return true;
929 }
930 std::string temp;
931 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
932 return false;
933 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800934 if (compile_app_image_) {
935 // For app images, we need to prune boot loader classes that are not in the boot image since
936 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800937 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800938 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800939 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800940 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700941}
942
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000943class ImageWriter::PruneClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700944 public:
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000945 PruneClassesVisitor(ImageWriter* image_writer, ObjPtr<mirror::ClassLoader> class_loader)
946 : image_writer_(image_writer),
947 class_loader_(class_loader),
948 classes_to_prune_(),
949 defined_class_count_(0u) { }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700950
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000951 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700952 if (!image_writer_->KeepClass(klass.Ptr())) {
953 classes_to_prune_.insert(klass.Ptr());
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000954 if (klass->GetClassLoader() == class_loader_) {
955 ++defined_class_count_;
956 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700957 }
958 return true;
959 }
960
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000961 size_t Prune() REQUIRES_SHARED(Locks::mutator_lock_) {
962 ClassTable* class_table =
963 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader_);
964 for (mirror::Class* klass : classes_to_prune_) {
965 std::string storage;
966 const char* descriptor = klass->GetDescriptor(&storage);
967 bool result = class_table->Remove(descriptor);
968 DCHECK(result);
969 DCHECK(!class_table->Remove(descriptor)) << descriptor;
970 }
971 return defined_class_count_;
972 }
973
974 private:
Vladimir Markocb5ab352016-11-30 15:31:13 +0000975 ImageWriter* const image_writer_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000976 const ObjPtr<mirror::ClassLoader> class_loader_;
977 std::unordered_set<mirror::Class*> classes_to_prune_;
978 size_t defined_class_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700979};
980
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000981class ImageWriter::PruneClassLoaderClassesVisitor : public ClassLoaderVisitor {
982 public:
983 explicit PruneClassLoaderClassesVisitor(ImageWriter* image_writer)
984 : image_writer_(image_writer), removed_class_count_(0) {}
985
986 virtual void Visit(ObjPtr<mirror::ClassLoader> class_loader) OVERRIDE
987 REQUIRES_SHARED(Locks::mutator_lock_) {
988 PruneClassesVisitor classes_visitor(image_writer_, class_loader);
989 ClassTable* class_table =
990 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader);
991 class_table->Visit(classes_visitor);
992 removed_class_count_ += classes_visitor.Prune();
Vladimir Markof25cc732017-03-16 16:18:15 +0000993
994 // Record app image class loader. The fake boot class loader should not get registered
995 // and we should end up with only one class loader for an app and none for boot image.
996 if (class_loader != nullptr && class_table != nullptr) {
997 DCHECK(class_loader_ == nullptr);
998 class_loader_ = class_loader;
999 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001000 }
1001
1002 size_t GetRemovedClassCount() const {
1003 return removed_class_count_;
1004 }
1005
Vladimir Markof25cc732017-03-16 16:18:15 +00001006 ObjPtr<mirror::ClassLoader> GetClassLoader() const REQUIRES_SHARED(Locks::mutator_lock_) {
1007 return class_loader_;
1008 }
1009
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001010 private:
1011 ImageWriter* const image_writer_;
1012 size_t removed_class_count_;
Vladimir Markof25cc732017-03-16 16:18:15 +00001013 ObjPtr<mirror::ClassLoader> class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001014};
1015
1016void ImageWriter::VisitClassLoaders(ClassLoaderVisitor* visitor) {
1017 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1018 visitor->Visit(nullptr); // Visit boot class loader.
1019 Runtime::Current()->GetClassLinker()->VisitClassLoaders(visitor);
1020}
1021
Vladimir Markof25cc732017-03-16 16:18:15 +00001022void ImageWriter::PruneAndPreloadDexCache(ObjPtr<mirror::DexCache> dex_cache,
1023 ObjPtr<mirror::ClassLoader> class_loader) {
1024 // To ensure deterministic contents of the hash-based arrays, each slot shall contain
1025 // the candidate with the lowest index. As we're processing entries in increasing index
1026 // order, this means trying to look up the entry for the current index if the slot is
1027 // empty or if it contains a higher index.
1028
1029 Runtime* runtime = Runtime::Current();
1030 ClassLinker* class_linker = runtime->GetClassLinker();
Vladimir Markof25cc732017-03-16 16:18:15 +00001031 const DexFile& dex_file = *dex_cache->GetDexFile();
1032 // Prune methods.
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001033 mirror::MethodDexCacheType* resolved_methods = dex_cache->GetResolvedMethods();
1034 dex::TypeIndex last_class_idx; // Initialized to invalid index.
1035 ObjPtr<mirror::Class> last_class = nullptr;
1036 for (size_t i = 0, num = dex_cache->GetDexFile()->NumMethodIds(); i != num; ++i) {
1037 uint32_t slot_idx = dex_cache->MethodSlotIndex(i);
1038 auto pair =
1039 mirror::DexCache::GetNativePairPtrSize(resolved_methods, slot_idx, target_ptr_size_);
1040 uint32_t stored_index = pair.index;
1041 ArtMethod* method = pair.object;
1042 if (method != nullptr && i > stored_index) {
1043 continue; // Already checked.
1044 }
Vladimir Marko3b155452017-07-05 11:41:33 +01001045 // Check if the referenced class is in the image. Note that we want to check the referenced
1046 // class rather than the declaring class to preserve the semantics, i.e. using a MethodId
1047 // results in resolving the referenced class and that can for example throw OOME.
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001048 const DexFile::MethodId& method_id = dex_file.GetMethodId(i);
1049 if (method_id.class_idx_ != last_class_idx) {
1050 last_class_idx = method_id.class_idx_;
1051 last_class = class_linker->LookupResolvedType(
1052 dex_file, last_class_idx, dex_cache, class_loader);
1053 if (last_class != nullptr && !KeepClass(last_class)) {
1054 last_class = nullptr;
1055 }
1056 }
1057 if (method == nullptr || i < stored_index) {
1058 if (last_class != nullptr) {
1059 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
1060 Signature signature = dex_file.GetMethodSignature(method_id);
1061 if (last_class->IsInterface()) {
1062 method = last_class->FindInterfaceMethod(name, signature, target_ptr_size_);
1063 } else {
1064 method = last_class->FindClassMethod(name, signature, target_ptr_size_);
1065 }
1066 if (method != nullptr) {
1067 // If the referenced class is in the image, the defining class must also be there.
1068 DCHECK(KeepClass(method->GetDeclaringClass()));
1069 dex_cache->SetResolvedMethod(i, method, target_ptr_size_);
1070 }
1071 }
1072 } else {
1073 DCHECK_EQ(i, stored_index);
1074 if (last_class == nullptr) {
1075 dex_cache->ClearResolvedMethod(stored_index, target_ptr_size_);
1076 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001077 }
1078 }
1079 // Prune fields and make the contents of the field array deterministic.
1080 mirror::FieldDexCacheType* resolved_fields = dex_cache->GetResolvedFields();
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001081 last_class_idx = dex::TypeIndex(); // Initialized to invalid index.
1082 last_class = nullptr;
Vladimir Markof25cc732017-03-16 16:18:15 +00001083 for (size_t i = 0, end = dex_file.NumFieldIds(); i < end; ++i) {
1084 uint32_t slot_idx = dex_cache->FieldSlotIndex(i);
1085 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_fields, slot_idx, target_ptr_size_);
1086 uint32_t stored_index = pair.index;
1087 ArtField* field = pair.object;
1088 if (field != nullptr && i > stored_index) {
1089 continue; // Already checked.
1090 }
1091 // Check if the referenced class is in the image. Note that we want to check the referenced
1092 // class rather than the declaring class to preserve the semantics, i.e. using a FieldId
1093 // results in resolving the referenced class and that can for example throw OOME.
1094 const DexFile::FieldId& field_id = dex_file.GetFieldId(i);
1095 if (field_id.class_idx_ != last_class_idx) {
1096 last_class_idx = field_id.class_idx_;
1097 last_class = class_linker->LookupResolvedType(
1098 dex_file, last_class_idx, dex_cache, class_loader);
1099 if (last_class != nullptr && !KeepClass(last_class)) {
1100 last_class = nullptr;
1101 }
1102 }
1103 if (field == nullptr || i < stored_index) {
1104 if (last_class != nullptr) {
1105 const char* name = dex_file.StringDataByIdx(field_id.name_idx_);
1106 const char* type = dex_file.StringByTypeIdx(field_id.type_idx_);
1107 field = mirror::Class::FindField(Thread::Current(), last_class, name, type);
1108 if (field != nullptr) {
1109 // If the referenced class is in the image, the defining class must also be there.
1110 DCHECK(KeepClass(field->GetDeclaringClass()));
1111 dex_cache->SetResolvedField(i, field, target_ptr_size_);
1112 }
1113 }
1114 } else {
1115 DCHECK_EQ(i, stored_index);
1116 if (last_class == nullptr) {
1117 dex_cache->ClearResolvedField(stored_index, target_ptr_size_);
1118 }
1119 }
1120 }
1121 // Prune types and make the contents of the type array deterministic.
1122 // This is done after fields and methods as their lookup can touch the types array.
1123 for (size_t i = 0, end = dex_cache->GetDexFile()->NumTypeIds(); i < end; ++i) {
1124 dex::TypeIndex type_idx(i);
1125 uint32_t slot_idx = dex_cache->TypeSlotIndex(type_idx);
1126 mirror::TypeDexCachePair pair =
1127 dex_cache->GetResolvedTypes()[slot_idx].load(std::memory_order_relaxed);
1128 uint32_t stored_index = pair.index;
1129 ObjPtr<mirror::Class> klass = pair.object.Read();
1130 if (klass == nullptr || i < stored_index) {
1131 klass = class_linker->LookupResolvedType(dex_file, type_idx, dex_cache, class_loader);
1132 if (klass != nullptr) {
1133 DCHECK_EQ(dex_cache->GetResolvedType(type_idx), klass);
1134 stored_index = i; // For correct clearing below if not keeping the `klass`.
1135 }
1136 } else if (i == stored_index && !KeepClass(klass)) {
1137 dex_cache->ClearResolvedType(dex::TypeIndex(stored_index));
1138 }
1139 }
1140 // Strings do not need pruning, but the contents of the string array must be deterministic.
1141 for (size_t i = 0, end = dex_cache->GetDexFile()->NumStringIds(); i < end; ++i) {
1142 dex::StringIndex string_idx(i);
1143 uint32_t slot_idx = dex_cache->StringSlotIndex(string_idx);
1144 mirror::StringDexCachePair pair =
1145 dex_cache->GetStrings()[slot_idx].load(std::memory_order_relaxed);
1146 uint32_t stored_index = pair.index;
1147 ObjPtr<mirror::String> string = pair.object.Read();
1148 if (string == nullptr || i < stored_index) {
1149 string = class_linker->LookupString(dex_file, string_idx, dex_cache);
1150 DCHECK(string == nullptr || dex_cache->GetResolvedString(string_idx) == string);
1151 }
1152 }
1153}
1154
Brian Carlstrom7940e442013-07-12 13:46:57 -07001155void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001156 Runtime* runtime = Runtime::Current();
1157 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001158 Thread* self = Thread::Current();
Vladimir Markof25cc732017-03-16 16:18:15 +00001159 ScopedAssertNoThreadSuspension sa(__FUNCTION__);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001160
Mathieu Chartier72041a02017-07-14 18:23:25 -07001161 // Prune uses-library dex caches. Only prune the uses-library dex caches since we want to make
1162 // sure the other ones don't get unloaded before the OatWriter runs.
1163 class_linker->VisitClassTables(
1164 [&](ClassTable* table) REQUIRES_SHARED(Locks::mutator_lock_) {
1165 table->RemoveStrongRoots(
1166 [&](GcRoot<mirror::Object> root) REQUIRES_SHARED(Locks::mutator_lock_) {
1167 ObjPtr<mirror::Object> obj = root.Read();
1168 if (obj->IsDexCache()) {
1169 // Return true if the dex file is not one of the ones in the map.
1170 return dex_file_oat_index_map_.find(obj->AsDexCache()->GetDexFile()) ==
1171 dex_file_oat_index_map_.end();
1172 }
1173 // Return false to avoid removing.
1174 return false;
1175 });
1176 });
Mathieu Chartier696632e2016-06-03 17:47:32 -07001177
Brian Carlstrom7940e442013-07-12 13:46:57 -07001178 // Remove the undesired classes from the class roots.
Vladimir Markof25cc732017-03-16 16:18:15 +00001179 ObjPtr<mirror::ClassLoader> class_loader;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001180 {
1181 PruneClassLoaderClassesVisitor class_loader_visitor(this);
1182 VisitClassLoaders(&class_loader_visitor);
1183 VLOG(compiler) << "Pruned " << class_loader_visitor.GetRemovedClassCount() << " classes";
Vladimir Markof25cc732017-03-16 16:18:15 +00001184 class_loader = class_loader_visitor.GetClassLoader();
1185 DCHECK_EQ(class_loader != nullptr, compile_app_image_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001186 }
1187
1188 // Clear references to removed classes from the DexCaches.
Vladimir Markof25cc732017-03-16 16:18:15 +00001189 std::vector<ObjPtr<mirror::DexCache>> dex_caches;
1190 {
1191 ReaderMutexLock mu2(self, *Locks::dex_lock_);
1192 dex_caches.reserve(class_linker->GetDexCachesData().size());
1193 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1194 if (self->IsJWeakCleared(data.weak_root)) {
1195 continue;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001196 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001197 dex_caches.push_back(self->DecodeJObject(data.weak_root)->AsDexCache());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001198 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001199 }
1200 for (ObjPtr<mirror::DexCache> dex_cache : dex_caches) {
1201 PruneAndPreloadDexCache(dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001202 }
Andreas Gampe8ac75952015-06-02 21:01:45 -07001203
1204 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
1205 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001206
1207 // Clear to save RAM.
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00001208 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001209}
1210
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001211void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001212 if (compiler_driver_.GetImageClasses() != nullptr) {
Andreas Gampe1c158a02017-07-13 17:26:19 -07001213 auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1214 if (obj->IsClass() && !IsInBootImage(obj)) {
1215 Class* klass = obj->AsClass();
1216 if (!KeepClass(klass)) {
1217 DumpImageClasses();
1218 std::string temp;
1219 CHECK(KeepClass(klass))
1220 << Runtime::Current()->GetHeap()->GetVerification()->FirstPathFromRootSet(klass);
1221 }
1222 }
1223 };
Mathieu Chartier590fee92013-09-13 13:46:47 -07001224 gc::Heap* heap = Runtime::Current()->GetHeap();
Andreas Gampe1c158a02017-07-13 17:26:19 -07001225 heap->VisitObjects(visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001226 }
1227}
1228
1229void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001230 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001231 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001232 for (const std::string& image_class : *image_classes) {
1233 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001234 }
1235}
1236
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001237mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
1238 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +00001239 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001240 ObjPtr<mirror::String> const found = image_info.intern_table_->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001241 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
1242 << string->ToModifiedUtf8();
1243 if (found != nullptr) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001244 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001245 }
1246 }
1247 if (compile_app_image_) {
1248 Runtime* const runtime = Runtime::Current();
Mathieu Chartier9e868092016-10-31 14:58:04 -07001249 ObjPtr<mirror::String> found = runtime->GetInternTable()->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001250 // If we found it in the runtime intern table it could either be in the boot image or interned
1251 // during app image compilation. If it was in the boot image return that, otherwise return null
1252 // since it belongs to another image space.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001253 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found.Ptr())) {
1254 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001255 }
1256 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
1257 << string->ToModifiedUtf8();
1258 }
1259 return nullptr;
1260}
1261
Brian Carlstrom7940e442013-07-12 13:46:57 -07001262
Vladimir Marko944da602016-02-19 12:27:55 +00001263ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001264 Runtime* runtime = Runtime::Current();
1265 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001266 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001267 StackHandleScope<3> hs(self);
1268 Handle<Class> object_array_class(hs.NewHandle(
1269 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001270
Jeff Haodcdc85b2015-12-04 14:06:18 -08001271 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +00001272 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001273 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +00001274 size_t image_oat_index = pair.second;
1275 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001276 image_dex_files.insert(image_dex_file);
1277 }
1278 }
1279
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001280 // build an Object[] of all the DexCaches used in the source_space_.
1281 // Since we can't hold the dex lock when allocating the dex_caches
1282 // ObjectArray, we lock the dex lock twice, first to get the number
1283 // of dex caches first and then lock it again to copy the dex
1284 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001285 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001286 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001287 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001288 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001289 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001290 ObjPtr<mirror::DexCache> dex_cache =
1291 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001292 if (dex_cache == nullptr) {
1293 continue;
1294 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001295 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001296 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001297 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1298 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001299 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001300 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001301 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001302 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001303 CHECK(dex_caches != nullptr) << "Failed to allocate a dex cache array.";
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001304 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001305 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001306 size_t non_image_dex_caches = 0;
1307 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001308 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001309 ObjPtr<mirror::DexCache> dex_cache =
1310 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001311 if (dex_cache == nullptr) {
1312 continue;
1313 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001314 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001315 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001316 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1317 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001318 }
1319 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1320 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001321 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001322 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001323 ObjPtr<mirror::DexCache> dex_cache =
1324 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001325 if (dex_cache == nullptr) {
1326 continue;
1327 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001328 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001329 if (!IsInBootImage(dex_cache.Ptr()) &&
1330 image_dex_files.find(dex_file) != image_dex_files.end()) {
1331 dex_caches->Set<false>(i, dex_cache.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001332 ++i;
1333 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001334 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001335 }
1336
1337 // build an Object[] of the roots needed to restore the runtime
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001338 int32_t image_roots_size = ImageHeader::NumberOfImageRoots(compile_app_image_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001339 auto image_roots(hs.NewHandle(
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001340 ObjectArray<Object>::Alloc(self, object_array_class.Get(), image_roots_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001341 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001342 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001343 // image_roots[ImageHeader::kClassLoader] will be set later for app image.
1344 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1345 "Class loader should be the last image root.");
1346 for (int32_t i = 0; i < ImageHeader::kImageRootsMax - 1; ++i) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001347 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001348 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001349 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001350}
1351
Mathieu Chartier496577f2016-09-20 15:33:31 -07001352mirror::Object* ImageWriter::TryAssignBinSlot(WorkStack& work_stack,
1353 mirror::Object* obj,
1354 size_t oat_index) {
1355 if (obj == nullptr || IsInBootImage(obj)) {
1356 // Object is null or already in the image, there is no work to do.
1357 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001358 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001359 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001360 // We want to intern all strings but also assign offsets for the source string. Since the
1361 // pruning phase has already happened, if we intern a string to one in the image we still
1362 // end up copying an unreachable string.
1363 if (obj->IsString()) {
1364 // Need to check if the string is already interned in another image info so that we don't have
1365 // the intern tables of two different images contain the same string.
1366 mirror::String* interned = FindInternedString(obj->AsString());
1367 if (interned == nullptr) {
1368 // Not in another image space, insert to our table.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001369 interned =
1370 GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString()).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001371 DCHECK_EQ(interned, obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001372 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001373 } else if (obj->IsDexCache()) {
1374 oat_index = GetOatIndexForDexCache(obj->AsDexCache());
1375 } else if (obj->IsClass()) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001376 // Visit and assign offsets for fields and field arrays.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001377 mirror::Class* as_klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001378 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Vladimir Marko72ab6842017-01-20 19:32:50 +00001379 DCHECK(!as_klass->IsErroneous()) << as_klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001380 if (compile_app_image_) {
1381 // Extra sanity, no boot loader classes should be left!
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00001382 CHECK(!IsBootClassLoaderClass(as_klass)) << as_klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001383 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001384 LengthPrefixedArray<ArtField>* fields[] = {
1385 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1386 };
Mathieu Chartier496577f2016-09-20 15:33:31 -07001387 // Overwrite the oat index value since the class' dex cache is more accurate of where it
1388 // belongs.
1389 oat_index = GetOatIndexForDexCache(dex_cache);
Vladimir Marko944da602016-02-19 12:27:55 +00001390 ImageInfo& image_info = GetImageInfo(oat_index);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001391 if (!compile_app_image_) {
1392 // Note: Avoid locking to prevent lock order violations from root visiting;
1393 // image_info.class_table_ is only accessed from the image writer.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001394 image_info.class_table_->InsertWithoutLocks(as_klass);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001395 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001396 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1397 // Total array length including header.
1398 if (cur_fields != nullptr) {
1399 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1400 // Forward the entire array at once.
1401 auto it = native_object_relocations_.find(cur_fields);
1402 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1403 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001404 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001405 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001406 native_object_relocations_.emplace(
1407 cur_fields,
1408 NativeObjectRelocation {
1409 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1410 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001411 offset += header_size;
1412 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001413 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001414 // Need to forward arrays separate of fields.
1415 ArtField* field = &cur_fields->At(i);
1416 auto it2 = native_object_relocations_.find(field);
1417 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
David Sehr709b0702016-10-13 09:12:37 -07001418 << " already assigned " << field->PrettyField() << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001419 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001420 native_object_relocations_.emplace(
1421 field,
1422 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001423 offset += sizeof(ArtField);
1424 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001425 }
1426 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001427 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001428 size_t num_methods = as_klass->NumMethods();
1429 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001430 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001431 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1432 if (WillMethodBeDirty(&m)) {
1433 any_dirty = true;
1434 break;
1435 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001436 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001437 NativeObjectRelocationType type = any_dirty
1438 ? kNativeObjectRelocationTypeArtMethodDirty
1439 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001440 Bin bin_type = BinTypeForNativeRelocationType(type);
1441 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001442 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1443 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001444 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1445 method_size,
1446 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001447 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001448 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001449 CHECK(it == native_object_relocations_.end())
1450 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001451 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001452 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001453 native_object_relocations_.emplace(array,
1454 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001455 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001456 offset,
1457 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1458 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001459 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001460 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001461 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001462 }
Alex Lighte64300b2015-12-15 15:02:47 -08001463 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001464 }
1465 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1466 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001467 if (as_klass->ShouldHaveImt()) {
1468 ImTable* imt = as_klass->GetImt(target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001469 if (TryAssignImTableOffset(imt, oat_index)) {
1470 // Since imt's can be shared only do this the first time to not double count imt method
1471 // fixups.
1472 for (size_t i = 0; i < ImTable::kSize; ++i) {
1473 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
1474 DCHECK(imt_method != nullptr);
1475 if (imt_method->IsRuntimeMethod() &&
1476 !IsInBootImage(imt_method) &&
1477 !NativeRelocationAssigned(imt_method)) {
1478 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
1479 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001480 }
1481 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001482 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001483 } else if (obj->IsClassLoader()) {
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001484 // Register the class loader if it has a class table.
1485 // The fake boot class loader should not get registered and we should end up with only one
1486 // class loader.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001487 mirror::ClassLoader* class_loader = obj->AsClassLoader();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001488 if (class_loader->GetClassTable() != nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001489 DCHECK(compile_app_image_);
1490 DCHECK(class_loaders_.empty());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001491 class_loaders_.insert(class_loader);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001492 ImageInfo& image_info = GetImageInfo(oat_index);
1493 // Note: Avoid locking to prevent lock order violations from root visiting;
1494 // image_info.class_table_ table is only accessed from the image writer
1495 // and class_loader->GetClassTable() is iterated but not modified.
1496 image_info.class_table_->CopyWithoutLocks(*class_loader->GetClassTable());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001497 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001498 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001499 AssignImageBinSlot(obj, oat_index);
1500 work_stack.emplace(obj, oat_index);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001501 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001502 if (obj->IsString()) {
1503 // Always return the interned string if there exists one.
1504 mirror::String* interned = FindInternedString(obj->AsString());
1505 if (interned != nullptr) {
1506 return interned;
1507 }
1508 }
1509 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001510}
1511
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001512bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1513 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1514}
1515
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001516bool ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001517 // No offset, or already assigned.
1518 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001519 return false;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001520 }
1521 // If the method is a conflict method we also want to assign the conflict table offset.
1522 ImageInfo& image_info = GetImageInfo(oat_index);
1523 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1524 native_object_relocations_.emplace(
1525 imt,
1526 NativeObjectRelocation {
1527 oat_index,
1528 image_info.bin_slot_sizes_[kBinImTable],
1529 kNativeObjectRelocationTypeIMTable});
1530 image_info.bin_slot_sizes_[kBinImTable] += size;
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001531 return true;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001532}
1533
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001534void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1535 // No offset, or already assigned.
1536 if (table == nullptr || NativeRelocationAssigned(table)) {
1537 return;
1538 }
1539 CHECK(!IsInBootImage(table));
1540 // If the method is a conflict method we also want to assign the conflict table offset.
1541 ImageInfo& image_info = GetImageInfo(oat_index);
1542 const size_t size = table->ComputeSize(target_ptr_size_);
1543 native_object_relocations_.emplace(
1544 table,
1545 NativeObjectRelocation {
1546 oat_index,
1547 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1548 kNativeObjectRelocationTypeIMTConflictTable});
1549 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1550}
1551
Jeff Haodcdc85b2015-12-04 14:06:18 -08001552void ImageWriter::AssignMethodOffset(ArtMethod* method,
1553 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001554 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001555 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001556 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
David Sehr709b0702016-10-13 09:12:37 -07001557 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001558 if (method->IsRuntimeMethod()) {
1559 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1560 }
Vladimir Marko944da602016-02-19 12:27:55 +00001561 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001562 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001563 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001564 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001565}
1566
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001567void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001568 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001569 CHECK(obj != nullptr);
1570
1571 // We know the bin slot, and the total bin sizes for all objects by now,
1572 // so calculate the object's final image offset.
1573
1574 DCHECK(IsImageBinSlotAssigned(obj));
1575 BinSlot bin_slot = GetImageBinSlot(obj);
1576 // Change the lockword from a bin slot into an offset
1577 AssignImageOffset(obj, bin_slot);
1578}
1579
Mathieu Chartier496577f2016-09-20 15:33:31 -07001580class ImageWriter::VisitReferencesVisitor {
1581 public:
1582 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index)
1583 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {}
1584
1585 // Fix up separately since we also need to fix up method entrypoints.
1586 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1587 REQUIRES_SHARED(Locks::mutator_lock_) {
1588 if (!root->IsNull()) {
1589 VisitRoot(root);
1590 }
1591 }
1592
1593 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1594 REQUIRES_SHARED(Locks::mutator_lock_) {
1595 root->Assign(VisitReference(root->AsMirrorPtr()));
1596 }
1597
Mathieu Chartier31e88222016-10-14 18:43:19 -07001598 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
Mathieu Chartier496577f2016-09-20 15:33:31 -07001599 MemberOffset offset,
1600 bool is_static ATTRIBUTE_UNUSED) const
1601 REQUIRES_SHARED(Locks::mutator_lock_) {
1602 mirror::Object* ref =
1603 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1604 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1605 }
1606
Mathieu Chartier31e88222016-10-14 18:43:19 -07001607 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1608 ObjPtr<mirror::Reference> ref) const
Mathieu Chartier496577f2016-09-20 15:33:31 -07001609 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001610 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001611 }
1612
1613 private:
1614 mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1615 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_);
1616 }
1617
1618 ImageWriter* const image_writer_;
1619 WorkStack* const work_stack_;
1620 const size_t oat_index_;
1621};
1622
1623class ImageWriter::GetRootsVisitor : public RootVisitor {
1624 public:
1625 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {}
1626
1627 void VisitRoots(mirror::Object*** roots,
1628 size_t count,
1629 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1630 REQUIRES_SHARED(Locks::mutator_lock_) {
1631 for (size_t i = 0; i < count; ++i) {
1632 roots_->push_back(*roots[i]);
1633 }
1634 }
1635
1636 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1637 size_t count,
1638 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1639 REQUIRES_SHARED(Locks::mutator_lock_) {
1640 for (size_t i = 0; i < count; ++i) {
1641 roots_->push_back(roots[i]->AsMirrorPtr());
1642 }
1643 }
1644
1645 private:
1646 std::vector<mirror::Object*>* const roots_;
1647};
1648
1649void ImageWriter::ProcessWorkStack(WorkStack* work_stack) {
1650 while (!work_stack->empty()) {
1651 std::pair<mirror::Object*, size_t> pair(work_stack->top());
1652 work_stack->pop();
1653 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second);
1654 // Walk references and assign bin slots for them.
1655 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1656 visitor,
1657 visitor);
1658 }
1659}
1660
Vladimir Markof4da6752014-08-01 19:04:18 +01001661void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001662 Thread* const self = Thread::Current();
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07001663 VariableSizedHandleScope handles(self);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001664 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001665 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1666 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001667 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001668
Mathieu Chartier496577f2016-09-20 15:33:31 -07001669 Runtime* const runtime = Runtime::Current();
1670 gc::Heap* const heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001671
Mathieu Chartier31e89252013-08-28 11:29:12 -07001672 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001673 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001674 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001675
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001676 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001677 // Write the image runtime methods.
1678 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1679 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1680 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001681 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001682 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves);
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001683 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001684 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly);
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001685 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001686 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001687 image_methods_[ImageHeader::kSaveEverythingMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001688 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything);
Mingyao Yang0a87a652017-04-12 13:43:15 -07001689 image_methods_[ImageHeader::kSaveEverythingMethodForClinit] =
1690 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForClinit);
1691 image_methods_[ImageHeader::kSaveEverythingMethodForSuspendCheck] =
1692 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForSuspendCheck);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001693 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001694 for (auto* m : image_methods_) {
1695 CHECK(m != nullptr);
1696 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001697 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1698 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001699 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001700 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001701 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001702
Mathieu Chartier496577f2016-09-20 15:33:31 -07001703 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
1704 // this lock while holding other locks may cause lock order violations.
Andreas Gampe1c158a02017-07-13 17:26:19 -07001705 {
1706 auto deflate_monitor = [](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1707 Monitor::Deflate(Thread::Current(), obj);
1708 };
1709 heap->VisitObjects(deflate_monitor);
1710 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001711
1712 // Work list of <object, oat_index> for objects. Everything on the stack must already be
1713 // assigned a bin slot.
1714 WorkStack work_stack;
1715
1716 // Special case interned strings to put them in the image they are likely to be resolved from.
1717 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
1718 auto it = dex_file_oat_index_map_.find(dex_file);
1719 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1720 const size_t oat_index = it->second;
1721 InternTable* const intern_table = runtime->GetInternTable();
1722 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
1723 uint32_t utf16_length;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001724 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(dex::StringIndex(i),
1725 &utf16_length);
Mathieu Chartier9e868092016-10-31 14:58:04 -07001726 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001727 TryAssignBinSlot(work_stack, string, oat_index);
1728 }
1729 }
1730
1731 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor
1732 // visits roots while holding various locks.
1733 {
1734 std::vector<mirror::Object*> roots;
1735 GetRootsVisitor root_visitor(&roots);
1736 runtime->VisitRoots(&root_visitor);
1737 for (mirror::Object* obj : roots) {
1738 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex());
1739 }
1740 }
1741 ProcessWorkStack(&work_stack);
1742
1743 // For app images, there may be objects that are only held live by the by the boot image. One
1744 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback
1745 // does not fail any checks. TODO: We should probably avoid copying these objects.
1746 if (compile_app_image_) {
1747 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) {
1748 DCHECK(space->IsImageSpace());
1749 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1750 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1751 reinterpret_cast<uintptr_t>(space->Limit()),
1752 [this, &work_stack](mirror::Object* obj)
1753 REQUIRES_SHARED(Locks::mutator_lock_) {
1754 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex());
1755 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot).
1756 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1757 visitor,
1758 visitor);
1759 });
1760 }
1761 // Process the work stack in case anything was added by TryAssignBinSlot.
1762 ProcessWorkStack(&work_stack);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001763
1764 // Store the class loader in the class roots.
1765 CHECK_EQ(class_loaders_.size(), 1u);
1766 CHECK_EQ(image_roots.size(), 1u);
1767 CHECK(*class_loaders_.begin() != nullptr);
1768 image_roots[0]->Set<false>(ImageHeader::kClassLoader, *class_loaders_.begin());
Mathieu Chartier496577f2016-09-20 15:33:31 -07001769 }
1770
1771 // Verify that all objects have assigned image bin slots.
Andreas Gampe1c158a02017-07-13 17:26:19 -07001772 {
1773 auto ensure_bin_slots_assigned = [&](mirror::Object* obj)
1774 REQUIRES_SHARED(Locks::mutator_lock_) {
1775 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) {
1776 CHECK(IsImageBinSlotAssigned(obj)) << mirror::Object::PrettyTypeOf(obj) << " " << obj;
1777 }
1778 };
1779 heap->VisitObjects(ensure_bin_slots_assigned);
1780 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001781
Vladimir Marko05792b92015-08-03 11:56:49 +01001782 // Calculate size of the dex cache arrays slot and prepare offsets.
1783 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001784
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001785 // Calculate the sizes of the intern tables, class tables, and fixup tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001786 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001787 // Calculate how big the intern table will be after being serialized.
1788 InternTable* const intern_table = image_info.intern_table_.get();
1789 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
Vladimir Marko1a1de672016-10-13 12:53:15 +01001790 if (intern_table->StrongSize() != 0u) {
1791 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1792 }
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001793
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001794 // Calculate the size of the class table.
1795 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001796 DCHECK_EQ(image_info.class_table_->NumReferencedZygoteClasses(), 0u);
1797 if (image_info.class_table_->NumReferencedNonZygoteClasses() != 0u) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001798 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
1799 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001800 }
1801
Vladimir Markocf36d492015-08-12 19:27:26 +01001802 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001803 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001804 size_t bin_offset = image_objects_offset_begin_;
1805 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001806 switch (i) {
1807 case kBinArtMethodClean:
1808 case kBinArtMethodDirty: {
1809 bin_offset = RoundUp(bin_offset, method_alignment);
1810 break;
1811 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001812 case kBinDexCacheArray:
Vladimir Markof44d36c2017-03-14 14:18:46 +00001813 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment(target_ptr_size_));
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001814 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001815 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001816 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001817 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001818 break;
1819 }
1820 default: {
1821 // Normal alignment.
1822 }
1823 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001824 image_info.bin_slot_offsets_[i] = bin_offset;
1825 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001826 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001827 // NOTE: There may be additional padding between the bin slots and the intern table.
1828 DCHECK_EQ(image_info.image_end_,
1829 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001830 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001831
Jeff Haodcdc85b2015-12-04 14:06:18 -08001832 // Calculate image offsets.
1833 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001834 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001835 image_info.image_begin_ = global_image_begin_ + image_offset;
1836 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001837 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001838 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001839 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001840 image_offset += image_info.image_size_;
1841 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001842
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001843 // 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 -07001844 {
1845 auto unbin_objects_into_offset = [&](mirror::Object* obj)
1846 REQUIRES_SHARED(Locks::mutator_lock_) {
1847 if (!IsInBootImage(obj)) {
1848 UnbinObjectsIntoOffset(obj);
1849 }
1850 };
1851 heap->VisitObjects(unbin_objects_into_offset);
1852 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001853
Jeff Haodcdc85b2015-12-04 14:06:18 -08001854 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001855 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001856 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1857 i++;
1858 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001859
Mathieu Chartiere401d142015-04-22 13:56:20 -07001860 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001861 for (auto& pair : native_object_relocations_) {
1862 NativeObjectRelocation& relocation = pair.second;
1863 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001864 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001865 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001866 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001867}
1868
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001869size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001870 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001871
1872 // Do not round up any sections here that are represented by the bins since it will break
1873 // offsets.
1874
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001875 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001876 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001877 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001878
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001879 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001880 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1881 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001882 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001883
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001884 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001885 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1886 *methods_section = ImageSection(
1887 bin_slot_offsets_[kBinArtMethodClean],
1888 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1889
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001890 // IMT section.
1891 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1892 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1893
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001894 // Conflict tables section.
1895 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1896 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1897 bin_slot_sizes_[kBinIMTConflictTable]);
1898
1899 // Runtime methods section.
1900 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1901 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1902 bin_slot_sizes_[kBinRuntimeMethod]);
1903
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001904 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001905 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1906 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1907 bin_slot_sizes_[kBinDexCacheArray]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001908 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001909 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001910 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001911 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001912 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1913 cur_pos = interned_strings_section->End();
1914 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1915 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1916 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001917 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001918 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001919 cur_pos = class_table_section->End();
1920 // Image end goes right before the start of the image bitmap.
1921 return cur_pos;
1922}
1923
Vladimir Marko944da602016-02-19 12:27:55 +00001924void ImageWriter::CreateHeader(size_t oat_index) {
1925 ImageInfo& image_info = GetImageInfo(oat_index);
1926 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1927 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1928 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001929
1930 // Create the image sections.
1931 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001932 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001933
Mathieu Chartiere401d142015-04-22 13:56:20 -07001934 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001935 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001936 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001937 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001938 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001939 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001940 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001941 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001942 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1943 ++idx;
1944 }
1945 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001946 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1947 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1948 << " Image offset=" << image_info.image_offset_ << std::dec;
1949 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1950 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1951 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1952 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001953 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001954 // Store boot image info for app image so that we can relocate.
1955 uint32_t boot_image_begin = 0;
1956 uint32_t boot_image_end = 0;
1957 uint32_t boot_oat_begin = 0;
1958 uint32_t boot_oat_end = 0;
1959 gc::Heap* const heap = Runtime::Current()->GetHeap();
1960 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001961
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001962 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1963 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001964 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1965 image_end,
1966 sections,
1967 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001968 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001969 PointerToLowMemUInt32(oat_file_begin),
1970 PointerToLowMemUInt32(image_info.oat_data_begin_),
1971 PointerToLowMemUInt32(oat_data_end),
1972 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001973 boot_image_begin,
1974 boot_image_end - boot_image_begin,
1975 boot_oat_begin,
1976 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001977 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001978 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001979 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001980 image_storage_mode_,
1981 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001982}
1983
1984ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001985 auto it = native_object_relocations_.find(method);
David Sehr709b0702016-10-13 09:12:37 -07001986 CHECK(it != native_object_relocations_.end()) << ArtMethod::PrettyMethod(method) << " @ "
1987 << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001988 size_t oat_index = GetOatIndex(method->GetDexCache());
1989 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001990 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1991 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001992}
1993
Vladimir Markoad06b982016-11-17 16:38:59 +00001994class ImageWriter::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001995 public:
1996 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1997 }
1998
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001999 void VisitRoots(mirror::Object*** roots ATTRIBUTE_UNUSED,
2000 size_t count ATTRIBUTE_UNUSED,
2001 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002002 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002003 LOG(FATAL) << "Unsupported";
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002004 }
2005
2006 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
2007 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002008 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002009 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002010 image_writer_->CopyReference(roots[i], roots[i]->AsMirrorPtr());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002011 }
2012 }
2013
2014 private:
2015 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002016};
2017
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002018void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
2019 for (size_t i = 0; i < ImTable::kSize; ++i) {
2020 ArtMethod* method = orig->Get(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002021 void** address = reinterpret_cast<void**>(copy->AddressOfElement(i, target_ptr_size_));
2022 CopyAndFixupPointer(address, method);
2023 DCHECK_EQ(copy->Get(i, target_ptr_size_), NativeLocationInImage(method));
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002024 }
2025}
2026
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002027void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
2028 const size_t count = orig->NumEntries(target_ptr_size_);
2029 for (size_t i = 0; i < count; ++i) {
2030 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
2031 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002032 CopyAndFixupPointer(copy->AddressOfInterfaceMethod(i, target_ptr_size_), interface_method);
2033 CopyAndFixupPointer(copy->AddressOfImplementationMethod(i, target_ptr_size_),
2034 implementation_method);
2035 DCHECK_EQ(copy->GetInterfaceMethod(i, target_ptr_size_),
2036 NativeLocationInImage(interface_method));
2037 DCHECK_EQ(copy->GetImplementationMethod(i, target_ptr_size_),
2038 NativeLocationInImage(implementation_method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002039 }
2040}
2041
Vladimir Marko944da602016-02-19 12:27:55 +00002042void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002043 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002044 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002045 for (auto& pair : native_object_relocations_) {
2046 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002047 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00002048 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002049 continue;
2050 }
2051 auto* dest = image_info.image_->Begin() + relocation.offset;
2052 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002053 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002054 switch (relocation.type) {
2055 case kNativeObjectRelocationTypeArtField: {
2056 memcpy(dest, pair.first, sizeof(ArtField));
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002057 CopyReference(
2058 reinterpret_cast<ArtField*>(dest)->GetDeclaringClassAddressWithoutBarrier(),
2059 reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass().Ptr());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002060 break;
2061 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002062 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002063 case kNativeObjectRelocationTypeArtMethodClean:
2064 case kNativeObjectRelocationTypeArtMethodDirty: {
2065 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08002066 reinterpret_cast<ArtMethod*>(dest),
2067 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002068 break;
2069 }
2070 // For arrays, copy just the header since the elements will get copied by their corresponding
2071 // relocations.
2072 case kNativeObjectRelocationTypeArtFieldArray: {
2073 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
2074 break;
2075 }
2076 case kNativeObjectRelocationTypeArtMethodArrayClean:
2077 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00002078 size_t size = ArtMethod::Size(target_ptr_size_);
2079 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
2080 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
2081 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
2082 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002083 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00002084 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002085 case kNativeObjectRelocationTypeDexCacheArray:
2086 // Nothing to copy here, everything is done in FixupDexCache().
2087 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002088 case kNativeObjectRelocationTypeIMTable: {
2089 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
2090 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
2091 CopyAndFixupImTable(orig_imt, dest_imt);
2092 break;
2093 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002094 case kNativeObjectRelocationTypeIMTConflictTable: {
2095 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
2096 CopyAndFixupImtConflictTable(
2097 orig_table,
2098 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
2099 break;
2100 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002101 }
2102 }
2103 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002104 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002105 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002106 ArtMethod* method = image_methods_[i];
2107 CHECK(method != nullptr);
2108 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002109 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002110 }
2111 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002112 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002113 FixupRootVisitor root_visitor(this);
2114
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002115 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002116 if (image_info.intern_table_bytes_ > 0) {
2117 const ImageSection& intern_table_section = image_header->GetImageSection(
2118 ImageHeader::kSectionInternedStrings);
2119 InternTable* const intern_table = image_info.intern_table_.get();
2120 uint8_t* const intern_table_memory_ptr =
2121 image_info.image_->Begin() + intern_table_section.Offset();
2122 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
2123 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
2124 // Fixup the pointers in the newly written intern table to contain image addresses.
2125 InternTable temp_intern_table;
2126 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
2127 // the VisitRoots() will update the memory directly rather than the copies.
2128 // This also relies on visit roots not doing any verification which could fail after we update
2129 // the roots to be the image addresses.
2130 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
2131 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
2132 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
2133 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002134 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
2135 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002136 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002137 const ImageSection& class_table_section = image_header->GetImageSection(
2138 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002139 uint8_t* const class_table_memory_ptr =
2140 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002141 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002142
2143 ClassTable* table = image_info.class_table_.get();
2144 CHECK(table != nullptr);
2145 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
2146 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
2147 // Fixup the pointers in the newly written class table to contain image addresses. See
2148 // above comment for intern tables.
2149 ClassTable temp_class_table;
2150 temp_class_table.ReadFromMemory(class_table_memory_ptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002151 CHECK_EQ(temp_class_table.NumReferencedZygoteClasses(),
2152 table->NumReferencedNonZygoteClasses() + table->NumReferencedZygoteClasses());
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002153 UnbufferedRootVisitor visitor(&root_visitor, RootInfo(kRootUnknown));
2154 temp_class_table.VisitRoots(visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002155 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002156}
2157
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08002158void ImageWriter::CopyAndFixupObjects() {
Andreas Gampe1c158a02017-07-13 17:26:19 -07002159 auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
2160 DCHECK(obj != nullptr);
2161 CopyAndFixupObject(obj);
2162 };
2163 Runtime::Current()->GetHeap()->VisitObjects(visitor);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002164 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002165 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08002166 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07002167 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
2168 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002169 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002170 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002171}
2172
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002173void ImageWriter::FixupPointerArray(mirror::Object* dst,
2174 mirror::PointerArray* arr,
2175 mirror::Class* klass,
2176 Bin array_type) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002177 CHECK(klass->IsArrayClass());
David Sehr709b0702016-10-13 09:12:37 -07002178 CHECK(arr->IsIntArray() || arr->IsLongArray()) << klass->PrettyClass() << " " << arr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002179 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07002180 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002181 dst->SetClass(GetImageAddress(arr->GetClass()));
2182 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002183 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002184 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002185 if (kIsDebugBuild && elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002186 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01002187 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002188 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002189 auto* method = reinterpret_cast<ArtMethod*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07002190 LOG(FATAL) << "No relocation entry for ArtMethod " << method->PrettyMethod() << " @ "
2191 << method << " idx=" << i << "/" << num_elements << " with declaring class "
2192 << Class::PrettyClass(method->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002193 } else {
2194 CHECK_EQ(array_type, kBinArtField);
2195 auto* field = reinterpret_cast<ArtField*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07002196 LOG(FATAL) << "No relocation entry for ArtField " << field->PrettyField() << " @ "
Mathieu Chartiere401d142015-04-22 13:56:20 -07002197 << field << " idx=" << i << "/" << num_elements << " with declaring class "
David Sehr709b0702016-10-13 09:12:37 -07002198 << Class::PrettyClass(field->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002199 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002200 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002201 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002202 }
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002203 CopyAndFixupPointer(dest_array->ElementAddress(i, target_ptr_size_), elem);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002204 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002205}
2206
2207void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002208 if (IsInBootImage(obj)) {
2209 return;
2210 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002211 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00002212 size_t oat_index = GetOatIndex(obj);
2213 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002214 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
2215 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002216 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002217
Jeff Haodcdc85b2015-12-04 14:06:18 -08002218 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002219
2220 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002221 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002222 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002223
Mathieu Chartierad2541a2013-10-25 10:05:23 -07002224 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
2225 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002226 const auto it = saved_hashcode_map_.find(obj);
2227 dst->SetLockWord(it != saved_hashcode_map_.end() ?
2228 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002229 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
2230 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
2231 // safe since we mark all of the objects that may reference non immune objects as gray.
2232 CHECK(dst->AtomicSetMarkBit(0, 1));
2233 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002234 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002235}
2236
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002237// Rewrite all the references in the copied object to point to their image address equivalent
Vladimir Markoad06b982016-11-17 16:38:59 +00002238class ImageWriter::FixupVisitor {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002239 public:
2240 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
2241 }
2242
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002243 // Ignore class roots since we don't have a way to map them to the destination. These are handled
2244 // with other logic.
2245 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
2246 const {}
2247 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
2248
2249
Mathieu Chartier31e88222016-10-14 18:43:19 -07002250 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002251 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07002252 ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002253 // Copy the reference and record the fixup if necessary.
2254 image_writer_->CopyReference(
2255 copy_->GetFieldObjectReferenceAddr<kVerifyNone>(offset),
2256 ref.Ptr());
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002257 }
2258
2259 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07002260 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2261 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002262 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002263 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002264 }
2265
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002266 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002267 ImageWriter* const image_writer_;
2268 mirror::Object* const copy_;
2269};
2270
Vladimir Markoad06b982016-11-17 16:38:59 +00002271class ImageWriter::FixupClassVisitor FINAL : public FixupVisitor {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002272 public:
2273 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
2274 }
2275
Mathieu Chartier31e88222016-10-14 18:43:19 -07002276 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07002277 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002278 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002279 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002280 }
2281
Mathieu Chartier31e88222016-10-14 18:43:19 -07002282 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2283 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002284 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002285 LOG(FATAL) << "Reference not expected here.";
2286 }
2287};
2288
Vladimir Marko05792b92015-08-03 11:56:49 +01002289uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
2290 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002291 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002292 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002293 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
2294 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002295 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01002296 return relocation.offset;
2297}
2298
2299template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002300std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002301 std::ostringstream oss;
2302 oss << ptr;
2303 return oss.str();
2304}
2305
2306template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002307std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07002308 return ArtMethod::PrettyMethod(method);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002309}
2310
2311template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002312T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002313 if (obj == nullptr || IsInBootImage(obj)) {
2314 return obj;
2315 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002316 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002317 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
2318 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002319 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00002320 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002321 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002322 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002323}
2324
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002325template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08002326T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
2327 if (obj == nullptr || IsInBootImage(obj)) {
2328 return obj;
2329 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002330 size_t oat_index = GetOatIndexForDexCache(dex_cache);
2331 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002332 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
2333 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002334}
2335
Vladimir Markoad06b982016-11-17 16:38:59 +00002336class ImageWriter::NativeLocationVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002337 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002338 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002339
2340 template <typename T>
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002341 T* operator()(T* ptr, void** dest_addr = nullptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
2342 if (dest_addr != nullptr) {
2343 image_writer_->CopyAndFixupPointer(dest_addr, ptr);
2344 }
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002345 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002346 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002347
2348 private:
2349 ImageWriter* const image_writer_;
2350};
2351
2352void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002353 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002354 FixupClassVisitor visitor(this, copy);
Mathieu Chartier31e88222016-10-14 18:43:19 -07002355 ObjPtr<mirror::Object>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002356
2357 // Remove the clinitThreadId. This is required for image determinism.
2358 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002359}
2360
Ian Rogersef7d42f2014-01-06 12:55:46 -08002361void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002362 DCHECK(orig != nullptr);
2363 DCHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002364 if (kUseBakerReadBarrier) {
2365 orig->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002366 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002367 auto* klass = orig->GetClass();
2368 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002369 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07002370 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
2371 if (it != pointer_arrays_.end()) {
2372 // Should only need to fixup every pointer array exactly once.
2373 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
2374 pointer_arrays_.erase(it);
2375 return;
2376 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002377 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002378 if (orig->IsClass()) {
2379 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002380 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002381 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
2382 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01002383 auto* dest = down_cast<mirror::Executable*>(copy);
2384 auto* src = down_cast<mirror::Executable*>(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002385 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05002386 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01002387 } else if (!klass->IsArrayClass()) {
2388 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2389 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
2390 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002391 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002392 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002393 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2394 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002395 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002396 // Also set allocator to null to be safe. The allocator is created when we create the class
2397 // table. We also never expect to unload things in the image since they are held live as
2398 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002399 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002400 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002401 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002402 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002403 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002404 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002405}
2406
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002407class ImageWriter::ImageAddressVisitorForDexCacheArray {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002408 public:
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002409 explicit ImageAddressVisitorForDexCacheArray(ImageWriter* image_writer)
2410 : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002411
2412 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002413 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002414 return image_writer_->GetImageAddress(ptr);
2415 }
2416
2417 private:
2418 ImageWriter* const image_writer_;
2419};
2420
Vladimir Marko05792b92015-08-03 11:56:49 +01002421void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2422 mirror::DexCache* copy_dex_cache) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002423 ImageAddressVisitorForDexCacheArray fixup_visitor(this);
Vladimir Marko05792b92015-08-03 11:56:49 +01002424 // Though the DexCache array fields are usually treated as native pointers, we set the full
2425 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2426 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2427 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002428 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002429 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002430 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002431 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002432 PointerSize::k64);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002433 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache), fixup_visitor);
Vladimir Marko05792b92015-08-03 11:56:49 +01002434 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002435 mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
Vladimir Marko05792b92015-08-03 11:56:49 +01002436 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002437 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002438 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002439 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002440 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002441 fixup_visitor);
Vladimir Marko05792b92015-08-03 11:56:49 +01002442 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002443 mirror::MethodDexCacheType* orig_methods = orig_dex_cache->GetResolvedMethods();
Vladimir Marko05792b92015-08-03 11:56:49 +01002444 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002445 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002446 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002447 PointerSize::k64);
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002448 mirror::MethodDexCacheType* copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002449 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002450 mirror::MethodDexCachePair orig_pair =
2451 mirror::DexCache::GetNativePairPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002452 // NativeLocationInImage also handles runtime methods since these have relocation info.
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002453 mirror::MethodDexCachePair copy_pair(NativeLocationInImage(orig_pair.object),
2454 orig_pair.index);
2455 mirror::DexCache::SetNativePairPtrSize(copy_methods, i, copy_pair, target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002456 }
2457 }
Vladimir Markof44d36c2017-03-14 14:18:46 +00002458 mirror::FieldDexCacheType* orig_fields = orig_dex_cache->GetResolvedFields();
Vladimir Marko05792b92015-08-03 11:56:49 +01002459 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002460 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002461 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002462 PointerSize::k64);
Vladimir Markof44d36c2017-03-14 14:18:46 +00002463 mirror::FieldDexCacheType* copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002464 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00002465 mirror::FieldDexCachePair orig =
2466 mirror::DexCache::GetNativePairPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002467 mirror::FieldDexCachePair copy = orig;
2468 copy.object = NativeLocationInImage(orig.object);
Vladimir Markof44d36c2017-03-14 14:18:46 +00002469 mirror::DexCache::SetNativePairPtrSize(copy_fields, i, copy, target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002470 }
2471 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01002472 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
2473 if (orig_method_types != nullptr) {
2474 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodTypesOffset(),
2475 NativeLocationInImage(orig_method_types),
2476 PointerSize::k64);
2477 orig_dex_cache->FixupResolvedMethodTypes(NativeCopyLocation(orig_method_types, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002478 fixup_visitor);
Narayan Kamath7fe56582016-10-14 18:49:12 +01002479 }
Orion Hodsonc069a302017-01-18 09:23:12 +00002480 GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
2481 if (orig_call_sites != nullptr) {
2482 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedCallSitesOffset(),
2483 NativeLocationInImage(orig_call_sites),
2484 PointerSize::k64);
2485 orig_dex_cache->FixupResolvedCallSites(NativeCopyLocation(orig_call_sites, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002486 fixup_visitor);
Orion Hodsonc069a302017-01-18 09:23:12 +00002487 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002488
2489 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2490 // compiler pointers in here will make the output non-deterministic.
2491 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002492}
2493
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002494const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2495 DCHECK_LT(type, kOatAddressCount);
2496 // If we are compiling an app image, we need to use the stubs of the boot image.
2497 if (compile_app_image_) {
2498 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002499 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002500 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2501 DCHECK(!image_spaces.empty());
2502 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002503 CHECK(oat_file != nullptr);
2504 const OatHeader& header = oat_file->GetOatHeader();
2505 switch (type) {
2506 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2507 case kOatAddressQuickGenericJNITrampoline:
2508 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2509 case kOatAddressInterpreterToInterpreterBridge:
2510 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2511 case kOatAddressInterpreterToCompiledCodeBridge:
2512 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2513 case kOatAddressJNIDlsymLookup:
2514 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2515 case kOatAddressQuickIMTConflictTrampoline:
2516 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2517 case kOatAddressQuickResolutionTrampoline:
2518 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2519 case kOatAddressQuickToInterpreterBridge:
2520 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2521 default:
2522 UNREACHABLE();
2523 }
2524 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002525 const ImageInfo& primary_image_info = GetImageInfo(0);
2526 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002527}
2528
Jeff Haodcdc85b2015-12-04 14:06:18 -08002529const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2530 const ImageInfo& image_info,
2531 bool* quick_is_interpreted) {
David Sehr709b0702016-10-13 09:12:37 -07002532 DCHECK(!method->IsResolutionMethod()) << method->PrettyMethod();
2533 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << method->PrettyMethod();
2534 DCHECK(!method->IsImtUnimplementedMethod()) << method->PrettyMethod();
2535 DCHECK(method->IsInvokable()) << method->PrettyMethod();
2536 DCHECK(!IsInBootImage(method)) << method->PrettyMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002537
2538 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2539 // trampoline.
2540
2541 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002542 const void* quick_oat_entry_point =
2543 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2544 const uint8_t* quick_code;
2545
2546 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2547 DCHECK(method->IsCopied());
2548 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2549 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2550 } else {
2551 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2552 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2553 }
2554
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002555 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002556 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2557 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002558 // We have code for a non-static or initialized method, just use the code.
2559 } else if (quick_code == nullptr && method->IsNative() &&
2560 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2561 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002562 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002563 } else if (quick_code == nullptr && !method->IsNative()) {
2564 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002565 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002566 *quick_is_interpreted = true;
2567 } else {
2568 CHECK(!method->GetDeclaringClass()->IsInitialized());
2569 // We have code for a static method, but need to go through the resolution stub for class
2570 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002571 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2572 }
2573 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002574 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002575 }
2576 return quick_code;
2577}
2578
Jeff Haodcdc85b2015-12-04 14:06:18 -08002579void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2580 ArtMethod* copy,
2581 const ImageInfo& image_info) {
Mingyao Yange8fcd012017-01-20 10:43:30 -08002582 if (orig->IsAbstract()) {
2583 // Ignore the single-implementation info for abstract method.
2584 // Do this on orig instead of copy, otherwise there is a crash due to methods
2585 // are copied before classes.
2586 // TODO: handle fixup of single-implementation method for abstract method.
2587 orig->SetHasSingleImplementation(false);
2588 orig->SetSingleImplementation(
2589 nullptr, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
2590 }
2591
Vladimir Marko14632852015-08-17 12:07:23 +01002592 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002593
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002594 CopyReference(copy->GetDeclaringClassAddressWithoutBarrier(), orig->GetDeclaringClassUnchecked());
2595
Vladimir Marko07bfbac2017-07-06 14:55:02 +01002596 mirror::MethodDexCacheType* orig_resolved_methods =
2597 orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002598 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002599
Ian Rogers848871b2013-08-05 10:56:33 -07002600 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2601 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002602
Ian Rogers848871b2013-08-05 10:56:33 -07002603 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002604 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002605 if (orig->IsRuntimeMethod()) {
2606 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2607 if (orig_table != nullptr) {
2608 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2609 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2610 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2611 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2612 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2613 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2614 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2615 } else {
2616 bool found_one = false;
Andreas Gampe8228cdf2017-05-30 15:03:54 -07002617 for (size_t i = 0; i < static_cast<size_t>(CalleeSaveType::kLastCalleeSaveType); ++i) {
2618 auto idx = static_cast<CalleeSaveType>(i);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002619 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2620 found_one = true;
2621 break;
2622 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002623 }
David Sehr709b0702016-10-13 09:12:37 -07002624 CHECK(found_one) << "Expected to find callee save method but got " << orig->PrettyMethod();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002625 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002626 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002627 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002628 // We assume all methods have code. If they don't currently then we set them to the use the
2629 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2630 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002631 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002632 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002633 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002634 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002635 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002636 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002637 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002638
Sebastien Hertze1d07812014-05-21 15:44:09 +02002639 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002640 if (orig->IsNative()) {
2641 // The native method's pointer is set to a stub to lookup via dlsym.
2642 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002643 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002644 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002645 }
2646 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002647 }
2648}
2649
Jeff Haodcdc85b2015-12-04 14:06:18 -08002650size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002651 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002652 return std::accumulate(&image_info.bin_slot_sizes_[0],
2653 &image_info.bin_slot_sizes_[up_to],
2654 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002655}
2656
2657ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2658 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002659 static_assert(kBinBits == 3, "wrong number of bin bits");
2660 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002661 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2662
2663 DCHECK_LT(GetBin(), kBinSize);
2664 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2665}
2666
2667ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2668 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2669 DCHECK_EQ(index, GetIndex());
2670}
2671
2672ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2673 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2674}
2675
2676uint32_t ImageWriter::BinSlot::GetIndex() const {
2677 return lockword_ & ~kBinMask;
2678}
2679
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002680ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2681 switch (type) {
2682 case kNativeObjectRelocationTypeArtField:
2683 case kNativeObjectRelocationTypeArtFieldArray:
2684 return kBinArtField;
2685 case kNativeObjectRelocationTypeArtMethodClean:
2686 case kNativeObjectRelocationTypeArtMethodArrayClean:
2687 return kBinArtMethodClean;
2688 case kNativeObjectRelocationTypeArtMethodDirty:
2689 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2690 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002691 case kNativeObjectRelocationTypeDexCacheArray:
2692 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002693 case kNativeObjectRelocationTypeRuntimeMethod:
2694 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002695 case kNativeObjectRelocationTypeIMTable:
2696 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002697 case kNativeObjectRelocationTypeIMTConflictTable:
2698 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002699 }
2700 UNREACHABLE();
2701}
2702
Vladimir Marko944da602016-02-19 12:27:55 +00002703size_t ImageWriter::GetOatIndex(mirror::Object* obj) 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 = oat_index_map_.find(obj);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002708 DCHECK(it != oat_index_map_.end()) << obj;
Mathieu Chartier496577f2016-09-20 15:33:31 -07002709 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002710}
2711
Vladimir Marko944da602016-02-19 12:27:55 +00002712size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002713 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002714 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002715 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002716 auto it = dex_file_oat_index_map_.find(dex_file);
2717 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2718 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002719}
2720
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002721size_t ImageWriter::GetOatIndexForDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
2722 return (dex_cache == nullptr)
2723 ? GetDefaultOatIndex()
2724 : GetOatIndexForDexFile(dex_cache->GetDexFile());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002725}
2726
Vladimir Marko944da602016-02-19 12:27:55 +00002727void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2728 size_t oat_loaded_size,
2729 size_t oat_data_offset,
2730 size_t oat_data_size) {
2731 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2732 for (const ImageInfo& info : image_infos_) {
2733 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2734 }
2735 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002736
Vladimir Marko944da602016-02-19 12:27:55 +00002737 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2738 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2739 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2740 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2741 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002742
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002743 if (compile_app_image_) {
2744 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2745 return;
2746 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002747
2748 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002749 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002750 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002751 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002752 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2753 }
2754}
2755
Vladimir Marko944da602016-02-19 12:27:55 +00002756void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2757 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2758 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2759
2760 if (oat_index == GetDefaultOatIndex()) {
2761 // Primary oat file, read the trampolines.
2762 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2763 oat_header.GetInterpreterToInterpreterBridgeOffset();
2764 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2765 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2766 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2767 oat_header.GetJniDlsymLookupOffset();
2768 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2769 oat_header.GetQuickGenericJniTrampolineOffset();
2770 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2771 oat_header.GetQuickImtConflictTrampolineOffset();
2772 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2773 oat_header.GetQuickResolutionTrampolineOffset();
2774 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2775 oat_header.GetQuickToInterpreterBridgeOffset();
2776 }
2777}
2778
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002779ImageWriter::ImageWriter(
2780 const CompilerDriver& compiler_driver,
2781 uintptr_t image_begin,
2782 bool compile_pic,
2783 bool compile_app_image,
2784 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002785 const std::vector<const char*>& oat_filenames,
Jeff Haoc23b0c02017-07-27 18:19:38 -07002786 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map,
2787 const std::unordered_set<std::string>* dirty_image_objects)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002788 : compiler_driver_(compiler_driver),
2789 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2790 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002791 compile_pic_(compile_pic),
2792 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002793 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002794 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002795 dirty_methods_(0u),
2796 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002797 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002798 oat_filenames_(oat_filenames),
Jeff Haoc23b0c02017-07-27 18:19:38 -07002799 dex_file_oat_index_map_(dex_file_oat_index_map),
2800 dirty_image_objects_(dirty_image_objects) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002801 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002802 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002803 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2804 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002805}
2806
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002807ImageWriter::ImageInfo::ImageInfo()
2808 : intern_table_(new InternTable),
2809 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002810
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002811void ImageWriter::CopyReference(mirror::HeapReference<mirror::Object>* dest,
2812 ObjPtr<mirror::Object> src) {
2813 dest->Assign(GetImageAddress(src.Ptr()));
2814}
2815
2816void ImageWriter::CopyReference(mirror::CompressedReference<mirror::Object>* dest,
2817 ObjPtr<mirror::Object> src) {
2818 dest->Assign(GetImageAddress(src.Ptr()));
2819}
2820
2821void ImageWriter::CopyAndFixupPointer(void** target, void* value) {
2822 void* new_value = value;
2823 if (value != nullptr && !IsInBootImage(value)) {
2824 auto it = native_object_relocations_.find(value);
2825 CHECK(it != native_object_relocations_.end()) << value;
2826 const NativeObjectRelocation& relocation = it->second;
2827 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2828 new_value = reinterpret_cast<void*>(image_info.image_begin_ + relocation.offset);
2829 }
2830 if (target_ptr_size_ == PointerSize::k32) {
2831 *reinterpret_cast<uint32_t*>(target) = PointerToLowMemUInt32(new_value);
2832 } else {
2833 *reinterpret_cast<uint64_t*>(target) = reinterpret_cast<uintptr_t>(new_value);
2834 }
2835}
2836
2837
Brian Carlstrom7940e442013-07-12 13:46:57 -07002838} // namespace art