blob: 871435b85fbc4a69bc54e726ef7ab0850276d20a [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "image_writer.h"
18
19#include <sys/stat.h>
Mathieu Chartierceb07b32015-12-10 09:33:21 -080020#include <lz4.h>
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -080021#include <lz4hc.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Vladimir Marko20f85592015-03-19 10:07:02 +000024#include <numeric>
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080025#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070026#include <vector>
27
Mathieu Chartierc7853442015-03-27 14:35:38 -070028#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070029#include "art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070030#include "base/logging.h"
31#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010032#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070033#include "compiled_method.h"
34#include "dex_file-inl.h"
35#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070036#include "elf_file.h"
37#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "elf_writer.h"
39#include "gc/accounting/card_table-inl.h"
40#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070041#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070042#include "gc/heap.h"
43#include "gc/space/large_object_space.h"
44#include "gc/space/space-inl.h"
45#include "globals.h"
46#include "image.h"
47#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070048#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070049#include "lock_word.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070050#include "mirror/abstract_method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "mirror/array-inl.h"
52#include "mirror/class-inl.h"
53#include "mirror/class_loader.h"
54#include "mirror/dex_cache-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070055#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "mirror/object-inl.h"
57#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070058#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "oat.h"
60#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070061#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "runtime.h"
63#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070064#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000065#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070067using ::art::mirror::Class;
68using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070069using ::art::mirror::Object;
70using ::art::mirror::ObjectArray;
71using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070072
73namespace art {
74
Igor Murashkinf5b4c502014-11-14 15:01:59 -080075// Separate objects into multiple bins to optimize dirty memory use.
76static constexpr bool kBinObjects = true;
77
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080078// Return true if an object is already in an image space.
79bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080080 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080081 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080082 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080083 return false;
84 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080085 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
86 const uint8_t* image_begin = boot_image_space->Begin();
87 // Real image end including ArtMethods and ArtField sections.
88 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
89 if (image_begin <= obj && obj < image_end) {
90 return true;
91 }
92 }
93 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080094}
95
96bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080097 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080098 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080099 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800100 return false;
101 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800102 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
103 const ImageHeader& image_header = boot_image_space->GetImageHeader();
104 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
105 return true;
106 }
107 }
108 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800109}
110
Andreas Gampedd9d0552015-03-09 12:57:41 -0700111static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700112 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700113 Class* klass = obj->GetClass();
114 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
115}
116
117static void CheckNoDexObjects() {
118 ScopedObjectAccess soa(Thread::Current());
119 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
120}
121
Vladimir Markof4da6752014-08-01 19:04:18 +0100122bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800123 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800124 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100125 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700126 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100127 PruneNonImageClasses(); // Remove junk
Mathieu Chartier901e0702016-02-19 13:42:48 -0800128 if (!compile_app_image_) {
129 // Avoid for app image since this may increase RAM and image size.
130 ComputeLazyFieldsForImageClasses(); // Add useful information
131 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100132 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100133 heap->CollectGarbage(false); // Remove garbage.
134
Andreas Gampedd9d0552015-03-09 12:57:41 -0700135 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
136 // dex files.
137 //
138 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
139 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
140 // true.
141 if (kIsDebugBuild) {
142 CheckNoDexObjects();
143 }
144
Vladimir Markof4da6752014-08-01 19:04:18 +0100145 if (kIsDebugBuild) {
146 ScopedObjectAccess soa(Thread::Current());
147 CheckNonImageClassesRemoved();
148 }
149
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700150 {
151 ScopedObjectAccess soa(Thread::Current());
152 CalculateNewObjectOffsets();
153 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100154
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700155 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
156 // bin size sums being calculated.
157 if (!AllocMemory()) {
158 return false;
159 }
160
Vladimir Markof4da6752014-08-01 19:04:18 +0100161 return true;
162}
163
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700164bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800165 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000166 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800167 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
168 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800169 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800170 if (image_fd != kInvalidFd) {
171 CHECK_EQ(image_filenames.size(), 1u);
172 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800173 CHECK(!oat_filenames.empty());
174 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700175
Vladimir Marko944da602016-02-19 12:27:55 +0000176 {
177 ScopedObjectAccess soa(Thread::Current());
178 for (size_t i = 0; i < oat_filenames.size(); ++i) {
179 CreateHeader(i);
180 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800181 }
182 }
Alex Light53cb16b2014-06-12 11:26:29 -0700183
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700184 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700185 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800186 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700187 Runtime::Current()->GetHeap()->DisableObjectValidation();
188 CopyAndFixupObjects();
189 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190
Jeff Haodcdc85b2015-12-04 14:06:18 -0800191 for (size_t i = 0; i < image_filenames.size(); ++i) {
192 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000193 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800194 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800195 if (image_fd != kInvalidFd) {
196 if (strlen(image_filename) == 0u) {
197 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800198 // Empty the file in case it already exists.
199 if (image_file != nullptr) {
200 TEMP_FAILURE_RETRY(image_file->SetLength(0));
201 TEMP_FAILURE_RETRY(image_file->Flush());
202 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800203 } else {
204 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
205 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800206 } else {
207 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800208 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800209
Jeff Haodcdc85b2015-12-04 14:06:18 -0800210 if (image_file == nullptr) {
211 LOG(ERROR) << "Failed to open image file " << image_filename;
212 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800213 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800214
215 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800216 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
217 image_file->Erase();
218 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800219 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800220
Jeff Haodcdc85b2015-12-04 14:06:18 -0800221 std::unique_ptr<char[]> compressed_data;
222 // Image data size excludes the bitmap and the header.
223 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
224 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
225 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
226 size_t data_size;
227 const char* image_data_to_write;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800228 const uint64_t compress_start_time = NanoTime();
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000229
Jeff Haodcdc85b2015-12-04 14:06:18 -0800230 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
231 switch (image_storage_mode_) {
232 case ImageHeader::kStorageModeLZ4: {
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800233 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800234 compressed_data.reset(new char[compressed_max_size]);
235 data_size = LZ4_compress(
236 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
237 &compressed_data[0],
238 image_data_size);
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800239
240 break;
241 }
242 case ImageHeader::kStorageModeLZ4HC: {
243 // Bound is same as non HC.
244 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
245 compressed_data.reset(new char[compressed_max_size]);
246 data_size = LZ4_compressHC(
247 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
248 &compressed_data[0],
249 image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800250 break;
251 }
252 case ImageHeader::kStorageModeUncompressed: {
253 data_size = image_data_size;
254 image_data_to_write = image_data;
255 break;
256 }
257 default: {
258 LOG(FATAL) << "Unsupported";
259 UNREACHABLE();
260 }
261 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800262
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800263 if (compressed_data != nullptr) {
264 image_data_to_write = &compressed_data[0];
265 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
266 << PrettyDuration(NanoTime() - compress_start_time);
267 }
268
Jeff Haodcdc85b2015-12-04 14:06:18 -0800269 // Write header first, as uncompressed.
270 image_header->data_size_ = data_size;
271 if (!image_file->WriteFully(image_info.image_->Begin(), sizeof(ImageHeader))) {
272 PLOG(ERROR) << "Failed to write image file header " << image_filename;
273 image_file->Erase();
274 return false;
275 }
276
277 // Write out the image + fields + methods.
278 const bool is_compressed = compressed_data != nullptr;
279 if (!image_file->WriteFully(image_data_to_write, data_size)) {
280 PLOG(ERROR) << "Failed to write image file data " << image_filename;
281 image_file->Erase();
282 return false;
283 }
284
285 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
286 // convenience.
287 const ImageSection& bitmap_section = image_header->GetImageSection(
288 ImageHeader::kSectionImageBitmap);
289 // Align up since data size may be unaligned if the image is compressed.
290 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
291 if (!is_compressed) {
292 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
293 }
294 if (!image_file->Write(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
295 bitmap_section.Size(),
296 bitmap_position_in_file)) {
297 PLOG(ERROR) << "Failed to write image file " << image_filename;
298 image_file->Erase();
299 return false;
300 }
301 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
302 static_cast<size_t>(image_file->GetLength()));
303 if (image_file->FlushCloseOrErase() != 0) {
304 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
305 return false;
306 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800307 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700308 return true;
309}
310
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700311void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700312 DCHECK(object != nullptr);
313 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800314
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800315 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700316 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700317 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700318 DCHECK(IsImageOffsetAssigned(object));
319}
320
Mathieu Chartiere401d142015-04-22 13:56:20 -0700321void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
322 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
323 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
324 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
325}
326
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800327void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700328 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800329 DCHECK_NE(image_objects_offset_begin_, 0u);
330
Vladimir Marko944da602016-02-19 12:27:55 +0000331 size_t oat_index = GetOatIndex(object);
332 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800333 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100334 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800335 DCHECK_ALIGNED(new_offset, kObjectAlignment);
336
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700337 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800338 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700339}
340
Ian Rogersef7d42f2014-01-06 12:55:46 -0800341bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800342 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700343 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700344 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700345}
346
Ian Rogersef7d42f2014-01-06 12:55:46 -0800347size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700348 DCHECK(object != nullptr);
349 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700350 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700351 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000352 size_t oat_index = GetOatIndex(object);
353 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800354 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700355 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700356}
357
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800358void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
359 DCHECK(object != nullptr);
360 DCHECK(!IsImageOffsetAssigned(object));
361 DCHECK(!IsImageBinSlotAssigned(object));
362
363 // Before we stomp over the lock word, save the hash code for later.
364 Monitor::Deflate(Thread::Current(), object);;
365 LockWord lw(object->GetLockWord(false));
366 switch (lw.GetState()) {
367 case LockWord::kFatLocked: {
368 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
369 break;
370 }
371 case LockWord::kThinLocked: {
372 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
373 break;
374 }
375 case LockWord::kUnlocked:
376 // No hash, don't need to save it.
377 break;
378 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700379 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
380 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800381 break;
382 default:
383 LOG(FATAL) << "Unreachable.";
384 UNREACHABLE();
385 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700386 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700387 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800388 DCHECK(IsImageBinSlotAssigned(object));
389}
390
Vladimir Marko20f85592015-03-19 10:07:02 +0000391void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000392 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000393 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
394 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800395 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000396 auto it = dex_file_oat_index_map_.find(dex_file);
397 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800398 ImageInfo& image_info = GetImageInfo(it->second);
399 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
400 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
401 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
402 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000403
Vladimir Marko20f85592015-03-19 10:07:02 +0000404 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700405 Thread* const self = Thread::Current();
406 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800407 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700408 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800409 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800410 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700411 continue;
412 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000413 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700414 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000415 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000416 size_t oat_index = GetOatIndexForDexCache(dex_cache);
417 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800418 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100419 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800420 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
421 start + layout.TypesOffset(),
422 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100423 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800424 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
425 start + layout.MethodsOffset(),
426 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100427 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800428 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
429 start + layout.FieldsOffset(),
430 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100431 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800432 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000433 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000434}
435
Jeff Haodcdc85b2015-12-04 14:06:18 -0800436void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100437 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800438 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000439 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800440 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000441 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100442 }
443}
444
Mathieu Chartiere401d142015-04-22 13:56:20 -0700445void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
446 DCHECK(arr != nullptr);
447 if (kIsDebugBuild) {
448 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800449 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700450 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800451 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800452 CHECK(klass == nullptr || KeepClass(klass))
453 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700454 }
455 }
456 }
457 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
458 // ArtMethods.
459 pointer_arrays_.emplace(arr, kBinArtMethodClean);
460}
461
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800462void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
463 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800464 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800465
466 // The magic happens here. We segregate objects into different bins based
467 // on how likely they are to get dirty at runtime.
468 //
469 // Likely-to-dirty objects get packed together into the same bin so that
470 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
471 // maximized.
472 //
473 // This means more pages will stay either clean or shared dirty (with zygote) and
474 // the app will use less of its own (private) memory.
475 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000476 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800477
478 if (kBinObjects) {
479 //
480 // Changing the bin of an object is purely a memory-use tuning.
481 // It has no change on runtime correctness.
482 //
483 // Memory analysis has determined that the following types of objects get dirtied
484 // the most:
485 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000486 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
487 // a fixed layout which helps improve generated code (using PC-relative addressing),
488 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
489 // Since these arrays are huge, most pages do not overlap other objects and it's not
490 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100491 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800492 // * Class'es which are verified [their clinit runs only at runtime]
493 // - classes in general [because their static fields get overwritten]
494 // - initialized classes with all-final statics are unlikely to be ever dirty,
495 // so bin them separately
496 // * Art Methods that are:
497 // - native [their native entry point is not looked up until runtime]
498 // - have declaring classes that aren't initialized
499 // [their interpreter/quick entry points are trampolines until the class
500 // becomes initialized]
501 //
502 // We also assume the following objects get dirtied either never or extremely rarely:
503 // * Strings (they are immutable)
504 // * Art methods that aren't native and have initialized declared classes
505 //
506 // We assume that "regular" bin objects are highly unlikely to become dirtied,
507 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
508 //
509 if (object->IsClass()) {
510 bin = kBinClassVerified;
511 mirror::Class* klass = object->AsClass();
512
Mathieu Chartiere401d142015-04-22 13:56:20 -0700513 // Add non-embedded vtable to the pointer array table if there is one.
514 auto* vtable = klass->GetVTable();
515 if (vtable != nullptr) {
516 AddMethodPointerArray(vtable);
517 }
518 auto* iftable = klass->GetIfTable();
519 if (iftable != nullptr) {
520 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
521 if (iftable->GetMethodArrayCount(i) > 0) {
522 AddMethodPointerArray(iftable->GetMethodArray(i));
523 }
524 }
525 }
526
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800527 if (klass->GetStatus() == Class::kStatusInitialized) {
528 bin = kBinClassInitialized;
529
530 // If the class's static fields are all final, put it into a separate bin
531 // since it's very likely it will stay clean.
532 uint32_t num_static_fields = klass->NumStaticFields();
533 if (num_static_fields == 0) {
534 bin = kBinClassInitializedFinalStatics;
535 } else {
536 // Maybe all the statics are final?
537 bool all_final = true;
538 for (uint32_t i = 0; i < num_static_fields; ++i) {
539 ArtField* field = klass->GetStaticField(i);
540 if (!field->IsFinal()) {
541 all_final = false;
542 break;
543 }
544 }
545
546 if (all_final) {
547 bin = kBinClassInitializedFinalStatics;
548 }
549 }
550 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800551 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
552 bin = kBinString; // Strings are almost always immutable (except for object header).
553 } // else bin = kBinRegular
554 }
555
Vladimir Marko944da602016-02-19 12:27:55 +0000556 size_t oat_index = GetOatIndex(object);
557 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800558
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800559 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800560 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
561 // Move the current bin size up to accommodate the object we just assigned a bin slot.
562 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800563
564 BinSlot new_bin_slot(bin, current_offset);
565 SetImageBinSlot(object, new_bin_slot);
566
Jeff Haodcdc85b2015-12-04 14:06:18 -0800567 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800568
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800569 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800570 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800571}
572
Mathieu Chartiere401d142015-04-22 13:56:20 -0700573bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
574 if (m->IsNative()) {
575 return true;
576 }
577 mirror::Class* declaring_class = m->GetDeclaringClass();
578 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
579 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
580}
581
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800582bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
583 DCHECK(object != nullptr);
584
585 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
586 // If it's in some other state, then we haven't yet assigned an image bin slot.
587 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
588 return false;
589 } else if (kIsDebugBuild) {
590 LockWord lock_word = object->GetLockWord(false);
591 size_t offset = lock_word.ForwardingAddress();
592 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000593 size_t oat_index = GetOatIndex(object);
594 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800595 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800596 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800597 }
598 return true;
599}
600
601ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
602 DCHECK(object != nullptr);
603 DCHECK(IsImageBinSlotAssigned(object));
604
605 LockWord lock_word = object->GetLockWord(false);
606 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
607 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
608
609 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000610 size_t oat_index = GetOatIndex(object);
611 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800612 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800613
614 return bin_slot;
615}
616
Brian Carlstrom7940e442013-07-12 13:46:57 -0700617bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000618 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800619 ImageSection unused_sections[ImageHeader::kSectionCount];
620 const size_t length = RoundUp(
621 image_info.CreateImageSections(target_ptr_size_, unused_sections),
622 kPageSize);
623
Jeff Haodcdc85b2015-12-04 14:06:18 -0800624 std::string error_msg;
625 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
626 nullptr,
627 length,
628 PROT_READ | PROT_WRITE,
629 false,
630 false,
631 &error_msg));
632 if (UNLIKELY(image_info.image_.get() == nullptr)) {
633 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
634 return false;
635 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700636
Jeff Haodcdc85b2015-12-04 14:06:18 -0800637 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
638 CHECK_LE(image_info.image_end_, length);
639 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
640 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
641 if (image_info.image_bitmap_.get() == nullptr) {
642 LOG(ERROR) << "Failed to allocate memory for image bitmap";
643 return false;
644 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700645 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700646 return true;
647}
648
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700649class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
650 public:
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800651 bool operator()(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700652 StackHandleScope<1> hs(Thread::Current());
653 mirror::Class::ComputeName(hs.NewHandle(c));
654 return true;
655 }
656};
657
Brian Carlstrom7940e442013-07-12 13:46:57 -0700658void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700659 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700660 ComputeLazyFieldsForClassesVisitor visitor;
661 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700662}
663
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800664static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
665 return klass->GetClassLoader() == nullptr;
666}
667
668bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
669 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
670}
671
Mathieu Chartier901e0702016-02-19 13:42:48 -0800672bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800673 bool early_exit = false;
674 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800675 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800676}
677
Mathieu Chartier901e0702016-02-19 13:42:48 -0800678bool ImageWriter::PruneAppImageClassInternal(
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800679 mirror::Class* klass,
680 bool* early_exit,
681 std::unordered_set<mirror::Class*>* visited) {
682 DCHECK(early_exit != nullptr);
683 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800684 DCHECK(compile_app_image_);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800685 if (klass == nullptr || IsInBootImage(klass)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700686 return false;
687 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800688 auto found = prune_class_memo_.find(klass);
689 if (found != prune_class_memo_.end()) {
690 // Already computed, return the found value.
691 return found->second;
692 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800693 // Circular dependencies, return false but do not store the result in the memoization table.
694 if (visited->find(klass) != visited->end()) {
695 *early_exit = true;
696 return false;
697 }
698 visited->emplace(klass);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800699 bool result = IsBootClassLoaderClass(klass);
700 std::string temp;
701 // Prune if not an image class, this handles any broken sets of image classes such as having a
702 // class in the set but not it's superclass.
703 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800704 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800705 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
706 // app image.
707 if (klass->GetStatus() == mirror::Class::kStatusError) {
708 result = true;
709 } else {
710 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
711 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800712 if (!result) {
713 // Check interfaces since these wont be visited through VisitReferences.)
714 mirror::IfTable* if_table = klass->GetIfTable();
715 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800716 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
717 &my_early_exit,
718 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800719 }
720 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800721 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800722 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
723 &my_early_exit,
724 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800725 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800726 // Check static fields and their classes.
727 size_t num_static_fields = klass->NumReferenceStaticFields();
728 if (num_static_fields != 0 && klass->IsResolved()) {
729 // Presumably GC can happen when we are cross compiling, it should not cause performance
730 // problems to do pointer size logic.
731 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
732 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
733 for (size_t i = 0u; i < num_static_fields; ++i) {
734 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
735 if (ref != nullptr) {
736 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800737 result = result || PruneAppImageClassInternal(ref->AsClass(),
738 &my_early_exit,
739 visited);
740 } else {
741 result = result || PruneAppImageClassInternal(ref->GetClass(),
742 &my_early_exit,
743 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800744 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800745 }
746 field_offset = MemberOffset(field_offset.Uint32Value() +
747 sizeof(mirror::HeapReference<mirror::Object>));
748 }
749 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800750 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
751 &my_early_exit,
752 visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800753 // Erase the element we stored earlier since we are exiting the function.
754 auto it = visited->find(klass);
755 DCHECK(it != visited->end());
756 visited->erase(it);
757 // Only store result if it is true or none of the calls early exited due to circular
758 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
759 // a child call and we can remember the result.
760 if (result == true || !my_early_exit || visited->empty()) {
761 prune_class_memo_[klass] = result;
762 }
763 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800764 return result;
765}
766
767bool ImageWriter::KeepClass(Class* klass) {
768 if (klass == nullptr) {
769 return false;
770 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800771 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
772 // Already in boot image, return true.
773 return true;
774 }
775 std::string temp;
776 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
777 return false;
778 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800779 if (compile_app_image_) {
780 // For app images, we need to prune boot loader classes that are not in the boot image since
781 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800782 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800783 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800784 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800785 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700786}
787
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700788class NonImageClassesVisitor : public ClassVisitor {
789 public:
790 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
791
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800792 bool operator()(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800793 if (!image_writer_->KeepClass(klass)) {
794 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700795 }
796 return true;
797 }
798
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800799 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700800 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700801};
802
803void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700804 Runtime* runtime = Runtime::Current();
805 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700806 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700807
808 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700809 NonImageClassesVisitor visitor(this);
810 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700811
812 // Remove the undesired classes from the class roots.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800813 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800814 for (mirror::Class* klass : visitor.classes_to_prune_) {
815 std::string temp;
816 const char* name = klass->GetDescriptor(&temp);
817 VLOG(compiler) << "Pruning class " << name;
818 if (!compile_app_image_) {
819 DCHECK(IsBootClassLoaderClass(klass));
820 }
821 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800822 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700823 }
824
825 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100826 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700827
828 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
829 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
830 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800831 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800832 if (self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700833 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700834 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800835 mirror::DexCache* dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700836 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
837 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800838 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700839 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700840 }
841 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100842 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
843 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
844 ArtMethod* method =
845 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800846 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
847 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800848 // Copied methods may be held live by a class which was not an image class but have a
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800849 // declaring class which is an image class. Set it to the resolution method to be safe and
850 // prevent dangling pointers.
Alex Light36121492016-02-22 13:43:29 -0800851 if (method->IsCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800852 mirror::DexCache::SetElementPtrSize(resolved_methods,
853 i,
854 resolution_method,
855 target_ptr_size_);
856 } else {
857 // Check that the class is still in the classes table.
858 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
859 << PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700860 }
861 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800862 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700863 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800864 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800865 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700866 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700867 }
868 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700869 // Clean the dex field. It might have been populated during the initialization phase, but
870 // contains data only valid during a real run.
871 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700872 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700873
874 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
875 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800876
877 // Clear to save RAM.
878 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700879}
880
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800881void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700882 if (compiler_driver_.GetImageClasses() != nullptr) {
883 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700884 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700885 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700886}
887
888void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
889 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800890 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700891 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800892 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700893 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700894 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800895 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
896 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700897 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700898 }
899}
900
901void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700902 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700903 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700904 for (const std::string& image_class : *image_classes) {
905 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700906 }
907}
908
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800909mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
910 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +0000911 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800912 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
913 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
914 << string->ToModifiedUtf8();
915 if (found != nullptr) {
916 return found;
917 }
918 }
919 if (compile_app_image_) {
920 Runtime* const runtime = Runtime::Current();
921 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
922 // If we found it in the runtime intern table it could either be in the boot image or interned
923 // during app image compilation. If it was in the boot image return that, otherwise return null
924 // since it belongs to another image space.
925 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
926 return found;
927 }
928 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
929 << string->ToModifiedUtf8();
930 }
931 return nullptr;
932}
933
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800934void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700935 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700936 // if it is a string, we want to intern it if its not interned.
937 if (obj->GetClass()->IsStringClass()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000938 size_t oat_index = GetOatIndex(obj);
939 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800940
Brian Carlstrom7940e442013-07-12 13:46:57 -0700941 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800942 if (IsImageBinSlotAssigned(obj)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800943 DCHECK_EQ(obj, FindInternedString(obj->AsString()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700944 return;
945 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800946 // Need to check if the string is already interned in another image info so that we don't have
947 // the intern tables of two different images contain the same string.
948 mirror::String* interned = FindInternedString(obj->AsString());
949 if (interned == nullptr) {
950 // Not in another image space, insert to our table.
951 interned = image_info.intern_table_->InternStrongImageString(obj->AsString());
952 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700953 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800954 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700955 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800956 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700957 }
958 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800959 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700960 return;
961 }
962 // else (obj == interned), nothing to do but fall through to the normal case
963 }
964
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800965 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700966}
967
Vladimir Marko944da602016-02-19 12:27:55 +0000968ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700969 Runtime* runtime = Runtime::Current();
970 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700971 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700972 StackHandleScope<3> hs(self);
973 Handle<Class> object_array_class(hs.NewHandle(
974 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700975
Jeff Haodcdc85b2015-12-04 14:06:18 -0800976 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +0000977 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800978 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +0000979 size_t image_oat_index = pair.second;
980 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800981 image_dex_files.insert(image_dex_file);
982 }
983 }
984
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700985 // build an Object[] of all the DexCaches used in the source_space_.
986 // Since we can't hold the dex lock when allocating the dex_caches
987 // ObjectArray, we lock the dex lock twice, first to get the number
988 // of dex caches first and then lock it again to copy the dex
989 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800990 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700991 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700992 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800993 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800994 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
995 mirror::DexCache* dex_cache =
996 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800997 const DexFile* dex_file = dex_cache->GetDexFile();
998 if (!IsInBootImage(dex_cache)) {
999 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1000 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001001 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001002 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001003 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001004 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001005 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1006 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001007 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001008 size_t non_image_dex_caches = 0;
1009 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001010 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1011 mirror::DexCache* dex_cache =
1012 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001013 const DexFile* dex_file = dex_cache->GetDexFile();
1014 if (!IsInBootImage(dex_cache)) {
1015 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1016 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001017 }
1018 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1019 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001020 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001021 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1022 mirror::DexCache* dex_cache =
1023 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001024 const DexFile* dex_file = dex_cache->GetDexFile();
1025 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001026 dex_caches->Set<false>(i, dex_cache);
1027 ++i;
1028 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001029 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001030 }
1031
1032 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001033 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001034 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001035 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001036 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001037 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001038 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001039 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001040 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001041}
1042
Mathieu Chartier590fee92013-09-13 13:46:47 -07001043// Walk instance fields of the given Class. Separate function to allow recursion on the super
1044// class.
1045void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1046 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001047 StackHandleScope<1> hs(Thread::Current());
1048 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1049 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001050 if (super != nullptr) {
1051 WalkInstanceFields(obj, super);
1052 }
1053 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001054 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +00001055 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001056 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001057 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001058 if (value != nullptr) {
1059 WalkFieldsInOrder(value);
1060 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001061 field_offset = MemberOffset(field_offset.Uint32Value() +
1062 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001063 }
1064}
1065
1066// For an unvisited object, visit it then all its children found via fields.
1067void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001068 if (IsInBootImage(obj)) {
1069 // Object is in the image, don't need to fix it up.
1070 return;
1071 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001072 // Use our own visitor routine (instead of GC visitor) to get better locality between
1073 // an object and its fields
1074 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001075 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001076 StackHandleScope<2> hs(Thread::Current());
1077 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1078 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001079 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001080 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001081 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001082 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001083 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001084 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001085 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001086 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001087 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001088 if (value != nullptr) {
1089 WalkFieldsInOrder(value);
1090 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001091 field_offset = MemberOffset(field_offset.Uint32Value() +
1092 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001093 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001094 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001095 auto* as_klass = h_obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001096 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001097 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1098 if (compile_app_image_) {
1099 // Extra sanity, no boot loader classes should be left!
1100 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1101 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001102 LengthPrefixedArray<ArtField>* fields[] = {
1103 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1104 };
Vladimir Marko944da602016-02-19 12:27:55 +00001105 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1106 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001107 {
1108 // Note: This table is only accessed from the image writer, so the lock is technically
1109 // unnecessary.
1110 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1111 // Insert in the class table for this iamge.
1112 image_info.class_table_->Insert(as_klass);
1113 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001114 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1115 // Total array length including header.
1116 if (cur_fields != nullptr) {
1117 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1118 // Forward the entire array at once.
1119 auto it = native_object_relocations_.find(cur_fields);
1120 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1121 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001122 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001123 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001124 native_object_relocations_.emplace(
1125 cur_fields,
1126 NativeObjectRelocation {
1127 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1128 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001129 offset += header_size;
1130 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001131 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001132 // Need to forward arrays separate of fields.
1133 ArtField* field = &cur_fields->At(i);
1134 auto it2 = native_object_relocations_.find(field);
1135 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1136 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001137 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001138 native_object_relocations_.emplace(
1139 field,
1140 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001141 offset += sizeof(ArtField);
1142 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001143 }
1144 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001145 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001146 size_t num_methods = as_klass->NumMethods();
1147 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001148 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001149 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1150 if (WillMethodBeDirty(&m)) {
1151 any_dirty = true;
1152 break;
1153 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001154 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001155 NativeObjectRelocationType type = any_dirty
1156 ? kNativeObjectRelocationTypeArtMethodDirty
1157 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001158 Bin bin_type = BinTypeForNativeRelocationType(type);
1159 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001160 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1161 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001162 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1163 method_size,
1164 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001165 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001166 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001167 CHECK(it == native_object_relocations_.end())
1168 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001169 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001170 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001171 native_object_relocations_.emplace(array,
1172 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001173 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001174 offset,
1175 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1176 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001177 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001178 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001179 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001180 }
Alex Lighte64300b2015-12-15 15:02:47 -08001181 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001182 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001183 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001184 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001185 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001186 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001187 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001188 mirror::Object* value = obj_array->Get(i);
1189 if (value != nullptr) {
1190 WalkFieldsInOrder(value);
1191 }
1192 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001193 } else if (h_obj->IsClassLoader()) {
1194 // Register the class loader if it has a class table.
1195 // The fake boot class loader should not get registered and we should end up with only one
1196 // class loader.
1197 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1198 if (class_loader->GetClassTable() != nullptr) {
1199 class_loaders_.insert(class_loader);
1200 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001201 }
1202 }
1203}
1204
Jeff Haodcdc85b2015-12-04 14:06:18 -08001205void ImageWriter::AssignMethodOffset(ArtMethod* method,
1206 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001207 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001208 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001209 auto it = native_object_relocations_.find(method);
1210 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001211 << PrettyMethod(method);
Vladimir Marko944da602016-02-19 12:27:55 +00001212 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001213 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001214 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001215 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001216}
1217
Mathieu Chartier590fee92013-09-13 13:46:47 -07001218void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1219 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1220 DCHECK(writer != nullptr);
1221 writer->WalkFieldsInOrder(obj);
1222}
1223
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001224void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1225 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1226 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001227 if (!writer->IsInBootImage(obj)) {
1228 writer->UnbinObjectsIntoOffset(obj);
1229 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001230}
1231
1232void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001233 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001234 CHECK(obj != nullptr);
1235
1236 // We know the bin slot, and the total bin sizes for all objects by now,
1237 // so calculate the object's final image offset.
1238
1239 DCHECK(IsImageBinSlotAssigned(obj));
1240 BinSlot bin_slot = GetImageBinSlot(obj);
1241 // Change the lockword from a bin slot into an offset
1242 AssignImageOffset(obj, bin_slot);
1243}
1244
Vladimir Markof4da6752014-08-01 19:04:18 +01001245void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001246 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001247 StackHandleScopeCollection handles(self);
1248 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001249 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1250 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001251 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001252
Mathieu Chartiere401d142015-04-22 13:56:20 -07001253 auto* runtime = Runtime::Current();
1254 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001255
Mathieu Chartier31e89252013-08-28 11:29:12 -07001256 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001257 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001258 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001259
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001260 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1261 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001262 // Write the image runtime methods.
1263 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1264 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1265 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1266 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1267 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1268 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1269 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1270 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001271
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001272 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001273 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1274 auto it = native_object_relocations_.find(&image_method_array_);
1275 CHECK(it == native_object_relocations_.end());
Vladimir Marko944da602016-02-19 12:27:55 +00001276 ImageInfo& default_image_info = GetImageInfo(GetDefaultOatIndex());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001277 size_t& offset =
1278 default_image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001279 if (!compile_app_image_) {
1280 native_object_relocations_.emplace(&image_method_array_,
Vladimir Marko944da602016-02-19 12:27:55 +00001281 NativeObjectRelocation { GetDefaultOatIndex(), offset, image_method_type });
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001282 }
Vladimir Marko14632852015-08-17 12:07:23 +01001283 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001284 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001285 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001286 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001287 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001288 for (auto* m : image_methods_) {
1289 CHECK(m != nullptr);
1290 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001291 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1292 if (!IsInBootImage(m)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001293 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001294 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001295 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001296 // Calculate size of the dex cache arrays slot and prepare offsets.
1297 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001298
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001299 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001300 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001301 // Calculate how big the intern table will be after being serialized.
1302 InternTable* const intern_table = image_info.intern_table_.get();
1303 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1304 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001305 // Calculate the size of the class table.
1306 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1307 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001308 }
1309
Vladimir Markocf36d492015-08-12 19:27:26 +01001310 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001311 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001312 size_t bin_offset = image_objects_offset_begin_;
1313 for (size_t i = 0; i != kBinSize; ++i) {
1314 image_info.bin_slot_offsets_[i] = bin_offset;
1315 bin_offset += image_info.bin_slot_sizes_[i];
1316 if (i == kBinArtField) {
1317 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1318 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1319 DCHECK_ALIGNED(bin_offset, 4u);
1320 DCHECK(method_alignment == 4u || method_alignment == 8u);
1321 bin_offset = RoundUp(bin_offset, method_alignment);
1322 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001323 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001324 // NOTE: There may be additional padding between the bin slots and the intern table.
1325 DCHECK_EQ(image_info.image_end_,
1326 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001327 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001328
Jeff Haodcdc85b2015-12-04 14:06:18 -08001329 // Calculate image offsets.
1330 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001331 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001332 image_info.image_begin_ = global_image_begin_ + image_offset;
1333 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001334 ImageSection unused_sections[ImageHeader::kSectionCount];
1335 image_info.image_size_ = RoundUp(
1336 image_info.CreateImageSections(target_ptr_size_, unused_sections),
1337 kPageSize);
1338 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001339 image_offset += image_info.image_size_;
1340 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001341
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001342 // Transform each object's bin slot into an offset which will be used to do the final copy.
1343 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001344
Jeff Haodcdc85b2015-12-04 14:06:18 -08001345 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001346
Jeff Haodcdc85b2015-12-04 14:06:18 -08001347 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001348 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001349 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1350 i++;
1351 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001352
Mathieu Chartiere401d142015-04-22 13:56:20 -07001353 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001354 for (auto& pair : native_object_relocations_) {
1355 NativeObjectRelocation& relocation = pair.second;
1356 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001357 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001358 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001359 }
1360
Jeff Haodcdc85b2015-12-04 14:06:18 -08001361 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001362}
1363
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001364size_t ImageWriter::ImageInfo::CreateImageSections(size_t target_ptr_size,
1365 ImageSection* out_sections) const {
1366 DCHECK(out_sections != nullptr);
1367 // Objects section
1368 auto* objects_section = &out_sections[ImageHeader::kSectionObjects];
1369 *objects_section = ImageSection(0u, image_end_);
1370 size_t cur_pos = objects_section->End();
1371 // Add field section.
1372 auto* field_section = &out_sections[ImageHeader::kSectionArtFields];
1373 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
1374 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
1375 cur_pos = field_section->End();
1376 // Round up to the alignment the required by the method section.
1377 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size));
1378 // Add method section.
1379 auto* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1380 *methods_section = ImageSection(cur_pos,
1381 bin_slot_sizes_[kBinArtMethodClean] +
1382 bin_slot_sizes_[kBinArtMethodDirty]);
1383 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
1384 cur_pos = methods_section->End();
1385 // Add dex cache arrays section.
1386 auto* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1387 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1388 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1389 cur_pos = dex_cache_arrays_section->End();
1390 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1391 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1392 // Calculate the size of the interned strings.
1393 auto* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
1394 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1395 cur_pos = interned_strings_section->End();
1396 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1397 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1398 // Calculate the size of the class table section.
1399 auto* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001400 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001401 cur_pos = class_table_section->End();
1402 // Image end goes right before the start of the image bitmap.
1403 return cur_pos;
1404}
1405
Vladimir Marko944da602016-02-19 12:27:55 +00001406void ImageWriter::CreateHeader(size_t oat_index) {
1407 ImageInfo& image_info = GetImageInfo(oat_index);
1408 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1409 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1410 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001411
1412 // Create the image sections.
1413 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001414 const size_t image_end = image_info.CreateImageSections(target_ptr_size_, sections);
1415
Mathieu Chartiere401d142015-04-22 13:56:20 -07001416 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001417 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001418 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001419 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001420 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001421 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001422 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001423 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001424 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1425 ++idx;
1426 }
1427 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001428 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1429 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1430 << " Image offset=" << image_info.image_offset_ << std::dec;
1431 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1432 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1433 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1434 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001435 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001436 // Store boot image info for app image so that we can relocate.
1437 uint32_t boot_image_begin = 0;
1438 uint32_t boot_image_end = 0;
1439 uint32_t boot_oat_begin = 0;
1440 uint32_t boot_oat_end = 0;
1441 gc::Heap* const heap = Runtime::Current()->GetHeap();
1442 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001443
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001444 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1445 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001446 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1447 image_end,
1448 sections,
1449 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001450 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001451 PointerToLowMemUInt32(oat_file_begin),
1452 PointerToLowMemUInt32(image_info.oat_data_begin_),
1453 PointerToLowMemUInt32(oat_data_end),
1454 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001455 boot_image_begin,
1456 boot_image_end - boot_image_begin,
1457 boot_oat_begin,
1458 boot_oat_end - boot_oat_begin,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001459 target_ptr_size_,
1460 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001461 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001462 image_storage_mode_,
1463 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001464}
1465
1466ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001467 auto it = native_object_relocations_.find(method);
1468 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001469 size_t oat_index = GetOatIndex(method->GetDexCache());
1470 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001471 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1472 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001473}
1474
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001475class FixupRootVisitor : public RootVisitor {
1476 public:
1477 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1478 }
1479
1480 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001481 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001482 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001483 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001484 }
1485 }
1486
1487 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1488 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001489 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001490 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001491 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001492 }
1493 }
1494
1495 private:
1496 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001497};
1498
Vladimir Marko944da602016-02-19 12:27:55 +00001499void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
1500 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001501 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001502 for (auto& pair : native_object_relocations_) {
1503 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001504 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001505 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001506 continue;
1507 }
1508 auto* dest = image_info.image_->Begin() + relocation.offset;
1509 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001510 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001511 switch (relocation.type) {
1512 case kNativeObjectRelocationTypeArtField: {
1513 memcpy(dest, pair.first, sizeof(ArtField));
1514 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1515 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1516 break;
1517 }
1518 case kNativeObjectRelocationTypeArtMethodClean:
1519 case kNativeObjectRelocationTypeArtMethodDirty: {
1520 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001521 reinterpret_cast<ArtMethod*>(dest),
1522 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001523 break;
1524 }
1525 // For arrays, copy just the header since the elements will get copied by their corresponding
1526 // relocations.
1527 case kNativeObjectRelocationTypeArtFieldArray: {
1528 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1529 break;
1530 }
1531 case kNativeObjectRelocationTypeArtMethodArrayClean:
1532 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001533 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1534 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001535 ArtMethod::Size(target_ptr_size_),
1536 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001537 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001538 case kNativeObjectRelocationTypeDexCacheArray:
1539 // Nothing to copy here, everything is done in FixupDexCache().
1540 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001541 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001542 }
1543 }
1544 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001545 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001546 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001547 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001548 ArtMethod* method = image_methods_[i];
1549 CHECK(method != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001550 // Only place runtime methods in the image of the default oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001551 if (method->IsRuntimeMethod() && oat_index != GetDefaultOatIndex()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001552 continue;
1553 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001554 if (!IsInBootImage(method)) {
1555 auto it = native_object_relocations_.find(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001556 CHECK(it != native_object_relocations_.end()) << "No forwarding for " << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001557 NativeObjectRelocation& relocation = it->second;
1558 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1559 << methods_section;
1560 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001561 method = reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001562 }
1563 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001564 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001565 FixupRootVisitor root_visitor(this);
1566
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001567 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001568 if (image_info.intern_table_bytes_ > 0) {
1569 const ImageSection& intern_table_section = image_header->GetImageSection(
1570 ImageHeader::kSectionInternedStrings);
1571 InternTable* const intern_table = image_info.intern_table_.get();
1572 uint8_t* const intern_table_memory_ptr =
1573 image_info.image_->Begin() + intern_table_section.Offset();
1574 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1575 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1576 // Fixup the pointers in the newly written intern table to contain image addresses.
1577 InternTable temp_intern_table;
1578 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1579 // the VisitRoots() will update the memory directly rather than the copies.
1580 // This also relies on visit roots not doing any verification which could fail after we update
1581 // the roots to be the image addresses.
1582 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1583 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1584 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1585 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001586 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1587 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001588 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001589 const ImageSection& class_table_section = image_header->GetImageSection(
1590 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001591 uint8_t* const class_table_memory_ptr =
1592 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001593 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001594
1595 ClassTable* table = image_info.class_table_.get();
1596 CHECK(table != nullptr);
1597 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1598 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1599 // Fixup the pointers in the newly written class table to contain image addresses. See
1600 // above comment for intern tables.
1601 ClassTable temp_class_table;
1602 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1603 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1604 table->NumZygoteClasses());
1605 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1606 RootInfo(kRootUnknown));
1607 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001608 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001609}
1610
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001611void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001612 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001613 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1614 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001615 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001616 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001617 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1618 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001619 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001620 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001621}
1622
Mathieu Chartier590fee92013-09-13 13:46:47 -07001623void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001624 DCHECK(obj != nullptr);
1625 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001626 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1627}
1628
Mathieu Chartiere401d142015-04-22 13:56:20 -07001629void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1630 mirror::Class* klass, Bin array_type) {
1631 CHECK(klass->IsArrayClass());
1632 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1633 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001634 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001635 dst->SetClass(GetImageAddress(arr->GetClass()));
1636 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001637 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001638 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1639 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001640 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001641 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001642 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001643 auto* method = reinterpret_cast<ArtMethod*>(elem);
1644 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1645 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1646 << PrettyClass(method->GetDeclaringClass());
1647 } else {
1648 CHECK_EQ(array_type, kBinArtField);
1649 auto* field = reinterpret_cast<ArtField*>(elem);
1650 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1651 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1652 << PrettyClass(field->GetDeclaringClass());
1653 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001654 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001655 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001656 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001657 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001658 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001659 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001660 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001661 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001662}
1663
1664void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001665 if (IsInBootImage(obj)) {
1666 return;
1667 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001668 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001669 size_t oat_index = GetOatIndex(obj);
1670 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001671 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1672 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001673 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001674
Jeff Haodcdc85b2015-12-04 14:06:18 -08001675 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001676
1677 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001678 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001679 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001680
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001681 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1682 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001683 const auto it = saved_hashcode_map_.find(obj);
1684 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1685 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001686 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001687}
1688
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001689// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001690class FixupVisitor {
1691 public:
1692 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1693 }
1694
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001695 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1696 // with other logic.
1697 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1698 const {}
1699 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1700
1701
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001702 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001703 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001704 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001705 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1706 // image.
1707 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001708 offset,
1709 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001710 }
1711
1712 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001713 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001714 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001715 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001716 mirror::Reference::ReferentOffset(),
1717 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001718 }
1719
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001720 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001721 ImageWriter* const image_writer_;
1722 mirror::Object* const copy_;
1723};
1724
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001725class FixupClassVisitor FINAL : public FixupVisitor {
1726 public:
1727 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1728 }
1729
Mathieu Chartierc7853442015-03-27 14:35:38 -07001730 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001731 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001732 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001733 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001734 }
1735
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001736 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1737 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001738 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001739 LOG(FATAL) << "Reference not expected here.";
1740 }
1741};
1742
Vladimir Marko05792b92015-08-03 11:56:49 +01001743uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1744 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001745 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001746 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001747 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1748 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001749 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001750 return relocation.offset;
1751}
1752
1753template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001754T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001755 if (obj == nullptr || IsInBootImage(obj)) {
1756 return obj;
1757 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001758 auto it = native_object_relocations_.find(obj);
1759 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1760 << Runtime::Current()->GetHeap()->DumpSpaces();
1761 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00001762 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001763 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001764 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001765}
1766
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001767template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001768T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1769 if (obj == nullptr || IsInBootImage(obj)) {
1770 return obj;
1771 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001772 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1773 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001774 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1775 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001776}
1777
1778class NativeLocationVisitor {
1779 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001780 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001781
1782 template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001783 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001784 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001785 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001786
1787 private:
1788 ImageWriter* const image_writer_;
1789};
1790
1791void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001792 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001793 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001794 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001795
1796 // Remove the clinitThreadId. This is required for image determinism.
1797 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001798}
1799
Ian Rogersef7d42f2014-01-06 12:55:46 -08001800void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001801 DCHECK(orig != nullptr);
1802 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001803 if (kUseBakerOrBrooksReadBarrier) {
1804 orig->AssertReadBarrierPointer();
1805 if (kUseBrooksReadBarrier) {
1806 // Note the address 'copy' isn't the same as the image address of 'orig'.
1807 copy->SetReadBarrierPointer(GetImageAddress(orig));
1808 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1809 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001810 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001811 auto* klass = orig->GetClass();
1812 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001813 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001814 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1815 if (it != pointer_arrays_.end()) {
1816 // Should only need to fixup every pointer array exactly once.
1817 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1818 pointer_arrays_.erase(it);
1819 return;
1820 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001821 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001822 if (orig->IsClass()) {
1823 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001824 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001825 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1826 // Need to go update the ArtMethod.
1827 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1828 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1829 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001830 auto it = native_object_relocations_.find(src_method);
1831 CHECK(it != native_object_relocations_.end())
1832 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001833 dest->SetArtMethod(
Jeff Haodcdc85b2015-12-04 14:06:18 -08001834 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001835 } else if (!klass->IsArrayClass()) {
1836 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1837 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1838 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001839 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001840 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01001841 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1842 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001843 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001844 // Also set allocator to null to be safe. The allocator is created when we create the class
1845 // table. We also never expect to unload things in the image since they are held live as
1846 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001847 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001848 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001849 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001850 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001851 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001852 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001853}
1854
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001855
1856class ImageAddressVisitor {
1857 public:
1858 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1859
1860 template <typename T>
1861 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1862 return image_writer_->GetImageAddress(ptr);
1863 }
1864
1865 private:
1866 ImageWriter* const image_writer_;
1867};
1868
1869
Vladimir Marko05792b92015-08-03 11:56:49 +01001870void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1871 mirror::DexCache* copy_dex_cache) {
1872 // Though the DexCache array fields are usually treated as native pointers, we set the full
1873 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1874 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1875 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1876 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1877 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001878 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001879 NativeLocationInImage(orig_strings),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001880 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001881 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
1882 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001883 }
1884 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1885 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001886 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001887 NativeLocationInImage(orig_types),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001888 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001889 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
1890 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001891 }
1892 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1893 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001894 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001895 NativeLocationInImage(orig_methods),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001896 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001897 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001898 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1899 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001900 // NativeLocationInImage also handles runtime methods since these have relocation info.
1901 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001902 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1903 }
1904 }
1905 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1906 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001907 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001908 NativeLocationInImage(orig_fields),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001909 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001910 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001911 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1912 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001913 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001914 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1915 }
1916 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001917
1918 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
1919 // compiler pointers in here will make the output non-deterministic.
1920 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001921}
1922
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001923const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1924 DCHECK_LT(type, kOatAddressCount);
1925 // If we are compiling an app image, we need to use the stubs of the boot image.
1926 if (compile_app_image_) {
1927 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001928 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08001929 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1930 DCHECK(!image_spaces.empty());
1931 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001932 CHECK(oat_file != nullptr);
1933 const OatHeader& header = oat_file->GetOatHeader();
1934 switch (type) {
1935 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1936 case kOatAddressQuickGenericJNITrampoline:
1937 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1938 case kOatAddressInterpreterToInterpreterBridge:
1939 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1940 case kOatAddressInterpreterToCompiledCodeBridge:
1941 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1942 case kOatAddressJNIDlsymLookup:
1943 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1944 case kOatAddressQuickIMTConflictTrampoline:
1945 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1946 case kOatAddressQuickResolutionTrampoline:
1947 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1948 case kOatAddressQuickToInterpreterBridge:
1949 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1950 default:
1951 UNREACHABLE();
1952 }
1953 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001954 const ImageInfo& primary_image_info = GetImageInfo(0);
1955 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001956}
1957
Jeff Haodcdc85b2015-12-04 14:06:18 -08001958const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
1959 const ImageInfo& image_info,
1960 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001961 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
1962 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
1963 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07001964 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001965 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001966
1967 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1968 // trampoline.
1969
1970 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08001971 const void* quick_oat_entry_point =
1972 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
1973 const uint8_t* quick_code;
1974
1975 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
1976 DCHECK(method->IsCopied());
1977 // If the code is not in the oat file corresponding to this image (e.g. default methods)
1978 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
1979 } else {
1980 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
1981 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
1982 }
1983
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001984 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001985 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
1986 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001987 // We have code for a non-static or initialized method, just use the code.
1988 } else if (quick_code == nullptr && method->IsNative() &&
1989 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1990 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001991 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001992 } else if (quick_code == nullptr && !method->IsNative()) {
1993 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001994 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001995 *quick_is_interpreted = true;
1996 } else {
1997 CHECK(!method->GetDeclaringClass()->IsInitialized());
1998 // We have code for a static method, but need to go through the resolution stub for class
1999 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002000 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2001 }
2002 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002003 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002004 }
2005 return quick_code;
2006}
2007
Jeff Haodcdc85b2015-12-04 14:06:18 -08002008void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2009 ArtMethod* copy,
2010 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002011 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002012
2013 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002014
2015 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002016 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002017 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002018 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002019
Ian Rogers848871b2013-08-05 10:56:33 -07002020 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2021 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002022
Ian Rogers848871b2013-08-05 10:56:33 -07002023 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002024 Runtime* runtime = Runtime::Current();
2025 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002026 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002027 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002028 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
2029 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002030 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002031 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002032 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
2033 bool found_one = false;
2034 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2035 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2036 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2037 found_one = true;
2038 break;
2039 }
2040 }
2041 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2042 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002043 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002044 // We assume all methods have code. If they don't currently then we set them to the use the
2045 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2046 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002047 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002048 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002049 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002050 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002051 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002052 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002053 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002054
Sebastien Hertze1d07812014-05-21 15:44:09 +02002055 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002056 if (orig->IsNative()) {
2057 // The native method's pointer is set to a stub to lookup via dlsym.
2058 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002059 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002060 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002061 }
2062 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002063 }
2064}
2065
Jeff Haodcdc85b2015-12-04 14:06:18 -08002066size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002067 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002068 return std::accumulate(&image_info.bin_slot_sizes_[0],
2069 &image_info.bin_slot_sizes_[up_to],
2070 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002071}
2072
2073ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2074 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002075 static_assert(kBinBits == 3, "wrong number of bin bits");
2076 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002077 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2078
2079 DCHECK_LT(GetBin(), kBinSize);
2080 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2081}
2082
2083ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2084 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2085 DCHECK_EQ(index, GetIndex());
2086}
2087
2088ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2089 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2090}
2091
2092uint32_t ImageWriter::BinSlot::GetIndex() const {
2093 return lockword_ & ~kBinMask;
2094}
2095
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002096ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2097 switch (type) {
2098 case kNativeObjectRelocationTypeArtField:
2099 case kNativeObjectRelocationTypeArtFieldArray:
2100 return kBinArtField;
2101 case kNativeObjectRelocationTypeArtMethodClean:
2102 case kNativeObjectRelocationTypeArtMethodArrayClean:
2103 return kBinArtMethodClean;
2104 case kNativeObjectRelocationTypeArtMethodDirty:
2105 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2106 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002107 case kNativeObjectRelocationTypeDexCacheArray:
2108 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002109 }
2110 UNREACHABLE();
2111}
2112
Vladimir Marko944da602016-02-19 12:27:55 +00002113size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002114 if (compile_app_image_) {
Vladimir Marko944da602016-02-19 12:27:55 +00002115 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002116 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002117 mirror::DexCache* dex_cache =
2118 obj->IsDexCache() ? obj->AsDexCache()
2119 : obj->IsClass() ? obj->AsClass()->GetDexCache()
2120 : obj->GetClass()->GetDexCache();
2121 return GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002122 }
2123}
2124
Vladimir Marko944da602016-02-19 12:27:55 +00002125size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
2126 if (compile_app_image_) {
2127 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002128 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002129 auto it = dex_file_oat_index_map_.find(dex_file);
2130 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002131 return it->second;
2132 }
2133}
2134
Vladimir Marko944da602016-02-19 12:27:55 +00002135size_t ImageWriter::GetOatIndexForDexCache(mirror::DexCache* dex_cache) const {
2136 if (dex_cache == nullptr) {
2137 return GetDefaultOatIndex();
2138 } else {
2139 return GetOatIndexForDexFile(dex_cache->GetDexFile());
2140 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002141}
2142
Vladimir Marko944da602016-02-19 12:27:55 +00002143void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2144 size_t oat_loaded_size,
2145 size_t oat_data_offset,
2146 size_t oat_data_size) {
2147 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2148 for (const ImageInfo& info : image_infos_) {
2149 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2150 }
2151 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002152
Vladimir Marko944da602016-02-19 12:27:55 +00002153 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2154 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2155 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2156 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2157 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002158
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002159 if (compile_app_image_) {
2160 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2161 return;
2162 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002163
2164 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002165 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002166 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002167 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002168 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2169 }
2170}
2171
Vladimir Marko944da602016-02-19 12:27:55 +00002172void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2173 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2174 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2175
2176 if (oat_index == GetDefaultOatIndex()) {
2177 // Primary oat file, read the trampolines.
2178 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2179 oat_header.GetInterpreterToInterpreterBridgeOffset();
2180 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2181 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2182 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2183 oat_header.GetJniDlsymLookupOffset();
2184 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2185 oat_header.GetQuickGenericJniTrampolineOffset();
2186 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2187 oat_header.GetQuickImtConflictTrampolineOffset();
2188 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2189 oat_header.GetQuickResolutionTrampolineOffset();
2190 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2191 oat_header.GetQuickToInterpreterBridgeOffset();
2192 }
2193}
2194
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002195ImageWriter::ImageWriter(
2196 const CompilerDriver& compiler_driver,
2197 uintptr_t image_begin,
2198 bool compile_pic,
2199 bool compile_app_image,
2200 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002201 const std::vector<const char*>& oat_filenames,
2202 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002203 : compiler_driver_(compiler_driver),
2204 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2205 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002206 compile_pic_(compile_pic),
2207 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002208 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002209 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002210 image_method_array_(ImageHeader::kImageMethodsCount),
2211 dirty_methods_(0u),
2212 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002213 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002214 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002215 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002216 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002217 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002218 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2219 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002220}
2221
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002222ImageWriter::ImageInfo::ImageInfo()
2223 : intern_table_(new InternTable),
2224 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002225
Brian Carlstrom7940e442013-07-12 13:46:57 -07002226} // namespace art