blob: a8fdecaa4a387a869c1bc77ce0592dc8b3951630 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "image_writer.h"
18
19#include <sys/stat.h>
Mathieu Chartierceb07b32015-12-10 09:33:21 -080020#include <lz4.h>
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -080021#include <lz4hc.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Vladimir Marko20f85592015-03-19 10:07:02 +000024#include <numeric>
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080025#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070026#include <vector>
27
Mathieu Chartierc7853442015-03-27 14:35:38 -070028#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070029#include "art_method-inl.h"
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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "gc/heap.h"
47#include "gc/space/large_object_space.h"
48#include "gc/space/space-inl.h"
Mathieu Chartier4f5e3cb2017-06-12 13:10:01 -070049#include "gc/verification.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "globals.h"
Mathieu Chartier4f5e3cb2017-06-12 13:10:01 -070051#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070052#include "image.h"
Andreas Gampe75a7db62016-09-26 12:04:26 -070053#include "imt_conflict_table.h"
Mathieu Chartier3738e982017-05-12 16:07:28 -070054#include "jni_internal.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070055#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070056#include "lock_word.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070057#include "mirror/array-inl.h"
58#include "mirror/class-inl.h"
Alex Lightd6251582016-10-31 11:12:30 -070059#include "mirror/class_ext.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "mirror/class_loader.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070061#include "mirror/dex_cache.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "mirror/dex_cache-inl.h"
Neil Fuller0e844392016-09-08 13:43:31 +010063#include "mirror/executable.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070064#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080066#include "mirror/object-refvisitor-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070068#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070069#include "oat.h"
70#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070071#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070072#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070073#include "scoped_thread_state_change-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000074#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070076using ::art::mirror::Class;
77using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070078using ::art::mirror::Object;
79using ::art::mirror::ObjectArray;
80using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070081
82namespace art {
83
Igor Murashkinf5b4c502014-11-14 15:01:59 -080084// Separate objects into multiple bins to optimize dirty memory use.
85static constexpr bool kBinObjects = true;
86
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080087// Return true if an object is already in an image space.
88bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080089 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080090 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080091 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080092 return false;
93 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080094 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
95 const uint8_t* image_begin = boot_image_space->Begin();
96 // Real image end including ArtMethods and ArtField sections.
97 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
98 if (image_begin <= obj && obj < image_end) {
99 return true;
100 }
101 }
102 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800103}
104
105bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800106 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800107 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800108 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800109 return false;
110 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800111 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
112 const ImageHeader& image_header = boot_image_space->GetImageHeader();
113 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
114 return true;
115 }
116 }
117 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800118}
119
Mathieu Chartier3738e982017-05-12 16:07:28 -0700120static void ClearDexFileCookieCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700121 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier3738e982017-05-12 16:07:28 -0700122 DCHECK(obj != nullptr);
Andreas Gampedd9d0552015-03-09 12:57:41 -0700123 Class* klass = obj->GetClass();
Mathieu Chartier3738e982017-05-12 16:07:28 -0700124 if (klass == WellKnownClasses::ToClass(WellKnownClasses::dalvik_system_DexFile)) {
125 ArtField* field = jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
126 // Null out the cookie to enable determinism. b/34090128
127 field->SetObject</*kTransactionActive*/false>(obj, nullptr);
128 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700129}
130
Mathieu Chartier3738e982017-05-12 16:07:28 -0700131static void ClearDexFileCookies() REQUIRES_SHARED(Locks::mutator_lock_) {
132 Runtime::Current()->GetHeap()->VisitObjects(ClearDexFileCookieCallback, nullptr);
Andreas Gampedd9d0552015-03-09 12:57:41 -0700133}
134
Vladimir Markof4da6752014-08-01 19:04:18 +0100135bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800136 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800137 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100138 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700139 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100140 PruneNonImageClasses(); // Remove junk
Mathieu Chartier3738e982017-05-12 16:07:28 -0700141 if (compile_app_image_) {
142 // Clear dex file cookies for app images to enable app image determinism. This is required
143 // since the cookie field contains long pointers to DexFiles which are not deterministic.
144 // b/34090128
145 ClearDexFileCookies();
146 } else {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800147 // Avoid for app image since this may increase RAM and image size.
148 ComputeLazyFieldsForImageClasses(); // Add useful information
149 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100150 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100151 heap->CollectGarbage(false); // Remove garbage.
152
Vladimir Markof4da6752014-08-01 19:04:18 +0100153 if (kIsDebugBuild) {
154 ScopedObjectAccess soa(Thread::Current());
155 CheckNonImageClassesRemoved();
156 }
157
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700158 {
159 ScopedObjectAccess soa(Thread::Current());
160 CalculateNewObjectOffsets();
161 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100162
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700163 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
164 // bin size sums being calculated.
165 if (!AllocMemory()) {
166 return false;
167 }
168
Vladimir Markof4da6752014-08-01 19:04:18 +0100169 return true;
170}
171
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700172bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800173 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000174 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800175 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
176 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800177 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800178 if (image_fd != kInvalidFd) {
179 CHECK_EQ(image_filenames.size(), 1u);
180 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800181 CHECK(!oat_filenames.empty());
182 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700183
Vladimir Marko944da602016-02-19 12:27:55 +0000184 {
185 ScopedObjectAccess soa(Thread::Current());
186 for (size_t i = 0; i < oat_filenames.size(); ++i) {
187 CreateHeader(i);
188 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800189 }
190 }
Alex Light53cb16b2014-06-12 11:26:29 -0700191
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700192 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700193 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800194 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700195 Runtime::Current()->GetHeap()->DisableObjectValidation();
196 CopyAndFixupObjects();
197 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700198
Jeff Haodcdc85b2015-12-04 14:06:18 -0800199 for (size_t i = 0; i < image_filenames.size(); ++i) {
200 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000201 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800202 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800203 if (image_fd != kInvalidFd) {
204 if (strlen(image_filename) == 0u) {
205 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800206 // Empty the file in case it already exists.
207 if (image_file != nullptr) {
208 TEMP_FAILURE_RETRY(image_file->SetLength(0));
209 TEMP_FAILURE_RETRY(image_file->Flush());
210 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800211 } else {
212 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
213 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800214 } else {
215 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800216 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800217
Jeff Haodcdc85b2015-12-04 14:06:18 -0800218 if (image_file == nullptr) {
219 LOG(ERROR) << "Failed to open image file " << image_filename;
220 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800221 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800222
223 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800224 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
225 image_file->Erase();
226 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800227 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800228
Jeff Haodcdc85b2015-12-04 14:06:18 -0800229 std::unique_ptr<char[]> compressed_data;
230 // Image data size excludes the bitmap and the header.
231 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
232 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
233 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
234 size_t data_size;
235 const char* image_data_to_write;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800236 const uint64_t compress_start_time = NanoTime();
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000237
Jeff Haodcdc85b2015-12-04 14:06:18 -0800238 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
239 switch (image_storage_mode_) {
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700240 case ImageHeader::kStorageModeLZ4HC: // Fall-through.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800241 case ImageHeader::kStorageModeLZ4: {
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800242 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800243 compressed_data.reset(new char[compressed_max_size]);
David Lin915ec552017-02-23 15:36:06 -0800244 data_size = LZ4_compress_default(
Jeff Haodcdc85b2015-12-04 14:06:18 -0800245 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
246 &compressed_data[0],
David Lin915ec552017-02-23 15:36:06 -0800247 image_data_size,
248 compressed_max_size);
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800249
250 break;
251 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700252 /*
253 * Disabled due to image_test64 flakyness. Both use same decompression. b/27560444
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800254 case ImageHeader::kStorageModeLZ4HC: {
255 // Bound is same as non HC.
256 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
257 compressed_data.reset(new char[compressed_max_size]);
258 data_size = LZ4_compressHC(
259 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
260 &compressed_data[0],
261 image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800262 break;
263 }
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700264 */
Jeff Haodcdc85b2015-12-04 14:06:18 -0800265 case ImageHeader::kStorageModeUncompressed: {
266 data_size = image_data_size;
267 image_data_to_write = image_data;
268 break;
269 }
270 default: {
271 LOG(FATAL) << "Unsupported";
272 UNREACHABLE();
273 }
274 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800275
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800276 if (compressed_data != nullptr) {
277 image_data_to_write = &compressed_data[0];
278 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
279 << PrettyDuration(NanoTime() - compress_start_time);
Mathieu Chartier9894fc82016-03-17 19:19:15 -0700280 if (kIsDebugBuild) {
281 std::unique_ptr<uint8_t[]> temp(new uint8_t[image_data_size]);
282 const size_t decompressed_size = LZ4_decompress_safe(
283 reinterpret_cast<char*>(&compressed_data[0]),
284 reinterpret_cast<char*>(&temp[0]),
285 data_size,
286 image_data_size);
287 CHECK_EQ(decompressed_size, image_data_size);
288 CHECK_EQ(memcmp(image_data, &temp[0], image_data_size), 0) << image_storage_mode_;
289 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800290 }
291
Jeff Haodcdc85b2015-12-04 14:06:18 -0800292 // Write out the image + fields + methods.
293 const bool is_compressed = compressed_data != nullptr;
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800294 if (!image_file->PwriteFully(image_data_to_write, data_size, sizeof(ImageHeader))) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800295 PLOG(ERROR) << "Failed to write image file data " << image_filename;
296 image_file->Erase();
297 return false;
298 }
299
300 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
301 // convenience.
302 const ImageSection& bitmap_section = image_header->GetImageSection(
303 ImageHeader::kSectionImageBitmap);
304 // Align up since data size may be unaligned if the image is compressed.
305 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
306 if (!is_compressed) {
307 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
308 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800309 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
310 bitmap_section.Size(),
311 bitmap_position_in_file)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800312 PLOG(ERROR) << "Failed to write image file " << image_filename;
313 image_file->Erase();
314 return false;
315 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800316
317 int err = image_file->Flush();
318 if (err < 0) {
319 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
320 image_file->Erase();
321 return false;
322 }
323
324 // Write header last in case the compiler gets killed in the middle of image writing.
325 // We do not want to have a corrupted image with a valid header.
326 // The header is uncompressed since it contains whether the image is compressed or not.
327 image_header->data_size_ = data_size;
328 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
329 sizeof(ImageHeader),
330 0)) {
331 PLOG(ERROR) << "Failed to write image file header " << image_filename;
332 image_file->Erase();
333 return false;
334 }
335
Jeff Haodcdc85b2015-12-04 14:06:18 -0800336 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
337 static_cast<size_t>(image_file->GetLength()));
338 if (image_file->FlushCloseOrErase() != 0) {
339 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
340 return false;
341 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800342 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700343 return true;
344}
345
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700346void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700347 DCHECK(object != nullptr);
348 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800349
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800350 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700351 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700352 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700353 DCHECK(IsImageOffsetAssigned(object));
354}
355
Mathieu Chartiere401d142015-04-22 13:56:20 -0700356void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
357 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
358 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
359 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
360}
361
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800362void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700363 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800364 DCHECK_NE(image_objects_offset_begin_, 0u);
365
Vladimir Marko944da602016-02-19 12:27:55 +0000366 size_t oat_index = GetOatIndex(object);
367 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800368 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100369 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800370 DCHECK_ALIGNED(new_offset, kObjectAlignment);
371
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700372 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800373 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700374}
375
Ian Rogersef7d42f2014-01-06 12:55:46 -0800376bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800377 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700378 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700379 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700380}
381
Ian Rogersef7d42f2014-01-06 12:55:46 -0800382size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700383 DCHECK(object != nullptr);
384 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700385 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700386 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000387 size_t oat_index = GetOatIndex(object);
388 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800389 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700390 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700391}
392
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800393void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
394 DCHECK(object != nullptr);
395 DCHECK(!IsImageOffsetAssigned(object));
396 DCHECK(!IsImageBinSlotAssigned(object));
397
398 // Before we stomp over the lock word, save the hash code for later.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800399 LockWord lw(object->GetLockWord(false));
400 switch (lw.GetState()) {
401 case LockWord::kFatLocked: {
402 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
403 break;
404 }
405 case LockWord::kThinLocked: {
406 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
407 break;
408 }
409 case LockWord::kUnlocked:
410 // No hash, don't need to save it.
411 break;
412 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700413 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
414 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800415 break;
416 default:
417 LOG(FATAL) << "Unreachable.";
418 UNREACHABLE();
419 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700420 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700421 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800422 DCHECK(IsImageBinSlotAssigned(object));
423}
424
Vladimir Marko20f85592015-03-19 10:07:02 +0000425void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000426 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000427 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
428 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800429 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000430 auto it = dex_file_oat_index_map_.find(dex_file);
431 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800432 ImageInfo& image_info = GetImageInfo(it->second);
433 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
434 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
435 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
436 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000437
Vladimir Marko20f85592015-03-19 10:07:02 +0000438 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700439 Thread* const self = Thread::Current();
Andreas Gampecc1b5352016-12-01 16:58:38 -0800440 ReaderMutexLock mu(self, *Locks::dex_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800441 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700442 ObjPtr<mirror::DexCache> dex_cache =
443 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
444 if (dex_cache == nullptr || IsInBootImage(dex_cache.Ptr())) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700445 continue;
446 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000447 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartier0b490842016-05-25 15:05:59 -0700448 CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
449 << "Dex cache should have been pruned " << dex_file->GetLocation()
450 << "; possibly in class path";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700451 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000452 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000453 size_t oat_index = GetOatIndexForDexCache(dex_cache);
454 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800455 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100456 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800457 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
458 start + layout.TypesOffset(),
459 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100460 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800461 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
462 start + layout.MethodsOffset(),
463 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100464 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800465 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
466 start + layout.FieldsOffset(),
467 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100468 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800469 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Narayan Kamath7fe56582016-10-14 18:49:12 +0100470
471 if (dex_cache->GetResolvedMethodTypes() != nullptr) {
472 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethodTypes(),
473 start + layout.MethodTypesOffset(),
474 dex_cache);
475 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000476 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000477}
478
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700479void ImageWriter::AddDexCacheArrayRelocation(void* array,
480 size_t offset,
481 ObjPtr<mirror::DexCache> dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100482 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800483 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000484 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800485 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000486 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100487 }
488}
489
Mathieu Chartiere401d142015-04-22 13:56:20 -0700490void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
491 DCHECK(arr != nullptr);
492 if (kIsDebugBuild) {
493 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800494 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700495 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800496 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800497 CHECK(klass == nullptr || KeepClass(klass))
David Sehr709b0702016-10-13 09:12:37 -0700498 << Class::PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700499 }
500 }
501 }
502 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
503 // ArtMethods.
504 pointer_arrays_.emplace(arr, kBinArtMethodClean);
505}
506
Mathieu Chartier496577f2016-09-20 15:33:31 -0700507void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800508 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800509 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800510
511 // The magic happens here. We segregate objects into different bins based
512 // on how likely they are to get dirty at runtime.
513 //
514 // Likely-to-dirty objects get packed together into the same bin so that
515 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
516 // maximized.
517 //
518 // This means more pages will stay either clean or shared dirty (with zygote) and
519 // the app will use less of its own (private) memory.
520 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000521 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800522
523 if (kBinObjects) {
524 //
525 // Changing the bin of an object is purely a memory-use tuning.
526 // It has no change on runtime correctness.
527 //
528 // Memory analysis has determined that the following types of objects get dirtied
529 // the most:
530 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000531 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
532 // a fixed layout which helps improve generated code (using PC-relative addressing),
533 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
534 // Since these arrays are huge, most pages do not overlap other objects and it's not
535 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100536 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800537 // * Class'es which are verified [their clinit runs only at runtime]
538 // - classes in general [because their static fields get overwritten]
539 // - initialized classes with all-final statics are unlikely to be ever dirty,
540 // so bin them separately
541 // * Art Methods that are:
542 // - native [their native entry point is not looked up until runtime]
543 // - have declaring classes that aren't initialized
544 // [their interpreter/quick entry points are trampolines until the class
545 // becomes initialized]
546 //
547 // We also assume the following objects get dirtied either never or extremely rarely:
548 // * Strings (they are immutable)
549 // * Art methods that aren't native and have initialized declared classes
550 //
551 // We assume that "regular" bin objects are highly unlikely to become dirtied,
552 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
553 //
554 if (object->IsClass()) {
555 bin = kBinClassVerified;
556 mirror::Class* klass = object->AsClass();
557
Mathieu Chartiere401d142015-04-22 13:56:20 -0700558 // Add non-embedded vtable to the pointer array table if there is one.
559 auto* vtable = klass->GetVTable();
560 if (vtable != nullptr) {
561 AddMethodPointerArray(vtable);
562 }
563 auto* iftable = klass->GetIfTable();
564 if (iftable != nullptr) {
565 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
566 if (iftable->GetMethodArrayCount(i) > 0) {
567 AddMethodPointerArray(iftable->GetMethodArray(i));
568 }
569 }
570 }
571
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800572 if (klass->GetStatus() == Class::kStatusInitialized) {
573 bin = kBinClassInitialized;
574
575 // If the class's static fields are all final, put it into a separate bin
576 // since it's very likely it will stay clean.
577 uint32_t num_static_fields = klass->NumStaticFields();
578 if (num_static_fields == 0) {
579 bin = kBinClassInitializedFinalStatics;
580 } else {
581 // Maybe all the statics are final?
582 bool all_final = true;
583 for (uint32_t i = 0; i < num_static_fields; ++i) {
584 ArtField* field = klass->GetStaticField(i);
585 if (!field->IsFinal()) {
586 all_final = false;
587 break;
588 }
589 }
590
591 if (all_final) {
592 bin = kBinClassInitializedFinalStatics;
593 }
594 }
595 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800596 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
597 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartier2ba04ea2016-04-08 19:01:05 -0700598 } else if (object->GetClass<kVerifyNone>() ==
599 Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
600 // Instance of java lang object, probably a lock object. This means it will be dirty when we
601 // synchronize on it.
602 bin = kBinMiscDirty;
603 } else if (object->IsDexCache()) {
604 // Dex file field becomes dirty when the image is loaded.
605 bin = kBinMiscDirty;
606 }
607 // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800608 }
609
Mathieu Chartier496577f2016-09-20 15:33:31 -0700610 // Assign the oat index too.
611 DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
612 oat_index_map_.emplace(object, oat_index);
613
Vladimir Marko944da602016-02-19 12:27:55 +0000614 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800615
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800616 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800617 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
618 // Move the current bin size up to accommodate the object we just assigned a bin slot.
619 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800620
621 BinSlot new_bin_slot(bin, current_offset);
622 SetImageBinSlot(object, new_bin_slot);
623
Jeff Haodcdc85b2015-12-04 14:06:18 -0800624 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800625
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800626 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800627 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800628}
629
Mathieu Chartiere401d142015-04-22 13:56:20 -0700630bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
631 if (m->IsNative()) {
632 return true;
633 }
634 mirror::Class* declaring_class = m->GetDeclaringClass();
635 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
636 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
637}
638
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800639bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
640 DCHECK(object != nullptr);
641
642 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
643 // If it's in some other state, then we haven't yet assigned an image bin slot.
644 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
645 return false;
646 } else if (kIsDebugBuild) {
647 LockWord lock_word = object->GetLockWord(false);
648 size_t offset = lock_word.ForwardingAddress();
649 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000650 size_t oat_index = GetOatIndex(object);
651 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800652 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800653 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800654 }
655 return true;
656}
657
658ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
659 DCHECK(object != nullptr);
660 DCHECK(IsImageBinSlotAssigned(object));
661
662 LockWord lock_word = object->GetLockWord(false);
663 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
664 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
665
666 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000667 size_t oat_index = GetOatIndex(object);
668 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800669 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800670
671 return bin_slot;
672}
673
Brian Carlstrom7940e442013-07-12 13:46:57 -0700674bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000675 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800676 ImageSection unused_sections[ImageHeader::kSectionCount];
677 const size_t length = RoundUp(
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700678 image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800679
Jeff Haodcdc85b2015-12-04 14:06:18 -0800680 std::string error_msg;
681 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
682 nullptr,
683 length,
684 PROT_READ | PROT_WRITE,
685 false,
686 false,
687 &error_msg));
688 if (UNLIKELY(image_info.image_.get() == nullptr)) {
689 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
690 return false;
691 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700692
Jeff Haodcdc85b2015-12-04 14:06:18 -0800693 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
694 CHECK_LE(image_info.image_end_, length);
695 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
696 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
697 if (image_info.image_bitmap_.get() == nullptr) {
698 LOG(ERROR) << "Failed to allocate memory for image bitmap";
699 return false;
700 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700701 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700702 return true;
703}
704
Vladimir Markoad06b982016-11-17 16:38:59 +0000705class ImageWriter::ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700706 public:
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700707 bool operator()(ObjPtr<Class> c) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700708 StackHandleScope<1> hs(Thread::Current());
709 mirror::Class::ComputeName(hs.NewHandle(c));
710 return true;
711 }
712};
713
Brian Carlstrom7940e442013-07-12 13:46:57 -0700714void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700715 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700716 ComputeLazyFieldsForClassesVisitor visitor;
717 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700718}
719
Vladimir Markof25cc732017-03-16 16:18:15 +0000720static bool IsBootClassLoaderClass(ObjPtr<mirror::Class> klass)
721 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800722 return klass->GetClassLoader() == nullptr;
723}
724
725bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
726 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
727}
728
Vladimir Markof25cc732017-03-16 16:18:15 +0000729bool ImageWriter::PruneAppImageClass(ObjPtr<mirror::Class> klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800730 bool early_exit = false;
731 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800732 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800733}
734
Mathieu Chartier901e0702016-02-19 13:42:48 -0800735bool ImageWriter::PruneAppImageClassInternal(
Vladimir Markof25cc732017-03-16 16:18:15 +0000736 ObjPtr<mirror::Class> klass,
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800737 bool* early_exit,
738 std::unordered_set<mirror::Class*>* visited) {
739 DCHECK(early_exit != nullptr);
740 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800741 DCHECK(compile_app_image_);
Vladimir Markof25cc732017-03-16 16:18:15 +0000742 if (klass == nullptr || IsInBootImage(klass.Ptr())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700743 return false;
744 }
Vladimir Markof25cc732017-03-16 16:18:15 +0000745 auto found = prune_class_memo_.find(klass.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800746 if (found != prune_class_memo_.end()) {
747 // Already computed, return the found value.
748 return found->second;
749 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800750 // Circular dependencies, return false but do not store the result in the memoization table.
Vladimir Markof25cc732017-03-16 16:18:15 +0000751 if (visited->find(klass.Ptr()) != visited->end()) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800752 *early_exit = true;
753 return false;
754 }
Vladimir Markof25cc732017-03-16 16:18:15 +0000755 visited->emplace(klass.Ptr());
Mathieu Chartier901e0702016-02-19 13:42:48 -0800756 bool result = IsBootClassLoaderClass(klass);
757 std::string temp;
758 // Prune if not an image class, this handles any broken sets of image classes such as having a
759 // class in the set but not it's superclass.
760 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800761 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800762 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
763 // app image.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000764 if (klass->IsErroneous()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800765 result = true;
766 } else {
Alex Lightd6251582016-10-31 11:12:30 -0700767 ObjPtr<mirror::ClassExt> ext(klass->GetExtData());
768 CHECK(ext.IsNull() || ext->GetVerifyError() == nullptr) << klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800769 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800770 if (!result) {
771 // Check interfaces since these wont be visited through VisitReferences.)
772 mirror::IfTable* if_table = klass->GetIfTable();
773 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800774 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
775 &my_early_exit,
776 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800777 }
778 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800779 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800780 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
781 &my_early_exit,
782 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800783 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800784 // Check static fields and their classes.
Vladimir Marko72ab6842017-01-20 19:32:50 +0000785 if (klass->IsResolved() && klass->NumReferenceStaticFields() != 0) {
786 size_t num_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800787 // Presumably GC can happen when we are cross compiling, it should not cause performance
788 // problems to do pointer size logic.
789 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
790 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
791 for (size_t i = 0u; i < num_static_fields; ++i) {
792 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
793 if (ref != nullptr) {
794 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800795 result = result || PruneAppImageClassInternal(ref->AsClass(),
796 &my_early_exit,
797 visited);
798 } else {
799 result = result || PruneAppImageClassInternal(ref->GetClass(),
800 &my_early_exit,
801 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800802 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800803 }
804 field_offset = MemberOffset(field_offset.Uint32Value() +
805 sizeof(mirror::HeapReference<mirror::Object>));
806 }
807 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800808 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
809 &my_early_exit,
810 visited);
Mathieu Chartierc27bc402016-08-05 16:09:09 -0700811 // Remove the class if the dex file is not in the set of dex files. This happens for classes that
812 // are from uses library if there is no profile. b/30688277
813 mirror::DexCache* dex_cache = klass->GetDexCache();
814 if (dex_cache != nullptr) {
815 result = result ||
816 dex_file_oat_index_map_.find(dex_cache->GetDexFile()) == dex_file_oat_index_map_.end();
817 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800818 // Erase the element we stored earlier since we are exiting the function.
Vladimir Markof25cc732017-03-16 16:18:15 +0000819 auto it = visited->find(klass.Ptr());
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800820 DCHECK(it != visited->end());
821 visited->erase(it);
822 // Only store result if it is true or none of the calls early exited due to circular
823 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
824 // a child call and we can remember the result.
825 if (result == true || !my_early_exit || visited->empty()) {
Vladimir Markof25cc732017-03-16 16:18:15 +0000826 prune_class_memo_[klass.Ptr()] = result;
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800827 }
828 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800829 return result;
830}
831
Vladimir Markof25cc732017-03-16 16:18:15 +0000832bool ImageWriter::KeepClass(ObjPtr<mirror::Class> klass) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800833 if (klass == nullptr) {
834 return false;
835 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800836 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
837 // Already in boot image, return true.
838 return true;
839 }
840 std::string temp;
841 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
842 return false;
843 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800844 if (compile_app_image_) {
845 // For app images, we need to prune boot loader classes that are not in the boot image since
846 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800847 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800848 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800849 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800850 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700851}
852
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000853class ImageWriter::PruneClassesVisitor : public ClassVisitor {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700854 public:
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000855 PruneClassesVisitor(ImageWriter* image_writer, ObjPtr<mirror::ClassLoader> class_loader)
856 : image_writer_(image_writer),
857 class_loader_(class_loader),
858 classes_to_prune_(),
859 defined_class_count_(0u) { }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700860
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000861 bool operator()(ObjPtr<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier28357fa2016-10-18 16:27:40 -0700862 if (!image_writer_->KeepClass(klass.Ptr())) {
863 classes_to_prune_.insert(klass.Ptr());
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000864 if (klass->GetClassLoader() == class_loader_) {
865 ++defined_class_count_;
866 }
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700867 }
868 return true;
869 }
870
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000871 size_t Prune() REQUIRES_SHARED(Locks::mutator_lock_) {
872 ClassTable* class_table =
873 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader_);
874 for (mirror::Class* klass : classes_to_prune_) {
875 std::string storage;
876 const char* descriptor = klass->GetDescriptor(&storage);
877 bool result = class_table->Remove(descriptor);
878 DCHECK(result);
879 DCHECK(!class_table->Remove(descriptor)) << descriptor;
880 }
881 return defined_class_count_;
882 }
883
884 private:
Vladimir Markocb5ab352016-11-30 15:31:13 +0000885 ImageWriter* const image_writer_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000886 const ObjPtr<mirror::ClassLoader> class_loader_;
887 std::unordered_set<mirror::Class*> classes_to_prune_;
888 size_t defined_class_count_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700889};
890
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000891class ImageWriter::PruneClassLoaderClassesVisitor : public ClassLoaderVisitor {
892 public:
893 explicit PruneClassLoaderClassesVisitor(ImageWriter* image_writer)
894 : image_writer_(image_writer), removed_class_count_(0) {}
895
896 virtual void Visit(ObjPtr<mirror::ClassLoader> class_loader) OVERRIDE
897 REQUIRES_SHARED(Locks::mutator_lock_) {
898 PruneClassesVisitor classes_visitor(image_writer_, class_loader);
899 ClassTable* class_table =
900 Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader);
901 class_table->Visit(classes_visitor);
902 removed_class_count_ += classes_visitor.Prune();
Vladimir Markof25cc732017-03-16 16:18:15 +0000903
904 // Record app image class loader. The fake boot class loader should not get registered
905 // and we should end up with only one class loader for an app and none for boot image.
906 if (class_loader != nullptr && class_table != nullptr) {
907 DCHECK(class_loader_ == nullptr);
908 class_loader_ = class_loader;
909 }
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000910 }
911
912 size_t GetRemovedClassCount() const {
913 return removed_class_count_;
914 }
915
Vladimir Markof25cc732017-03-16 16:18:15 +0000916 ObjPtr<mirror::ClassLoader> GetClassLoader() const REQUIRES_SHARED(Locks::mutator_lock_) {
917 return class_loader_;
918 }
919
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000920 private:
921 ImageWriter* const image_writer_;
922 size_t removed_class_count_;
Vladimir Markof25cc732017-03-16 16:18:15 +0000923 ObjPtr<mirror::ClassLoader> class_loader_;
Vladimir Markoc5798bf2016-12-09 10:20:54 +0000924};
925
926void ImageWriter::VisitClassLoaders(ClassLoaderVisitor* visitor) {
927 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
928 visitor->Visit(nullptr); // Visit boot class loader.
929 Runtime::Current()->GetClassLinker()->VisitClassLoaders(visitor);
930}
931
Vladimir Markof25cc732017-03-16 16:18:15 +0000932void ImageWriter::PruneAndPreloadDexCache(ObjPtr<mirror::DexCache> dex_cache,
933 ObjPtr<mirror::ClassLoader> class_loader) {
934 // To ensure deterministic contents of the hash-based arrays, each slot shall contain
935 // the candidate with the lowest index. As we're processing entries in increasing index
936 // order, this means trying to look up the entry for the current index if the slot is
937 // empty or if it contains a higher index.
938
939 Runtime* runtime = Runtime::Current();
940 ClassLinker* class_linker = runtime->GetClassLinker();
941 ArtMethod* resolution_method = runtime->GetResolutionMethod();
942 const DexFile& dex_file = *dex_cache->GetDexFile();
943 // Prune methods.
944 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
945 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
946 ArtMethod* method =
947 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
948 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
949 mirror::Class* declaring_class = method->GetDeclaringClass();
950 // Copied methods may be held live by a class which was not an image class but have a
951 // declaring class which is an image class. Set it to the resolution method to be safe and
952 // prevent dangling pointers.
953 if (method->IsCopied() || !KeepClass(declaring_class)) {
954 mirror::DexCache::SetElementPtrSize(resolved_methods,
955 i,
956 resolution_method,
957 target_ptr_size_);
958 } else if (kIsDebugBuild) {
959 // Check that the class is still in the classes table.
960 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
961 CHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
962 << Class::PrettyClass(declaring_class) << " not in class linker table";
963 }
964 }
965 // Prune fields and make the contents of the field array deterministic.
966 mirror::FieldDexCacheType* resolved_fields = dex_cache->GetResolvedFields();
967 dex::TypeIndex last_class_idx; // Initialized to invalid index.
968 ObjPtr<mirror::Class> last_class = nullptr;
969 for (size_t i = 0, end = dex_file.NumFieldIds(); i < end; ++i) {
970 uint32_t slot_idx = dex_cache->FieldSlotIndex(i);
971 auto pair = mirror::DexCache::GetNativePairPtrSize(resolved_fields, slot_idx, target_ptr_size_);
972 uint32_t stored_index = pair.index;
973 ArtField* field = pair.object;
974 if (field != nullptr && i > stored_index) {
975 continue; // Already checked.
976 }
977 // Check if the referenced class is in the image. Note that we want to check the referenced
978 // class rather than the declaring class to preserve the semantics, i.e. using a FieldId
979 // results in resolving the referenced class and that can for example throw OOME.
980 const DexFile::FieldId& field_id = dex_file.GetFieldId(i);
981 if (field_id.class_idx_ != last_class_idx) {
982 last_class_idx = field_id.class_idx_;
983 last_class = class_linker->LookupResolvedType(
984 dex_file, last_class_idx, dex_cache, class_loader);
985 if (last_class != nullptr && !KeepClass(last_class)) {
986 last_class = nullptr;
987 }
988 }
989 if (field == nullptr || i < stored_index) {
990 if (last_class != nullptr) {
991 const char* name = dex_file.StringDataByIdx(field_id.name_idx_);
992 const char* type = dex_file.StringByTypeIdx(field_id.type_idx_);
993 field = mirror::Class::FindField(Thread::Current(), last_class, name, type);
994 if (field != nullptr) {
995 // If the referenced class is in the image, the defining class must also be there.
996 DCHECK(KeepClass(field->GetDeclaringClass()));
997 dex_cache->SetResolvedField(i, field, target_ptr_size_);
998 }
999 }
1000 } else {
1001 DCHECK_EQ(i, stored_index);
1002 if (last_class == nullptr) {
1003 dex_cache->ClearResolvedField(stored_index, target_ptr_size_);
1004 }
1005 }
1006 }
1007 // Prune types and make the contents of the type array deterministic.
1008 // This is done after fields and methods as their lookup can touch the types array.
1009 for (size_t i = 0, end = dex_cache->GetDexFile()->NumTypeIds(); i < end; ++i) {
1010 dex::TypeIndex type_idx(i);
1011 uint32_t slot_idx = dex_cache->TypeSlotIndex(type_idx);
1012 mirror::TypeDexCachePair pair =
1013 dex_cache->GetResolvedTypes()[slot_idx].load(std::memory_order_relaxed);
1014 uint32_t stored_index = pair.index;
1015 ObjPtr<mirror::Class> klass = pair.object.Read();
1016 if (klass == nullptr || i < stored_index) {
1017 klass = class_linker->LookupResolvedType(dex_file, type_idx, dex_cache, class_loader);
1018 if (klass != nullptr) {
1019 DCHECK_EQ(dex_cache->GetResolvedType(type_idx), klass);
1020 stored_index = i; // For correct clearing below if not keeping the `klass`.
1021 }
1022 } else if (i == stored_index && !KeepClass(klass)) {
1023 dex_cache->ClearResolvedType(dex::TypeIndex(stored_index));
1024 }
1025 }
1026 // Strings do not need pruning, but the contents of the string array must be deterministic.
1027 for (size_t i = 0, end = dex_cache->GetDexFile()->NumStringIds(); i < end; ++i) {
1028 dex::StringIndex string_idx(i);
1029 uint32_t slot_idx = dex_cache->StringSlotIndex(string_idx);
1030 mirror::StringDexCachePair pair =
1031 dex_cache->GetStrings()[slot_idx].load(std::memory_order_relaxed);
1032 uint32_t stored_index = pair.index;
1033 ObjPtr<mirror::String> string = pair.object.Read();
1034 if (string == nullptr || i < stored_index) {
1035 string = class_linker->LookupString(dex_file, string_idx, dex_cache);
1036 DCHECK(string == nullptr || dex_cache->GetResolvedString(string_idx) == string);
1037 }
1038 }
1039}
1040
Brian Carlstrom7940e442013-07-12 13:46:57 -07001041void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001042 Runtime* runtime = Runtime::Current();
1043 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001044 Thread* self = Thread::Current();
Vladimir Markof25cc732017-03-16 16:18:15 +00001045 ScopedAssertNoThreadSuspension sa(__FUNCTION__);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001046
Mathieu Chartier696632e2016-06-03 17:47:32 -07001047 // Clear class table strong roots so that dex caches can get pruned. We require pruning the class
1048 // path dex caches.
1049 class_linker->ClearClassTableStrongRoots();
1050
Brian Carlstrom7940e442013-07-12 13:46:57 -07001051 // Remove the undesired classes from the class roots.
Vladimir Markof25cc732017-03-16 16:18:15 +00001052 ObjPtr<mirror::ClassLoader> class_loader;
Vladimir Markoc5798bf2016-12-09 10:20:54 +00001053 {
1054 PruneClassLoaderClassesVisitor class_loader_visitor(this);
1055 VisitClassLoaders(&class_loader_visitor);
1056 VLOG(compiler) << "Pruned " << class_loader_visitor.GetRemovedClassCount() << " classes";
Vladimir Markof25cc732017-03-16 16:18:15 +00001057 class_loader = class_loader_visitor.GetClassLoader();
1058 DCHECK_EQ(class_loader != nullptr, compile_app_image_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001059 }
1060
1061 // Clear references to removed classes from the DexCaches.
Vladimir Markof25cc732017-03-16 16:18:15 +00001062 std::vector<ObjPtr<mirror::DexCache>> dex_caches;
1063 {
1064 ReaderMutexLock mu2(self, *Locks::dex_lock_);
1065 dex_caches.reserve(class_linker->GetDexCachesData().size());
1066 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1067 if (self->IsJWeakCleared(data.weak_root)) {
1068 continue;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001069 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001070 dex_caches.push_back(self->DecodeJObject(data.weak_root)->AsDexCache());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001071 }
Vladimir Markof25cc732017-03-16 16:18:15 +00001072 }
1073 for (ObjPtr<mirror::DexCache> dex_cache : dex_caches) {
1074 PruneAndPreloadDexCache(dex_cache, class_loader);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001075 }
Andreas Gampe8ac75952015-06-02 21:01:45 -07001076
1077 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
1078 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001079
1080 // Clear to save RAM.
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00001081 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001082}
1083
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001084void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001085 if (compiler_driver_.GetImageClasses() != nullptr) {
1086 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001087 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001088 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001089}
1090
1091void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
1092 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001093 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001094 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001095 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001096 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -07001097 std::string temp;
Mathieu Chartier4f5e3cb2017-06-12 13:10:01 -07001098 CHECK(image_writer->KeepClass(klass))
1099 << Runtime::Current()->GetHeap()->GetVerification()->FirstPathFromRootSet(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001100 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001101 }
1102}
1103
1104void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001105 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001106 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -07001107 for (const std::string& image_class : *image_classes) {
1108 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001109 }
1110}
1111
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001112mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
1113 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +00001114 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001115 ObjPtr<mirror::String> const found = image_info.intern_table_->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001116 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
1117 << string->ToModifiedUtf8();
1118 if (found != nullptr) {
Mathieu Chartier9e868092016-10-31 14:58:04 -07001119 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001120 }
1121 }
1122 if (compile_app_image_) {
1123 Runtime* const runtime = Runtime::Current();
Mathieu Chartier9e868092016-10-31 14:58:04 -07001124 ObjPtr<mirror::String> found = runtime->GetInternTable()->LookupStrong(self, string);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001125 // If we found it in the runtime intern table it could either be in the boot image or interned
1126 // during app image compilation. If it was in the boot image return that, otherwise return null
1127 // since it belongs to another image space.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001128 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found.Ptr())) {
1129 return found.Ptr();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001130 }
1131 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
1132 << string->ToModifiedUtf8();
1133 }
1134 return nullptr;
1135}
1136
Brian Carlstrom7940e442013-07-12 13:46:57 -07001137
Vladimir Marko944da602016-02-19 12:27:55 +00001138ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001139 Runtime* runtime = Runtime::Current();
1140 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001141 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001142 StackHandleScope<3> hs(self);
1143 Handle<Class> object_array_class(hs.NewHandle(
1144 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001145
Jeff Haodcdc85b2015-12-04 14:06:18 -08001146 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +00001147 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001148 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +00001149 size_t image_oat_index = pair.second;
1150 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001151 image_dex_files.insert(image_dex_file);
1152 }
1153 }
1154
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001155 // build an Object[] of all the DexCaches used in the source_space_.
1156 // Since we can't hold the dex lock when allocating the dex_caches
1157 // ObjectArray, we lock the dex lock twice, first to get the number
1158 // of dex caches first and then lock it again to copy the dex
1159 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001160 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001161 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001162 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001163 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001164 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001165 ObjPtr<mirror::DexCache> dex_cache =
1166 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001167 if (dex_cache == nullptr) {
1168 continue;
1169 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001170 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001171 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001172 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1173 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001174 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001175 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001176 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001177 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Andreas Gampefa4333d2017-02-14 11:10:34 -08001178 CHECK(dex_caches != nullptr) << "Failed to allocate a dex cache array.";
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001179 {
Andreas Gampecc1b5352016-12-01 16:58:38 -08001180 ReaderMutexLock mu(self, *Locks::dex_lock_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001181 size_t non_image_dex_caches = 0;
1182 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001183 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001184 ObjPtr<mirror::DexCache> dex_cache =
1185 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001186 if (dex_cache == nullptr) {
1187 continue;
1188 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001189 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001190 if (!IsInBootImage(dex_cache.Ptr())) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001191 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1192 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001193 }
1194 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1195 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001196 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001197 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001198 ObjPtr<mirror::DexCache> dex_cache =
1199 ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
Brian Carlstrom0c050a12016-04-29 10:28:34 -07001200 if (dex_cache == nullptr) {
1201 continue;
1202 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001203 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc4f39252016-10-05 18:32:08 -07001204 if (!IsInBootImage(dex_cache.Ptr()) &&
1205 image_dex_files.find(dex_file) != image_dex_files.end()) {
1206 dex_caches->Set<false>(i, dex_cache.Ptr());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001207 ++i;
1208 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001209 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001210 }
1211
1212 // build an Object[] of the roots needed to restore the runtime
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001213 int32_t image_roots_size = ImageHeader::NumberOfImageRoots(compile_app_image_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001214 auto image_roots(hs.NewHandle(
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001215 ObjectArray<Object>::Alloc(self, object_array_class.Get(), image_roots_size)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001216 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001217 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001218 // image_roots[ImageHeader::kClassLoader] will be set later for app image.
1219 static_assert(ImageHeader::kClassLoader + 1u == ImageHeader::kImageRootsMax,
1220 "Class loader should be the last image root.");
1221 for (int32_t i = 0; i < ImageHeader::kImageRootsMax - 1; ++i) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001222 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001223 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001224 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001225}
1226
Mathieu Chartier496577f2016-09-20 15:33:31 -07001227mirror::Object* ImageWriter::TryAssignBinSlot(WorkStack& work_stack,
1228 mirror::Object* obj,
1229 size_t oat_index) {
1230 if (obj == nullptr || IsInBootImage(obj)) {
1231 // Object is null or already in the image, there is no work to do.
1232 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001233 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001234 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier496577f2016-09-20 15:33:31 -07001235 // We want to intern all strings but also assign offsets for the source string. Since the
1236 // pruning phase has already happened, if we intern a string to one in the image we still
1237 // end up copying an unreachable string.
1238 if (obj->IsString()) {
1239 // Need to check if the string is already interned in another image info so that we don't have
1240 // the intern tables of two different images contain the same string.
1241 mirror::String* interned = FindInternedString(obj->AsString());
1242 if (interned == nullptr) {
1243 // Not in another image space, insert to our table.
Mathieu Chartier9e868092016-10-31 14:58:04 -07001244 interned =
1245 GetImageInfo(oat_index).intern_table_->InternStrongImageString(obj->AsString()).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001246 DCHECK_EQ(interned, obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001247 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001248 } else if (obj->IsDexCache()) {
1249 oat_index = GetOatIndexForDexCache(obj->AsDexCache());
1250 } else if (obj->IsClass()) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001251 // Visit and assign offsets for fields and field arrays.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001252 mirror::Class* as_klass = obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001253 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Vladimir Marko72ab6842017-01-20 19:32:50 +00001254 DCHECK(!as_klass->IsErroneous()) << as_klass->GetStatus();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001255 if (compile_app_image_) {
1256 // Extra sanity, no boot loader classes should be left!
Vladimir Marko2c8c6b62016-12-01 17:42:00 +00001257 CHECK(!IsBootClassLoaderClass(as_klass)) << as_klass->PrettyClass();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001258 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001259 LengthPrefixedArray<ArtField>* fields[] = {
1260 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1261 };
Mathieu Chartier496577f2016-09-20 15:33:31 -07001262 // Overwrite the oat index value since the class' dex cache is more accurate of where it
1263 // belongs.
1264 oat_index = GetOatIndexForDexCache(dex_cache);
Vladimir Marko944da602016-02-19 12:27:55 +00001265 ImageInfo& image_info = GetImageInfo(oat_index);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001266 if (!compile_app_image_) {
1267 // Note: Avoid locking to prevent lock order violations from root visiting;
1268 // image_info.class_table_ is only accessed from the image writer.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001269 image_info.class_table_->InsertWithoutLocks(as_klass);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001270 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001271 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1272 // Total array length including header.
1273 if (cur_fields != nullptr) {
1274 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1275 // Forward the entire array at once.
1276 auto it = native_object_relocations_.find(cur_fields);
1277 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1278 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001279 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001280 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001281 native_object_relocations_.emplace(
1282 cur_fields,
1283 NativeObjectRelocation {
1284 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1285 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001286 offset += header_size;
1287 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001288 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001289 // Need to forward arrays separate of fields.
1290 ArtField* field = &cur_fields->At(i);
1291 auto it2 = native_object_relocations_.find(field);
1292 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
David Sehr709b0702016-10-13 09:12:37 -07001293 << " already assigned " << field->PrettyField() << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001294 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001295 native_object_relocations_.emplace(
1296 field,
1297 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001298 offset += sizeof(ArtField);
1299 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001300 }
1301 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001302 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001303 size_t num_methods = as_klass->NumMethods();
1304 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001305 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001306 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1307 if (WillMethodBeDirty(&m)) {
1308 any_dirty = true;
1309 break;
1310 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001311 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001312 NativeObjectRelocationType type = any_dirty
1313 ? kNativeObjectRelocationTypeArtMethodDirty
1314 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001315 Bin bin_type = BinTypeForNativeRelocationType(type);
1316 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001317 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1318 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001319 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1320 method_size,
1321 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001322 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001323 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001324 CHECK(it == native_object_relocations_.end())
1325 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001326 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001327 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001328 native_object_relocations_.emplace(array,
1329 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001330 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001331 offset,
1332 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1333 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001334 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001335 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001336 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001337 }
Alex Lighte64300b2015-12-15 15:02:47 -08001338 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartier97bad1b2016-05-16 14:58:01 -07001339 }
1340 // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1341 // live.
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001342 if (as_klass->ShouldHaveImt()) {
1343 ImTable* imt = as_klass->GetImt(target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001344 if (TryAssignImTableOffset(imt, oat_index)) {
1345 // Since imt's can be shared only do this the first time to not double count imt method
1346 // fixups.
1347 for (size_t i = 0; i < ImTable::kSize; ++i) {
1348 ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
1349 DCHECK(imt_method != nullptr);
1350 if (imt_method->IsRuntimeMethod() &&
1351 !IsInBootImage(imt_method) &&
1352 !NativeRelocationAssigned(imt_method)) {
1353 AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
1354 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001355 }
1356 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001357 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001358 } else if (obj->IsClassLoader()) {
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001359 // Register the class loader if it has a class table.
1360 // The fake boot class loader should not get registered and we should end up with only one
1361 // class loader.
Mathieu Chartier496577f2016-09-20 15:33:31 -07001362 mirror::ClassLoader* class_loader = obj->AsClassLoader();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001363 if (class_loader->GetClassTable() != nullptr) {
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001364 DCHECK(compile_app_image_);
1365 DCHECK(class_loaders_.empty());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001366 class_loaders_.insert(class_loader);
Vladimir Marko6ad2f6d2017-01-18 15:22:59 +00001367 ImageInfo& image_info = GetImageInfo(oat_index);
1368 // Note: Avoid locking to prevent lock order violations from root visiting;
1369 // image_info.class_table_ table is only accessed from the image writer
1370 // and class_loader->GetClassTable() is iterated but not modified.
1371 image_info.class_table_->CopyWithoutLocks(*class_loader->GetClassTable());
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001372 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001373 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001374 AssignImageBinSlot(obj, oat_index);
1375 work_stack.emplace(obj, oat_index);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001376 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07001377 if (obj->IsString()) {
1378 // Always return the interned string if there exists one.
1379 mirror::String* interned = FindInternedString(obj->AsString());
1380 if (interned != nullptr) {
1381 return interned;
1382 }
1383 }
1384 return obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -07001385}
1386
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001387bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1388 return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1389}
1390
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001391bool ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001392 // No offset, or already assigned.
1393 if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001394 return false;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001395 }
1396 // If the method is a conflict method we also want to assign the conflict table offset.
1397 ImageInfo& image_info = GetImageInfo(oat_index);
1398 const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1399 native_object_relocations_.emplace(
1400 imt,
1401 NativeObjectRelocation {
1402 oat_index,
1403 image_info.bin_slot_sizes_[kBinImTable],
1404 kNativeObjectRelocationTypeIMTable});
1405 image_info.bin_slot_sizes_[kBinImTable] += size;
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001406 return true;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001407}
1408
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001409void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1410 // No offset, or already assigned.
1411 if (table == nullptr || NativeRelocationAssigned(table)) {
1412 return;
1413 }
1414 CHECK(!IsInBootImage(table));
1415 // If the method is a conflict method we also want to assign the conflict table offset.
1416 ImageInfo& image_info = GetImageInfo(oat_index);
1417 const size_t size = table->ComputeSize(target_ptr_size_);
1418 native_object_relocations_.emplace(
1419 table,
1420 NativeObjectRelocation {
1421 oat_index,
1422 image_info.bin_slot_sizes_[kBinIMTConflictTable],
1423 kNativeObjectRelocationTypeIMTConflictTable});
1424 image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1425}
1426
Jeff Haodcdc85b2015-12-04 14:06:18 -08001427void ImageWriter::AssignMethodOffset(ArtMethod* method,
1428 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001429 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001430 DCHECK(!IsInBootImage(method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001431 CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
David Sehr709b0702016-10-13 09:12:37 -07001432 << ArtMethod::PrettyMethod(method);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001433 if (method->IsRuntimeMethod()) {
1434 TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1435 }
Vladimir Marko944da602016-02-19 12:27:55 +00001436 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001437 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001438 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001439 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001440}
1441
Mathieu Chartier496577f2016-09-20 15:33:31 -07001442void ImageWriter::EnsureBinSlotAssignedCallback(mirror::Object* obj, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001443 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1444 DCHECK(writer != nullptr);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001445 if (!Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(obj)) {
David Sehr709b0702016-10-13 09:12:37 -07001446 CHECK(writer->IsImageBinSlotAssigned(obj)) << mirror::Object::PrettyTypeOf(obj) << " " << obj;
Mathieu Chartier496577f2016-09-20 15:33:31 -07001447 }
1448}
1449
1450void ImageWriter::DeflateMonitorCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED) {
1451 Monitor::Deflate(Thread::Current(), obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001452}
1453
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001454void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1455 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1456 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001457 if (!writer->IsInBootImage(obj)) {
1458 writer->UnbinObjectsIntoOffset(obj);
1459 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001460}
1461
1462void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001463 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001464 CHECK(obj != nullptr);
1465
1466 // We know the bin slot, and the total bin sizes for all objects by now,
1467 // so calculate the object's final image offset.
1468
1469 DCHECK(IsImageBinSlotAssigned(obj));
1470 BinSlot bin_slot = GetImageBinSlot(obj);
1471 // Change the lockword from a bin slot into an offset
1472 AssignImageOffset(obj, bin_slot);
1473}
1474
Mathieu Chartier496577f2016-09-20 15:33:31 -07001475class ImageWriter::VisitReferencesVisitor {
1476 public:
1477 VisitReferencesVisitor(ImageWriter* image_writer, WorkStack* work_stack, size_t oat_index)
1478 : image_writer_(image_writer), work_stack_(work_stack), oat_index_(oat_index) {}
1479
1480 // Fix up separately since we also need to fix up method entrypoints.
1481 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1482 REQUIRES_SHARED(Locks::mutator_lock_) {
1483 if (!root->IsNull()) {
1484 VisitRoot(root);
1485 }
1486 }
1487
1488 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1489 REQUIRES_SHARED(Locks::mutator_lock_) {
1490 root->Assign(VisitReference(root->AsMirrorPtr()));
1491 }
1492
Mathieu Chartier31e88222016-10-14 18:43:19 -07001493 ALWAYS_INLINE void operator() (ObjPtr<mirror::Object> obj,
Mathieu Chartier496577f2016-09-20 15:33:31 -07001494 MemberOffset offset,
1495 bool is_static ATTRIBUTE_UNUSED) const
1496 REQUIRES_SHARED(Locks::mutator_lock_) {
1497 mirror::Object* ref =
1498 obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1499 obj->SetFieldObject</*kTransactionActive*/false>(offset, VisitReference(ref));
1500 }
1501
Mathieu Chartier31e88222016-10-14 18:43:19 -07001502 ALWAYS_INLINE void operator() (ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1503 ObjPtr<mirror::Reference> ref) const
Mathieu Chartier496577f2016-09-20 15:33:31 -07001504 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001505 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
Mathieu Chartier496577f2016-09-20 15:33:31 -07001506 }
1507
1508 private:
1509 mirror::Object* VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1510 return image_writer_->TryAssignBinSlot(*work_stack_, ref, oat_index_);
1511 }
1512
1513 ImageWriter* const image_writer_;
1514 WorkStack* const work_stack_;
1515 const size_t oat_index_;
1516};
1517
1518class ImageWriter::GetRootsVisitor : public RootVisitor {
1519 public:
1520 explicit GetRootsVisitor(std::vector<mirror::Object*>* roots) : roots_(roots) {}
1521
1522 void VisitRoots(mirror::Object*** roots,
1523 size_t count,
1524 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1525 REQUIRES_SHARED(Locks::mutator_lock_) {
1526 for (size_t i = 0; i < count; ++i) {
1527 roots_->push_back(*roots[i]);
1528 }
1529 }
1530
1531 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
1532 size_t count,
1533 const RootInfo& info ATTRIBUTE_UNUSED) OVERRIDE
1534 REQUIRES_SHARED(Locks::mutator_lock_) {
1535 for (size_t i = 0; i < count; ++i) {
1536 roots_->push_back(roots[i]->AsMirrorPtr());
1537 }
1538 }
1539
1540 private:
1541 std::vector<mirror::Object*>* const roots_;
1542};
1543
1544void ImageWriter::ProcessWorkStack(WorkStack* work_stack) {
1545 while (!work_stack->empty()) {
1546 std::pair<mirror::Object*, size_t> pair(work_stack->top());
1547 work_stack->pop();
1548 VisitReferencesVisitor visitor(this, work_stack, /*oat_index*/ pair.second);
1549 // Walk references and assign bin slots for them.
1550 pair.first->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1551 visitor,
1552 visitor);
1553 }
1554}
1555
Vladimir Markof4da6752014-08-01 19:04:18 +01001556void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001557 Thread* const self = Thread::Current();
Mathieu Chartiere8a3c572016-10-11 16:52:17 -07001558 VariableSizedHandleScope handles(self);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001559 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001560 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1561 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001562 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001563
Mathieu Chartier496577f2016-09-20 15:33:31 -07001564 Runtime* const runtime = Runtime::Current();
1565 gc::Heap* const heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001566
Mathieu Chartier31e89252013-08-28 11:29:12 -07001567 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001568 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001569 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001570
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001571 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001572 // Write the image runtime methods.
1573 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1574 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1575 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001576 image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001577 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves);
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001578 image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001579 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly);
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001580 image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001581 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001582 image_methods_[ImageHeader::kSaveEverythingMethod] =
Andreas Gampe8228cdf2017-05-30 15:03:54 -07001583 runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001584 // Visit image methods first to have the main runtime methods in the first image.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001585 for (auto* m : image_methods_) {
1586 CHECK(m != nullptr);
1587 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001588 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1589 if (!IsInBootImage(m)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001590 AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001591 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001592 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001593
Mathieu Chartier496577f2016-09-20 15:33:31 -07001594 // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
1595 // this lock while holding other locks may cause lock order violations.
1596 heap->VisitObjects(DeflateMonitorCallback, this);
1597
1598 // Work list of <object, oat_index> for objects. Everything on the stack must already be
1599 // assigned a bin slot.
1600 WorkStack work_stack;
1601
1602 // Special case interned strings to put them in the image they are likely to be resolved from.
1603 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
1604 auto it = dex_file_oat_index_map_.find(dex_file);
1605 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
1606 const size_t oat_index = it->second;
1607 InternTable* const intern_table = runtime->GetInternTable();
1608 for (size_t i = 0, count = dex_file->NumStringIds(); i < count; ++i) {
1609 uint32_t utf16_length;
Andreas Gampe8a0128a2016-11-28 07:38:35 -08001610 const char* utf8_data = dex_file->StringDataAndUtf16LengthByIdx(dex::StringIndex(i),
1611 &utf16_length);
Mathieu Chartier9e868092016-10-31 14:58:04 -07001612 mirror::String* string = intern_table->LookupStrong(self, utf16_length, utf8_data).Ptr();
Mathieu Chartier496577f2016-09-20 15:33:31 -07001613 TryAssignBinSlot(work_stack, string, oat_index);
1614 }
1615 }
1616
1617 // Get the GC roots and then visit them separately to avoid lock violations since the root visitor
1618 // visits roots while holding various locks.
1619 {
1620 std::vector<mirror::Object*> roots;
1621 GetRootsVisitor root_visitor(&roots);
1622 runtime->VisitRoots(&root_visitor);
1623 for (mirror::Object* obj : roots) {
1624 TryAssignBinSlot(work_stack, obj, GetDefaultOatIndex());
1625 }
1626 }
1627 ProcessWorkStack(&work_stack);
1628
1629 // For app images, there may be objects that are only held live by the by the boot image. One
1630 // example is finalizer references. Forward these objects so that EnsureBinSlotAssignedCallback
1631 // does not fail any checks. TODO: We should probably avoid copying these objects.
1632 if (compile_app_image_) {
1633 for (gc::space::ImageSpace* space : heap->GetBootImageSpaces()) {
1634 DCHECK(space->IsImageSpace());
1635 gc::accounting::ContinuousSpaceBitmap* live_bitmap = space->GetLiveBitmap();
1636 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
1637 reinterpret_cast<uintptr_t>(space->Limit()),
1638 [this, &work_stack](mirror::Object* obj)
1639 REQUIRES_SHARED(Locks::mutator_lock_) {
1640 VisitReferencesVisitor visitor(this, &work_stack, GetDefaultOatIndex());
1641 // Visit all references and try to assign bin slots for them (calls TryAssignBinSlot).
1642 obj->VisitReferences</*kVisitNativeRoots*/true, kVerifyNone, kWithoutReadBarrier>(
1643 visitor,
1644 visitor);
1645 });
1646 }
1647 // Process the work stack in case anything was added by TryAssignBinSlot.
1648 ProcessWorkStack(&work_stack);
Vladimir Markoeca3eda2016-11-09 16:26:44 +00001649
1650 // Store the class loader in the class roots.
1651 CHECK_EQ(class_loaders_.size(), 1u);
1652 CHECK_EQ(image_roots.size(), 1u);
1653 CHECK(*class_loaders_.begin() != nullptr);
1654 image_roots[0]->Set<false>(ImageHeader::kClassLoader, *class_loaders_.begin());
Mathieu Chartier496577f2016-09-20 15:33:31 -07001655 }
1656
1657 // Verify that all objects have assigned image bin slots.
1658 heap->VisitObjects(EnsureBinSlotAssignedCallback, this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001659
Vladimir Marko05792b92015-08-03 11:56:49 +01001660 // Calculate size of the dex cache arrays slot and prepare offsets.
1661 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001662
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001663 // Calculate the sizes of the intern tables, class tables, and fixup tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001664 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001665 // Calculate how big the intern table will be after being serialized.
1666 InternTable* const intern_table = image_info.intern_table_.get();
1667 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
Vladimir Marko1a1de672016-10-13 12:53:15 +01001668 if (intern_table->StrongSize() != 0u) {
1669 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1670 }
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001671
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001672 // Calculate the size of the class table.
1673 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001674 DCHECK_EQ(image_info.class_table_->NumReferencedZygoteClasses(), 0u);
1675 if (image_info.class_table_->NumReferencedNonZygoteClasses() != 0u) {
Vladimir Marko1a1de672016-10-13 12:53:15 +01001676 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
1677 }
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001678 }
1679
Vladimir Markocf36d492015-08-12 19:27:26 +01001680 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001681 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001682 size_t bin_offset = image_objects_offset_begin_;
1683 for (size_t i = 0; i != kBinSize; ++i) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001684 switch (i) {
1685 case kBinArtMethodClean:
1686 case kBinArtMethodDirty: {
1687 bin_offset = RoundUp(bin_offset, method_alignment);
1688 break;
1689 }
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001690 case kBinDexCacheArray:
Vladimir Markof44d36c2017-03-14 14:18:46 +00001691 bin_offset = RoundUp(bin_offset, DexCacheArraysLayout::Alignment(target_ptr_size_));
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001692 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001693 case kBinImTable:
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001694 case kBinIMTConflictTable: {
Andreas Gampe542451c2016-07-26 09:02:02 -07001695 bin_offset = RoundUp(bin_offset, static_cast<size_t>(target_ptr_size_));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001696 break;
1697 }
1698 default: {
1699 // Normal alignment.
1700 }
1701 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001702 image_info.bin_slot_offsets_[i] = bin_offset;
1703 bin_offset += image_info.bin_slot_sizes_[i];
Vladimir Markocf36d492015-08-12 19:27:26 +01001704 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001705 // NOTE: There may be additional padding between the bin slots and the intern table.
1706 DCHECK_EQ(image_info.image_end_,
1707 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001708 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001709
Jeff Haodcdc85b2015-12-04 14:06:18 -08001710 // Calculate image offsets.
1711 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001712 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001713 image_info.image_begin_ = global_image_begin_ + image_offset;
1714 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001715 ImageSection unused_sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001716 image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001717 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001718 image_offset += image_info.image_size_;
1719 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001720
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001721 // Transform each object's bin slot into an offset which will be used to do the final copy.
1722 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001723
Jeff Haodcdc85b2015-12-04 14:06:18 -08001724 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001725 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001726 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1727 i++;
1728 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001729
Mathieu Chartiere401d142015-04-22 13:56:20 -07001730 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001731 for (auto& pair : native_object_relocations_) {
1732 NativeObjectRelocation& relocation = pair.second;
1733 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001734 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001735 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001736 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001737}
1738
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001739size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001740 DCHECK(out_sections != nullptr);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001741
1742 // Do not round up any sections here that are represented by the bins since it will break
1743 // offsets.
1744
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001745 // Objects section
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001746 ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001747 *objects_section = ImageSection(0u, image_end_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001748
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001749 // Add field section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001750 ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1751 *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001752 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001753
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001754 // Add method section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001755 ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1756 *methods_section = ImageSection(
1757 bin_slot_offsets_[kBinArtMethodClean],
1758 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1759
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001760 // IMT section.
1761 ImageSection* imt_section = &out_sections[ImageHeader::kSectionImTables];
1762 *imt_section = ImageSection(bin_slot_offsets_[kBinImTable], bin_slot_sizes_[kBinImTable]);
1763
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001764 // Conflict tables section.
1765 ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1766 *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1767 bin_slot_sizes_[kBinIMTConflictTable]);
1768
1769 // Runtime methods section.
1770 ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1771 *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1772 bin_slot_sizes_[kBinRuntimeMethod]);
1773
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001774 // Add dex cache arrays section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001775 ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1776 *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1777 bin_slot_sizes_[kBinDexCacheArray]);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001778 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001779 size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001780 // Calculate the size of the interned strings.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001781 ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001782 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1783 cur_pos = interned_strings_section->End();
1784 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1785 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1786 // Calculate the size of the class table section.
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001787 ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001788 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001789 cur_pos = class_table_section->End();
1790 // Image end goes right before the start of the image bitmap.
1791 return cur_pos;
1792}
1793
Vladimir Marko944da602016-02-19 12:27:55 +00001794void ImageWriter::CreateHeader(size_t oat_index) {
1795 ImageInfo& image_info = GetImageInfo(oat_index);
1796 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1797 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1798 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001799
1800 // Create the image sections.
1801 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001802 const size_t image_end = image_info.CreateImageSections(sections);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001803
Mathieu Chartiere401d142015-04-22 13:56:20 -07001804 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001805 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001806 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001807 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001808 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001809 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001810 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001811 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001812 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1813 ++idx;
1814 }
1815 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001816 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1817 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1818 << " Image offset=" << image_info.image_offset_ << std::dec;
1819 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1820 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1821 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1822 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001823 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001824 // Store boot image info for app image so that we can relocate.
1825 uint32_t boot_image_begin = 0;
1826 uint32_t boot_image_end = 0;
1827 uint32_t boot_oat_begin = 0;
1828 uint32_t boot_oat_end = 0;
1829 gc::Heap* const heap = Runtime::Current()->GetHeap();
1830 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001831
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001832 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1833 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001834 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1835 image_end,
1836 sections,
1837 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001838 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001839 PointerToLowMemUInt32(oat_file_begin),
1840 PointerToLowMemUInt32(image_info.oat_data_begin_),
1841 PointerToLowMemUInt32(oat_data_end),
1842 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001843 boot_image_begin,
1844 boot_image_end - boot_image_begin,
1845 boot_oat_begin,
1846 boot_oat_end - boot_oat_begin,
Andreas Gampe542451c2016-07-26 09:02:02 -07001847 static_cast<uint32_t>(target_ptr_size_),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001848 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001849 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001850 image_storage_mode_,
1851 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001852}
1853
1854ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001855 auto it = native_object_relocations_.find(method);
David Sehr709b0702016-10-13 09:12:37 -07001856 CHECK(it != native_object_relocations_.end()) << ArtMethod::PrettyMethod(method) << " @ "
1857 << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001858 size_t oat_index = GetOatIndex(method->GetDexCache());
1859 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001860 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1861 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001862}
1863
Vladimir Markoad06b982016-11-17 16:38:59 +00001864class ImageWriter::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001865 public:
1866 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1867 }
1868
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001869 void VisitRoots(mirror::Object*** roots ATTRIBUTE_UNUSED,
1870 size_t count ATTRIBUTE_UNUSED,
1871 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001872 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001873 LOG(FATAL) << "Unsupported";
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001874 }
1875
1876 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1877 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001878 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001879 for (size_t i = 0; i < count; ++i) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001880 image_writer_->CopyReference(roots[i], roots[i]->AsMirrorPtr());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001881 }
1882 }
1883
1884 private:
1885 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001886};
1887
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001888void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
1889 for (size_t i = 0; i < ImTable::kSize; ++i) {
1890 ArtMethod* method = orig->Get(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001891 void** address = reinterpret_cast<void**>(copy->AddressOfElement(i, target_ptr_size_));
1892 CopyAndFixupPointer(address, method);
1893 DCHECK_EQ(copy->Get(i, target_ptr_size_), NativeLocationInImage(method));
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001894 }
1895}
1896
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001897void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
1898 const size_t count = orig->NumEntries(target_ptr_size_);
1899 for (size_t i = 0; i < count; ++i) {
1900 ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
1901 ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001902 CopyAndFixupPointer(copy->AddressOfInterfaceMethod(i, target_ptr_size_), interface_method);
1903 CopyAndFixupPointer(copy->AddressOfImplementationMethod(i, target_ptr_size_),
1904 implementation_method);
1905 DCHECK_EQ(copy->GetInterfaceMethod(i, target_ptr_size_),
1906 NativeLocationInImage(interface_method));
1907 DCHECK_EQ(copy->GetImplementationMethod(i, target_ptr_size_),
1908 NativeLocationInImage(implementation_method));
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001909 }
1910}
1911
Vladimir Marko944da602016-02-19 12:27:55 +00001912void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001913 const ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001914 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001915 for (auto& pair : native_object_relocations_) {
1916 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001917 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001918 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001919 continue;
1920 }
1921 auto* dest = image_info.image_->Begin() + relocation.offset;
1922 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001923 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001924 switch (relocation.type) {
1925 case kNativeObjectRelocationTypeArtField: {
1926 memcpy(dest, pair.first, sizeof(ArtField));
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001927 CopyReference(
1928 reinterpret_cast<ArtField*>(dest)->GetDeclaringClassAddressWithoutBarrier(),
1929 reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass().Ptr());
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001930 break;
1931 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001932 case kNativeObjectRelocationTypeRuntimeMethod:
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001933 case kNativeObjectRelocationTypeArtMethodClean:
1934 case kNativeObjectRelocationTypeArtMethodDirty: {
1935 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001936 reinterpret_cast<ArtMethod*>(dest),
1937 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001938 break;
1939 }
1940 // For arrays, copy just the header since the elements will get copied by their corresponding
1941 // relocations.
1942 case kNativeObjectRelocationTypeArtFieldArray: {
1943 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1944 break;
1945 }
1946 case kNativeObjectRelocationTypeArtMethodArrayClean:
1947 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markod9813cb2016-03-15 12:41:27 +00001948 size_t size = ArtMethod::Size(target_ptr_size_);
1949 size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1950 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1951 // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1952 reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001953 break;
Vladimir Markod9813cb2016-03-15 12:41:27 +00001954 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001955 case kNativeObjectRelocationTypeDexCacheArray:
1956 // Nothing to copy here, everything is done in FixupDexCache().
1957 break;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001958 case kNativeObjectRelocationTypeIMTable: {
1959 ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
1960 ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
1961 CopyAndFixupImTable(orig_imt, dest_imt);
1962 break;
1963 }
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001964 case kNativeObjectRelocationTypeIMTConflictTable: {
1965 auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
1966 CopyAndFixupImtConflictTable(
1967 orig_table,
1968 new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
1969 break;
1970 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001971 }
1972 }
1973 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001974 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001975 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001976 ArtMethod* method = image_methods_[i];
1977 CHECK(method != nullptr);
1978 if (!IsInBootImage(method)) {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001979 method = NativeLocationInImage(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001980 }
1981 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001982 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001983 FixupRootVisitor root_visitor(this);
1984
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001985 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001986 if (image_info.intern_table_bytes_ > 0) {
1987 const ImageSection& intern_table_section = image_header->GetImageSection(
1988 ImageHeader::kSectionInternedStrings);
1989 InternTable* const intern_table = image_info.intern_table_.get();
1990 uint8_t* const intern_table_memory_ptr =
1991 image_info.image_->Begin() + intern_table_section.Offset();
1992 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1993 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1994 // Fixup the pointers in the newly written intern table to contain image addresses.
1995 InternTable temp_intern_table;
1996 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1997 // the VisitRoots() will update the memory directly rather than the copies.
1998 // This also relies on visit roots not doing any verification which could fail after we update
1999 // the roots to be the image addresses.
2000 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
2001 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
2002 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
2003 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002004 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
2005 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002006 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002007 const ImageSection& class_table_section = image_header->GetImageSection(
2008 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002009 uint8_t* const class_table_memory_ptr =
2010 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08002011 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002012
2013 ClassTable* table = image_info.class_table_.get();
2014 CHECK(table != nullptr);
2015 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
2016 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
2017 // Fixup the pointers in the newly written class table to contain image addresses. See
2018 // above comment for intern tables.
2019 ClassTable temp_class_table;
2020 temp_class_table.ReadFromMemory(class_table_memory_ptr);
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002021 CHECK_EQ(temp_class_table.NumReferencedZygoteClasses(),
2022 table->NumReferencedNonZygoteClasses() + table->NumReferencedZygoteClasses());
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -08002023 UnbufferedRootVisitor visitor(&root_visitor, RootInfo(kRootUnknown));
2024 temp_class_table.VisitRoots(visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002025 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002026}
2027
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08002028void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07002029 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07002030 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
2031 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002032 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08002033 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07002034 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
2035 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07002036 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002037 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07002038}
2039
Mathieu Chartier590fee92013-09-13 13:46:47 -07002040void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07002041 DCHECK(obj != nullptr);
2042 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002043 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
2044}
2045
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002046void ImageWriter::FixupPointerArray(mirror::Object* dst,
2047 mirror::PointerArray* arr,
2048 mirror::Class* klass,
2049 Bin array_type) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002050 CHECK(klass->IsArrayClass());
David Sehr709b0702016-10-13 09:12:37 -07002051 CHECK(arr->IsIntArray() || arr->IsLongArray()) << klass->PrettyClass() << " " << arr;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002052 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07002053 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002054 dst->SetClass(GetImageAddress(arr->GetClass()));
2055 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002056 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002057 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002058 if (kIsDebugBuild && elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002059 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01002060 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002061 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002062 auto* method = reinterpret_cast<ArtMethod*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07002063 LOG(FATAL) << "No relocation entry for ArtMethod " << method->PrettyMethod() << " @ "
2064 << method << " idx=" << i << "/" << num_elements << " with declaring class "
2065 << Class::PrettyClass(method->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002066 } else {
2067 CHECK_EQ(array_type, kBinArtField);
2068 auto* field = reinterpret_cast<ArtField*>(elem);
David Sehr709b0702016-10-13 09:12:37 -07002069 LOG(FATAL) << "No relocation entry for ArtField " << field->PrettyField() << " @ "
Mathieu Chartiere401d142015-04-22 13:56:20 -07002070 << field << " idx=" << i << "/" << num_elements << " with declaring class "
David Sehr709b0702016-10-13 09:12:37 -07002071 << Class::PrettyClass(field->GetDeclaringClass());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002072 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002073 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07002074 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002075 }
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002076 CopyAndFixupPointer(dest_array->ElementAddress(i, target_ptr_size_), elem);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002077 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002078}
2079
2080void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002081 if (IsInBootImage(obj)) {
2082 return;
2083 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002084 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00002085 size_t oat_index = GetOatIndex(obj);
2086 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002087 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
2088 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002089 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002090
Jeff Haodcdc85b2015-12-04 14:06:18 -08002091 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002092
2093 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002094 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002095 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002096
Mathieu Chartierad2541a2013-10-25 10:05:23 -07002097 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
2098 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002099 const auto it = saved_hashcode_map_.find(obj);
2100 dst->SetLockWord(it != saved_hashcode_map_.end() ?
2101 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartier36a270a2016-07-28 18:08:51 -07002102 if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
2103 // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
2104 // safe since we mark all of the objects that may reference non immune objects as gray.
2105 CHECK(dst->AtomicSetMarkBit(0, 1));
2106 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002107 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07002108}
2109
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002110// Rewrite all the references in the copied object to point to their image address equivalent
Vladimir Markoad06b982016-11-17 16:38:59 +00002111class ImageWriter::FixupVisitor {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002112 public:
2113 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
2114 }
2115
Mathieu Chartierda7c6502015-07-23 16:01:26 -07002116 // Ignore class roots since we don't have a way to map them to the destination. These are handled
2117 // with other logic.
2118 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
2119 const {}
2120 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
2121
2122
Mathieu Chartier31e88222016-10-14 18:43:19 -07002123 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002124 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier31e88222016-10-14 18:43:19 -07002125 ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002126 // Copy the reference and record the fixup if necessary.
2127 image_writer_->CopyReference(
2128 copy_->GetFieldObjectReferenceAddr<kVerifyNone>(offset),
2129 ref.Ptr());
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002130 }
2131
2132 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07002133 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2134 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002135 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002136 operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002137 }
2138
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002139 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002140 ImageWriter* const image_writer_;
2141 mirror::Object* const copy_;
2142};
2143
Vladimir Markoad06b982016-11-17 16:38:59 +00002144class ImageWriter::FixupClassVisitor FINAL : public FixupVisitor {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002145 public:
2146 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
2147 }
2148
Mathieu Chartier31e88222016-10-14 18:43:19 -07002149 void operator()(ObjPtr<Object> obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07002150 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002151 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002152 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002153 }
2154
Mathieu Chartier31e88222016-10-14 18:43:19 -07002155 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
2156 ObjPtr<mirror::Reference> ref ATTRIBUTE_UNUSED) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002157 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002158 LOG(FATAL) << "Reference not expected here.";
2159 }
2160};
2161
Vladimir Marko05792b92015-08-03 11:56:49 +01002162uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
2163 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002164 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002165 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002166 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
2167 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07002168 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01002169 return relocation.offset;
2170}
2171
2172template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002173std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002174 std::ostringstream oss;
2175 oss << ptr;
2176 return oss.str();
2177}
2178
2179template <>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002180std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -07002181 return ArtMethod::PrettyMethod(method);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002182}
2183
2184template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002185T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002186 if (obj == nullptr || IsInBootImage(obj)) {
2187 return obj;
2188 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002189 auto it = native_object_relocations_.find(obj);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002190 CHECK(it != native_object_relocations_.end()) << obj << " " << PrettyPrint(obj)
2191 << " spaces " << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002192 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00002193 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002194 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002195 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002196}
2197
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002198template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08002199T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
2200 if (obj == nullptr || IsInBootImage(obj)) {
2201 return obj;
2202 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002203 size_t oat_index = GetOatIndexForDexCache(dex_cache);
2204 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002205 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
2206 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002207}
2208
Vladimir Markoad06b982016-11-17 16:38:59 +00002209class ImageWriter::NativeLocationVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002210 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002211 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002212
2213 template <typename T>
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002214 T* operator()(T* ptr, void** dest_addr = nullptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
2215 if (dest_addr != nullptr) {
2216 image_writer_->CopyAndFixupPointer(dest_addr, ptr);
2217 }
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002218 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002219 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002220
2221 private:
2222 ImageWriter* const image_writer_;
2223};
2224
2225void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002226 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002227 FixupClassVisitor visitor(this, copy);
Mathieu Chartier31e88222016-10-14 18:43:19 -07002228 ObjPtr<mirror::Object>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08002229
2230 // Remove the clinitThreadId. This is required for image determinism.
2231 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002232}
2233
Ian Rogersef7d42f2014-01-06 12:55:46 -08002234void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07002235 DCHECK(orig != nullptr);
2236 DCHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07002237 if (kUseBakerReadBarrier) {
2238 orig->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08002239 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002240 auto* klass = orig->GetClass();
2241 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01002242 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07002243 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
2244 if (it != pointer_arrays_.end()) {
2245 // Should only need to fixup every pointer array exactly once.
2246 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
2247 pointer_arrays_.erase(it);
2248 return;
2249 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002250 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002251 if (orig->IsClass()) {
2252 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002253 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002254 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
2255 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01002256 auto* dest = down_cast<mirror::Executable*>(copy);
2257 auto* src = down_cast<mirror::Executable*>(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002258 ArtMethod* src_method = src->GetArtMethod();
Jing Ji96e640c2016-08-31 21:21:37 -05002259 dest->SetArtMethod(GetImageMethodAddress(src_method));
Vladimir Marko05792b92015-08-03 11:56:49 +01002260 } else if (!klass->IsArrayClass()) {
2261 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2262 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
2263 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08002264 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002265 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01002266 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
2267 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002268 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07002269 // Also set allocator to null to be safe. The allocator is created when we create the class
2270 // table. We also never expect to unload things in the image since they are held live as
2271 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002272 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002273 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002274 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002275 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07002276 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002277 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002278}
2279
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002280class ImageWriter::ImageAddressVisitorForDexCacheArray {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002281 public:
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002282 explicit ImageAddressVisitorForDexCacheArray(ImageWriter* image_writer)
2283 : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002284
2285 template <typename T>
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07002286 T* operator()(T* ptr) const REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002287 return image_writer_->GetImageAddress(ptr);
2288 }
2289
2290 private:
2291 ImageWriter* const image_writer_;
2292};
2293
Vladimir Marko05792b92015-08-03 11:56:49 +01002294void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
2295 mirror::DexCache* copy_dex_cache) {
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002296 ImageAddressVisitorForDexCacheArray fixup_visitor(this);
Vladimir Marko05792b92015-08-03 11:56:49 +01002297 // Though the DexCache array fields are usually treated as native pointers, we set the full
2298 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
2299 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
2300 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07002301 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
Vladimir Marko05792b92015-08-03 11:56:49 +01002302 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002303 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002304 NativeLocationInImage(orig_strings),
Andreas Gampe542451c2016-07-26 09:02:02 -07002305 PointerSize::k64);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002306 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache), fixup_visitor);
Vladimir Marko05792b92015-08-03 11:56:49 +01002307 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00002308 mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
Vladimir Marko05792b92015-08-03 11:56:49 +01002309 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002310 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002311 NativeLocationInImage(orig_types),
Andreas Gampe542451c2016-07-26 09:02:02 -07002312 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002313 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002314 fixup_visitor);
Vladimir Marko05792b92015-08-03 11:56:49 +01002315 }
2316 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
2317 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002318 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002319 NativeLocationInImage(orig_methods),
Andreas Gampe542451c2016-07-26 09:02:02 -07002320 PointerSize::k64);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002321 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002322 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
2323 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002324 // NativeLocationInImage also handles runtime methods since these have relocation info.
2325 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01002326 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
2327 }
2328 }
Vladimir Markof44d36c2017-03-14 14:18:46 +00002329 mirror::FieldDexCacheType* orig_fields = orig_dex_cache->GetResolvedFields();
Vladimir Marko05792b92015-08-03 11:56:49 +01002330 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08002331 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002332 NativeLocationInImage(orig_fields),
Andreas Gampe542451c2016-07-26 09:02:02 -07002333 PointerSize::k64);
Vladimir Markof44d36c2017-03-14 14:18:46 +00002334 mirror::FieldDexCacheType* copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01002335 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00002336 mirror::FieldDexCachePair orig =
2337 mirror::DexCache::GetNativePairPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002338 mirror::FieldDexCachePair copy = orig;
2339 copy.object = NativeLocationInImage(orig.object);
Vladimir Markof44d36c2017-03-14 14:18:46 +00002340 mirror::DexCache::SetNativePairPtrSize(copy_fields, i, copy, target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002341 }
2342 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01002343 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
2344 if (orig_method_types != nullptr) {
2345 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodTypesOffset(),
2346 NativeLocationInImage(orig_method_types),
2347 PointerSize::k64);
2348 orig_dex_cache->FixupResolvedMethodTypes(NativeCopyLocation(orig_method_types, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002349 fixup_visitor);
Narayan Kamath7fe56582016-10-14 18:49:12 +01002350 }
Orion Hodsonc069a302017-01-18 09:23:12 +00002351 GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
2352 if (orig_call_sites != nullptr) {
2353 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedCallSitesOffset(),
2354 NativeLocationInImage(orig_call_sites),
2355 PointerSize::k64);
2356 orig_dex_cache->FixupResolvedCallSites(NativeCopyLocation(orig_call_sites, orig_dex_cache),
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002357 fixup_visitor);
Orion Hodsonc069a302017-01-18 09:23:12 +00002358 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002359
2360 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2361 // compiler pointers in here will make the output non-deterministic.
2362 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002363}
2364
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002365const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2366 DCHECK_LT(type, kOatAddressCount);
2367 // If we are compiling an app image, we need to use the stubs of the boot image.
2368 if (compile_app_image_) {
2369 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002370 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002371 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2372 DCHECK(!image_spaces.empty());
2373 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002374 CHECK(oat_file != nullptr);
2375 const OatHeader& header = oat_file->GetOatHeader();
2376 switch (type) {
2377 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2378 case kOatAddressQuickGenericJNITrampoline:
2379 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2380 case kOatAddressInterpreterToInterpreterBridge:
2381 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2382 case kOatAddressInterpreterToCompiledCodeBridge:
2383 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2384 case kOatAddressJNIDlsymLookup:
2385 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2386 case kOatAddressQuickIMTConflictTrampoline:
2387 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2388 case kOatAddressQuickResolutionTrampoline:
2389 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2390 case kOatAddressQuickToInterpreterBridge:
2391 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2392 default:
2393 UNREACHABLE();
2394 }
2395 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002396 const ImageInfo& primary_image_info = GetImageInfo(0);
2397 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002398}
2399
Jeff Haodcdc85b2015-12-04 14:06:18 -08002400const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2401 const ImageInfo& image_info,
2402 bool* quick_is_interpreted) {
David Sehr709b0702016-10-13 09:12:37 -07002403 DCHECK(!method->IsResolutionMethod()) << method->PrettyMethod();
2404 DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << method->PrettyMethod();
2405 DCHECK(!method->IsImtUnimplementedMethod()) << method->PrettyMethod();
2406 DCHECK(method->IsInvokable()) << method->PrettyMethod();
2407 DCHECK(!IsInBootImage(method)) << method->PrettyMethod();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002408
2409 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2410 // trampoline.
2411
2412 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08002413 const void* quick_oat_entry_point =
2414 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2415 const uint8_t* quick_code;
2416
2417 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2418 DCHECK(method->IsCopied());
2419 // If the code is not in the oat file corresponding to this image (e.g. default methods)
2420 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2421 } else {
2422 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2423 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2424 }
2425
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002426 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002427 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2428 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002429 // We have code for a non-static or initialized method, just use the code.
2430 } else if (quick_code == nullptr && method->IsNative() &&
2431 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2432 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002433 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002434 } else if (quick_code == nullptr && !method->IsNative()) {
2435 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002436 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002437 *quick_is_interpreted = true;
2438 } else {
2439 CHECK(!method->GetDeclaringClass()->IsInitialized());
2440 // We have code for a static method, but need to go through the resolution stub for class
2441 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002442 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2443 }
2444 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002445 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002446 }
2447 return quick_code;
2448}
2449
Jeff Haodcdc85b2015-12-04 14:06:18 -08002450void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2451 ArtMethod* copy,
2452 const ImageInfo& image_info) {
Mingyao Yange8fcd012017-01-20 10:43:30 -08002453 if (orig->IsAbstract()) {
2454 // Ignore the single-implementation info for abstract method.
2455 // Do this on orig instead of copy, otherwise there is a crash due to methods
2456 // are copied before classes.
2457 // TODO: handle fixup of single-implementation method for abstract method.
2458 orig->SetHasSingleImplementation(false);
2459 orig->SetSingleImplementation(
2460 nullptr, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
2461 }
2462
Vladimir Marko14632852015-08-17 12:07:23 +01002463 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002464
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002465 CopyReference(copy->GetDeclaringClassAddressWithoutBarrier(), orig->GetDeclaringClassUnchecked());
2466
Vladimir Marko05792b92015-08-03 11:56:49 +01002467 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002468 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002469
Ian Rogers848871b2013-08-05 10:56:33 -07002470 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2471 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002472
Ian Rogers848871b2013-08-05 10:56:33 -07002473 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002474 Runtime* runtime = Runtime::Current();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002475 if (orig->IsRuntimeMethod()) {
2476 ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2477 if (orig_table != nullptr) {
2478 // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2479 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2480 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2481 copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2482 } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2483 copy->SetEntryPointFromQuickCompiledCodePtrSize(
2484 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2485 } else {
2486 bool found_one = false;
Andreas Gampe8228cdf2017-05-30 15:03:54 -07002487 for (size_t i = 0; i < static_cast<size_t>(CalleeSaveType::kLastCalleeSaveType); ++i) {
2488 auto idx = static_cast<CalleeSaveType>(i);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002489 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2490 found_one = true;
2491 break;
2492 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07002493 }
David Sehr709b0702016-10-13 09:12:37 -07002494 CHECK(found_one) << "Expected to find callee save method but got " << orig->PrettyMethod();
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002495 CHECK(copy->IsRuntimeMethod());
Mathieu Chartiere401d142015-04-22 13:56:20 -07002496 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002497 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002498 // We assume all methods have code. If they don't currently then we set them to the use the
2499 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2500 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002501 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002502 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002503 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002504 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002505 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002506 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002507 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002508
Sebastien Hertze1d07812014-05-21 15:44:09 +02002509 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002510 if (orig->IsNative()) {
2511 // The native method's pointer is set to a stub to lookup via dlsym.
2512 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002513 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002514 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002515 }
2516 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002517 }
2518}
2519
Jeff Haodcdc85b2015-12-04 14:06:18 -08002520size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002521 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002522 return std::accumulate(&image_info.bin_slot_sizes_[0],
2523 &image_info.bin_slot_sizes_[up_to],
2524 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002525}
2526
2527ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2528 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002529 static_assert(kBinBits == 3, "wrong number of bin bits");
2530 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002531 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2532
2533 DCHECK_LT(GetBin(), kBinSize);
2534 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2535}
2536
2537ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2538 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2539 DCHECK_EQ(index, GetIndex());
2540}
2541
2542ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2543 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2544}
2545
2546uint32_t ImageWriter::BinSlot::GetIndex() const {
2547 return lockword_ & ~kBinMask;
2548}
2549
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002550ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2551 switch (type) {
2552 case kNativeObjectRelocationTypeArtField:
2553 case kNativeObjectRelocationTypeArtFieldArray:
2554 return kBinArtField;
2555 case kNativeObjectRelocationTypeArtMethodClean:
2556 case kNativeObjectRelocationTypeArtMethodArrayClean:
2557 return kBinArtMethodClean;
2558 case kNativeObjectRelocationTypeArtMethodDirty:
2559 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2560 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002561 case kNativeObjectRelocationTypeDexCacheArray:
2562 return kBinDexCacheArray;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002563 case kNativeObjectRelocationTypeRuntimeMethod:
2564 return kBinRuntimeMethod;
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00002565 case kNativeObjectRelocationTypeIMTable:
2566 return kBinImTable;
Mathieu Chartiere42888f2016-04-14 10:49:19 -07002567 case kNativeObjectRelocationTypeIMTConflictTable:
2568 return kBinIMTConflictTable;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002569 }
2570 UNREACHABLE();
2571}
2572
Vladimir Marko944da602016-02-19 12:27:55 +00002573size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002574 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002575 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002576 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002577 auto it = oat_index_map_.find(obj);
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002578 DCHECK(it != oat_index_map_.end()) << obj;
Mathieu Chartier496577f2016-09-20 15:33:31 -07002579 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002580}
2581
Vladimir Marko944da602016-02-19 12:27:55 +00002582size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
Mathieu Chartier496577f2016-09-20 15:33:31 -07002583 if (!IsMultiImage()) {
Vladimir Marko944da602016-02-19 12:27:55 +00002584 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002585 }
Mathieu Chartier496577f2016-09-20 15:33:31 -07002586 auto it = dex_file_oat_index_map_.find(dex_file);
2587 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2588 return it->second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002589}
2590
Mathieu Chartierc4f39252016-10-05 18:32:08 -07002591size_t ImageWriter::GetOatIndexForDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
2592 return (dex_cache == nullptr)
2593 ? GetDefaultOatIndex()
2594 : GetOatIndexForDexFile(dex_cache->GetDexFile());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002595}
2596
Vladimir Marko944da602016-02-19 12:27:55 +00002597void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2598 size_t oat_loaded_size,
2599 size_t oat_data_offset,
2600 size_t oat_data_size) {
2601 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2602 for (const ImageInfo& info : image_infos_) {
2603 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2604 }
2605 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002606
Vladimir Marko944da602016-02-19 12:27:55 +00002607 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2608 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2609 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2610 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2611 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002612
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002613 if (compile_app_image_) {
2614 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2615 return;
2616 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002617
2618 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002619 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002620 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002621 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002622 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2623 }
2624}
2625
Vladimir Marko944da602016-02-19 12:27:55 +00002626void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2627 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2628 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2629
2630 if (oat_index == GetDefaultOatIndex()) {
2631 // Primary oat file, read the trampolines.
2632 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2633 oat_header.GetInterpreterToInterpreterBridgeOffset();
2634 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2635 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2636 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2637 oat_header.GetJniDlsymLookupOffset();
2638 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2639 oat_header.GetQuickGenericJniTrampolineOffset();
2640 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2641 oat_header.GetQuickImtConflictTrampolineOffset();
2642 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2643 oat_header.GetQuickResolutionTrampolineOffset();
2644 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2645 oat_header.GetQuickToInterpreterBridgeOffset();
2646 }
2647}
2648
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002649ImageWriter::ImageWriter(
2650 const CompilerDriver& compiler_driver,
2651 uintptr_t image_begin,
2652 bool compile_pic,
2653 bool compile_app_image,
2654 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002655 const std::vector<const char*>& oat_filenames,
2656 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002657 : compiler_driver_(compiler_driver),
2658 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2659 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002660 compile_pic_(compile_pic),
2661 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002662 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002663 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002664 dirty_methods_(0u),
2665 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002666 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002667 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002668 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002669 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002670 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002671 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2672 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002673}
2674
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002675ImageWriter::ImageInfo::ImageInfo()
2676 : intern_table_(new InternTable),
2677 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002678
Mathieu Chartier8c19d242017-03-06 12:35:10 -08002679void ImageWriter::CopyReference(mirror::HeapReference<mirror::Object>* dest,
2680 ObjPtr<mirror::Object> src) {
2681 dest->Assign(GetImageAddress(src.Ptr()));
2682}
2683
2684void ImageWriter::CopyReference(mirror::CompressedReference<mirror::Object>* dest,
2685 ObjPtr<mirror::Object> src) {
2686 dest->Assign(GetImageAddress(src.Ptr()));
2687}
2688
2689void ImageWriter::CopyAndFixupPointer(void** target, void* value) {
2690 void* new_value = value;
2691 if (value != nullptr && !IsInBootImage(value)) {
2692 auto it = native_object_relocations_.find(value);
2693 CHECK(it != native_object_relocations_.end()) << value;
2694 const NativeObjectRelocation& relocation = it->second;
2695 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2696 new_value = reinterpret_cast<void*>(image_info.image_begin_ + relocation.offset);
2697 }
2698 if (target_ptr_size_ == PointerSize::k32) {
2699 *reinterpret_cast<uint32_t*>(target) = PointerToLowMemUInt32(new_value);
2700 } else {
2701 *reinterpret_cast<uint64_t*>(target) = reinterpret_cast<uintptr_t>(new_value);
2702 }
2703}
2704
2705
Brian Carlstrom7940e442013-07-12 13:46:57 -07002706} // namespace art