blob: 97ad9b33772aaedc94264708ea6c8a0c26b8e5a8 [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>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
Ian Rogers700a4022014-05-19 16:49:03 -070022#include <memory>
Vladimir Marko20f85592015-03-19 10:07:02 +000023#include <numeric>
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080024#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070025#include <vector>
26
Mathieu Chartierc7853442015-03-27 14:35:38 -070027#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070028#include "art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070029#include "base/logging.h"
30#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010031#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "compiled_method.h"
33#include "dex_file-inl.h"
34#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070035#include "elf_file.h"
36#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070037#include "elf_writer.h"
38#include "gc/accounting/card_table-inl.h"
39#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070040#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "gc/heap.h"
42#include "gc/space/large_object_space.h"
43#include "gc/space/space-inl.h"
44#include "globals.h"
45#include "image.h"
46#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070047#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070048#include "lock_word.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070049#include "mirror/abstract_method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "mirror/array-inl.h"
51#include "mirror/class-inl.h"
52#include "mirror/class_loader.h"
53#include "mirror/dex_cache-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070054#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "mirror/object-inl.h"
56#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070057#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "oat.h"
59#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070060#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "runtime.h"
62#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070063#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000064#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070066using ::art::mirror::Class;
67using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070068using ::art::mirror::Object;
69using ::art::mirror::ObjectArray;
70using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070071
72namespace art {
73
Igor Murashkinf5b4c502014-11-14 15:01:59 -080074// Separate objects into multiple bins to optimize dirty memory use.
75static constexpr bool kBinObjects = true;
76
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080077// Return true if an object is already in an image space.
78bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080079 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080080 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080081 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080082 return false;
83 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080084 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
85 const uint8_t* image_begin = boot_image_space->Begin();
86 // Real image end including ArtMethods and ArtField sections.
87 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
88 if (image_begin <= obj && obj < image_end) {
89 return true;
90 }
91 }
92 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080093}
94
95bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080096 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080097 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080098 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080099 return false;
100 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800101 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
102 const ImageHeader& image_header = boot_image_space->GetImageHeader();
103 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
104 return true;
105 }
106 }
107 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800108}
109
Andreas Gampedd9d0552015-03-09 12:57:41 -0700110static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700111 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700112 Class* klass = obj->GetClass();
113 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
114}
115
116static void CheckNoDexObjects() {
117 ScopedObjectAccess soa(Thread::Current());
118 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
119}
120
Vladimir Markof4da6752014-08-01 19:04:18 +0100121bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800122 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800123 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100124 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700125 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100126 PruneNonImageClasses(); // Remove junk
127 ComputeLazyFieldsForImageClasses(); // Add useful information
Vladimir Markof4da6752014-08-01 19:04:18 +0100128 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100129 heap->CollectGarbage(false); // Remove garbage.
130
Andreas Gampedd9d0552015-03-09 12:57:41 -0700131 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
132 // dex files.
133 //
134 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
135 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
136 // true.
137 if (kIsDebugBuild) {
138 CheckNoDexObjects();
139 }
140
Vladimir Markof4da6752014-08-01 19:04:18 +0100141 if (kIsDebugBuild) {
142 ScopedObjectAccess soa(Thread::Current());
143 CheckNonImageClassesRemoved();
144 }
145
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700146 {
147 ScopedObjectAccess soa(Thread::Current());
148 CalculateNewObjectOffsets();
149 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100150
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700151 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
152 // bin size sums being calculated.
153 if (!AllocMemory()) {
154 return false;
155 }
156
Vladimir Markof4da6752014-08-01 19:04:18 +0100157 return true;
158}
159
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700160bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800161 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000162 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800163 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
164 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800165 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800166 if (image_fd != kInvalidFd) {
167 CHECK_EQ(image_filenames.size(), 1u);
168 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800169 CHECK(!oat_filenames.empty());
170 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700171
Vladimir Marko944da602016-02-19 12:27:55 +0000172 {
173 ScopedObjectAccess soa(Thread::Current());
174 for (size_t i = 0; i < oat_filenames.size(); ++i) {
175 CreateHeader(i);
176 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800177 }
178 }
Alex Light53cb16b2014-06-12 11:26:29 -0700179
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700180 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700181 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800182 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700183 Runtime::Current()->GetHeap()->DisableObjectValidation();
184 CopyAndFixupObjects();
185 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700186
Jeff Haodcdc85b2015-12-04 14:06:18 -0800187 for (size_t i = 0; i < image_filenames.size(); ++i) {
188 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000189 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800190 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800191 if (image_fd != kInvalidFd) {
192 if (strlen(image_filename) == 0u) {
193 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800194 // Empty the file in case it already exists.
195 if (image_file != nullptr) {
196 TEMP_FAILURE_RETRY(image_file->SetLength(0));
197 TEMP_FAILURE_RETRY(image_file->Flush());
198 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800199 } else {
200 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
201 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800202 } else {
203 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800204 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800205
Jeff Haodcdc85b2015-12-04 14:06:18 -0800206 if (image_file == nullptr) {
207 LOG(ERROR) << "Failed to open image file " << image_filename;
208 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800209 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800210
211 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800212 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
213 image_file->Erase();
214 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800215 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800216
Jeff Haodcdc85b2015-12-04 14:06:18 -0800217 std::unique_ptr<char[]> compressed_data;
218 // Image data size excludes the bitmap and the header.
219 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
220 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
221 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
222 size_t data_size;
223 const char* image_data_to_write;
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000224
Jeff Haodcdc85b2015-12-04 14:06:18 -0800225 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
226 switch (image_storage_mode_) {
227 case ImageHeader::kStorageModeLZ4: {
228 size_t compressed_max_size = LZ4_compressBound(image_data_size);
229 compressed_data.reset(new char[compressed_max_size]);
230 data_size = LZ4_compress(
231 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
232 &compressed_data[0],
233 image_data_size);
234 image_data_to_write = &compressed_data[0];
235 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size;
236 break;
237 }
238 case ImageHeader::kStorageModeUncompressed: {
239 data_size = image_data_size;
240 image_data_to_write = image_data;
241 break;
242 }
243 default: {
244 LOG(FATAL) << "Unsupported";
245 UNREACHABLE();
246 }
247 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800248
Jeff Haodcdc85b2015-12-04 14:06:18 -0800249 // Write header first, as uncompressed.
250 image_header->data_size_ = data_size;
251 if (!image_file->WriteFully(image_info.image_->Begin(), sizeof(ImageHeader))) {
252 PLOG(ERROR) << "Failed to write image file header " << image_filename;
253 image_file->Erase();
254 return false;
255 }
256
257 // Write out the image + fields + methods.
258 const bool is_compressed = compressed_data != nullptr;
259 if (!image_file->WriteFully(image_data_to_write, data_size)) {
260 PLOG(ERROR) << "Failed to write image file data " << image_filename;
261 image_file->Erase();
262 return false;
263 }
264
265 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
266 // convenience.
267 const ImageSection& bitmap_section = image_header->GetImageSection(
268 ImageHeader::kSectionImageBitmap);
269 // Align up since data size may be unaligned if the image is compressed.
270 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
271 if (!is_compressed) {
272 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
273 }
274 if (!image_file->Write(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
275 bitmap_section.Size(),
276 bitmap_position_in_file)) {
277 PLOG(ERROR) << "Failed to write image file " << image_filename;
278 image_file->Erase();
279 return false;
280 }
281 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
282 static_cast<size_t>(image_file->GetLength()));
283 if (image_file->FlushCloseOrErase() != 0) {
284 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
285 return false;
286 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800287 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700288 return true;
289}
290
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700291void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700292 DCHECK(object != nullptr);
293 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800294
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800295 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700296 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700297 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700298 DCHECK(IsImageOffsetAssigned(object));
299}
300
Mathieu Chartiere401d142015-04-22 13:56:20 -0700301void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
302 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
303 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
304 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
305}
306
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800307void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700308 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800309 DCHECK_NE(image_objects_offset_begin_, 0u);
310
Vladimir Marko944da602016-02-19 12:27:55 +0000311 size_t oat_index = GetOatIndex(object);
312 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800313 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100314 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800315 DCHECK_ALIGNED(new_offset, kObjectAlignment);
316
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700317 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800318 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700319}
320
Ian Rogersef7d42f2014-01-06 12:55:46 -0800321bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800322 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700323 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700324 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700325}
326
Ian Rogersef7d42f2014-01-06 12:55:46 -0800327size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700328 DCHECK(object != nullptr);
329 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700330 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700331 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000332 size_t oat_index = GetOatIndex(object);
333 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800334 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700335 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700336}
337
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800338void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
339 DCHECK(object != nullptr);
340 DCHECK(!IsImageOffsetAssigned(object));
341 DCHECK(!IsImageBinSlotAssigned(object));
342
343 // Before we stomp over the lock word, save the hash code for later.
344 Monitor::Deflate(Thread::Current(), object);;
345 LockWord lw(object->GetLockWord(false));
346 switch (lw.GetState()) {
347 case LockWord::kFatLocked: {
348 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
349 break;
350 }
351 case LockWord::kThinLocked: {
352 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
353 break;
354 }
355 case LockWord::kUnlocked:
356 // No hash, don't need to save it.
357 break;
358 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700359 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
360 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800361 break;
362 default:
363 LOG(FATAL) << "Unreachable.";
364 UNREACHABLE();
365 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700366 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700367 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800368 DCHECK(IsImageBinSlotAssigned(object));
369}
370
Vladimir Marko20f85592015-03-19 10:07:02 +0000371void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000372 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000373 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
374 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800375 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000376 auto it = dex_file_oat_index_map_.find(dex_file);
377 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800378 ImageInfo& image_info = GetImageInfo(it->second);
379 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
380 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
381 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
382 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000383
Vladimir Marko20f85592015-03-19 10:07:02 +0000384 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700385 Thread* const self = Thread::Current();
386 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800387 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700388 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800389 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800390 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700391 continue;
392 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000393 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700394 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000395 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000396 size_t oat_index = GetOatIndexForDexCache(dex_cache);
397 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800398 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100399 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800400 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
401 start + layout.TypesOffset(),
402 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100403 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800404 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
405 start + layout.MethodsOffset(),
406 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100407 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800408 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
409 start + layout.FieldsOffset(),
410 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100411 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800412 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000413 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000414}
415
Jeff Haodcdc85b2015-12-04 14:06:18 -0800416void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100417 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800418 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000419 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800420 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000421 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100422 }
423}
424
Mathieu Chartiere401d142015-04-22 13:56:20 -0700425void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
426 DCHECK(arr != nullptr);
427 if (kIsDebugBuild) {
428 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800429 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700430 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800431 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800432 CHECK(klass == nullptr || KeepClass(klass))
433 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700434 }
435 }
436 }
437 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
438 // ArtMethods.
439 pointer_arrays_.emplace(arr, kBinArtMethodClean);
440}
441
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800442void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
443 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800444 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800445
446 // The magic happens here. We segregate objects into different bins based
447 // on how likely they are to get dirty at runtime.
448 //
449 // Likely-to-dirty objects get packed together into the same bin so that
450 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
451 // maximized.
452 //
453 // This means more pages will stay either clean or shared dirty (with zygote) and
454 // the app will use less of its own (private) memory.
455 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000456 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800457
458 if (kBinObjects) {
459 //
460 // Changing the bin of an object is purely a memory-use tuning.
461 // It has no change on runtime correctness.
462 //
463 // Memory analysis has determined that the following types of objects get dirtied
464 // the most:
465 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000466 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
467 // a fixed layout which helps improve generated code (using PC-relative addressing),
468 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
469 // Since these arrays are huge, most pages do not overlap other objects and it's not
470 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100471 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800472 // * Class'es which are verified [their clinit runs only at runtime]
473 // - classes in general [because their static fields get overwritten]
474 // - initialized classes with all-final statics are unlikely to be ever dirty,
475 // so bin them separately
476 // * Art Methods that are:
477 // - native [their native entry point is not looked up until runtime]
478 // - have declaring classes that aren't initialized
479 // [their interpreter/quick entry points are trampolines until the class
480 // becomes initialized]
481 //
482 // We also assume the following objects get dirtied either never or extremely rarely:
483 // * Strings (they are immutable)
484 // * Art methods that aren't native and have initialized declared classes
485 //
486 // We assume that "regular" bin objects are highly unlikely to become dirtied,
487 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
488 //
489 if (object->IsClass()) {
490 bin = kBinClassVerified;
491 mirror::Class* klass = object->AsClass();
492
Mathieu Chartiere401d142015-04-22 13:56:20 -0700493 // Add non-embedded vtable to the pointer array table if there is one.
494 auto* vtable = klass->GetVTable();
495 if (vtable != nullptr) {
496 AddMethodPointerArray(vtable);
497 }
498 auto* iftable = klass->GetIfTable();
499 if (iftable != nullptr) {
500 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
501 if (iftable->GetMethodArrayCount(i) > 0) {
502 AddMethodPointerArray(iftable->GetMethodArray(i));
503 }
504 }
505 }
506
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800507 if (klass->GetStatus() == Class::kStatusInitialized) {
508 bin = kBinClassInitialized;
509
510 // If the class's static fields are all final, put it into a separate bin
511 // since it's very likely it will stay clean.
512 uint32_t num_static_fields = klass->NumStaticFields();
513 if (num_static_fields == 0) {
514 bin = kBinClassInitializedFinalStatics;
515 } else {
516 // Maybe all the statics are final?
517 bool all_final = true;
518 for (uint32_t i = 0; i < num_static_fields; ++i) {
519 ArtField* field = klass->GetStaticField(i);
520 if (!field->IsFinal()) {
521 all_final = false;
522 break;
523 }
524 }
525
526 if (all_final) {
527 bin = kBinClassInitializedFinalStatics;
528 }
529 }
530 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800531 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
532 bin = kBinString; // Strings are almost always immutable (except for object header).
533 } // else bin = kBinRegular
534 }
535
Vladimir Marko944da602016-02-19 12:27:55 +0000536 size_t oat_index = GetOatIndex(object);
537 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800538
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800539 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800540 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
541 // Move the current bin size up to accommodate the object we just assigned a bin slot.
542 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800543
544 BinSlot new_bin_slot(bin, current_offset);
545 SetImageBinSlot(object, new_bin_slot);
546
Jeff Haodcdc85b2015-12-04 14:06:18 -0800547 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800548
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800549 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800550 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800551}
552
Mathieu Chartiere401d142015-04-22 13:56:20 -0700553bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
554 if (m->IsNative()) {
555 return true;
556 }
557 mirror::Class* declaring_class = m->GetDeclaringClass();
558 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
559 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
560}
561
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800562bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
563 DCHECK(object != nullptr);
564
565 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
566 // If it's in some other state, then we haven't yet assigned an image bin slot.
567 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
568 return false;
569 } else if (kIsDebugBuild) {
570 LockWord lock_word = object->GetLockWord(false);
571 size_t offset = lock_word.ForwardingAddress();
572 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000573 size_t oat_index = GetOatIndex(object);
574 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800575 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800576 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800577 }
578 return true;
579}
580
581ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
582 DCHECK(object != nullptr);
583 DCHECK(IsImageBinSlotAssigned(object));
584
585 LockWord lock_word = object->GetLockWord(false);
586 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
587 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
588
589 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000590 size_t oat_index = GetOatIndex(object);
591 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800592 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800593
594 return bin_slot;
595}
596
Brian Carlstrom7940e442013-07-12 13:46:57 -0700597bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000598 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800599 ImageSection unused_sections[ImageHeader::kSectionCount];
600 const size_t length = RoundUp(
601 image_info.CreateImageSections(target_ptr_size_, unused_sections),
602 kPageSize);
603
Jeff Haodcdc85b2015-12-04 14:06:18 -0800604 std::string error_msg;
605 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
606 nullptr,
607 length,
608 PROT_READ | PROT_WRITE,
609 false,
610 false,
611 &error_msg));
612 if (UNLIKELY(image_info.image_.get() == nullptr)) {
613 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
614 return false;
615 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700616
Jeff Haodcdc85b2015-12-04 14:06:18 -0800617 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
618 CHECK_LE(image_info.image_end_, length);
619 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
620 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
621 if (image_info.image_bitmap_.get() == nullptr) {
622 LOG(ERROR) << "Failed to allocate memory for image bitmap";
623 return false;
624 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700625 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700626 return true;
627}
628
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700629class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
630 public:
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800631 bool operator()(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700632 StackHandleScope<1> hs(Thread::Current());
633 mirror::Class::ComputeName(hs.NewHandle(c));
634 return true;
635 }
636};
637
Brian Carlstrom7940e442013-07-12 13:46:57 -0700638void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700639 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700640 ComputeLazyFieldsForClassesVisitor visitor;
641 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700642}
643
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800644static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
645 return klass->GetClassLoader() == nullptr;
646}
647
648bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
649 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
650}
651
652bool ImageWriter::ContainsBootClassLoaderNonImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800653 bool early_exit = false;
654 std::unordered_set<mirror::Class*> visited;
655 return ContainsBootClassLoaderNonImageClassInternal(klass, &early_exit, &visited);
656}
657
658bool ImageWriter::ContainsBootClassLoaderNonImageClassInternal(
659 mirror::Class* klass,
660 bool* early_exit,
661 std::unordered_set<mirror::Class*>* visited) {
662 DCHECK(early_exit != nullptr);
663 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800664 DCHECK(compile_app_image_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700665 if (klass == nullptr) {
666 return false;
667 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800668 auto found = prune_class_memo_.find(klass);
669 if (found != prune_class_memo_.end()) {
670 // Already computed, return the found value.
671 return found->second;
672 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800673 // Circular dependencies, return false but do not store the result in the memoization table.
674 if (visited->find(klass) != visited->end()) {
675 *early_exit = true;
676 return false;
677 }
678 visited->emplace(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800679 bool result = IsBootClassLoaderNonImageClass(klass);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800680 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800681 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
682 // app image.
683 if (klass->GetStatus() == mirror::Class::kStatusError) {
684 result = true;
685 } else {
686 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
687 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800688 if (!result) {
689 // Check interfaces since these wont be visited through VisitReferences.)
690 mirror::IfTable* if_table = klass->GetIfTable();
691 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800692 result = result || ContainsBootClassLoaderNonImageClassInternal(
693 if_table->GetInterface(i),
694 &my_early_exit,
695 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800696 }
697 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800698 if (klass->IsObjectArrayClass()) {
699 result = result || ContainsBootClassLoaderNonImageClassInternal(
700 klass->GetComponentType(),
701 &my_early_exit,
702 visited);
703 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800704 // Check static fields and their classes.
705 size_t num_static_fields = klass->NumReferenceStaticFields();
706 if (num_static_fields != 0 && klass->IsResolved()) {
707 // Presumably GC can happen when we are cross compiling, it should not cause performance
708 // problems to do pointer size logic.
709 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
710 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
711 for (size_t i = 0u; i < num_static_fields; ++i) {
712 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
713 if (ref != nullptr) {
714 if (ref->IsClass()) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800715 result = result ||
716 ContainsBootClassLoaderNonImageClassInternal(
717 ref->AsClass(),
718 &my_early_exit,
719 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800720 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800721 result = result ||
722 ContainsBootClassLoaderNonImageClassInternal(
723 ref->GetClass(),
724 &my_early_exit,
725 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800726 }
727 field_offset = MemberOffset(field_offset.Uint32Value() +
728 sizeof(mirror::HeapReference<mirror::Object>));
729 }
730 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800731 result = result ||
732 ContainsBootClassLoaderNonImageClassInternal(
733 klass->GetSuperClass(),
734 &my_early_exit,
735 visited);
736 // Erase the element we stored earlier since we are exiting the function.
737 auto it = visited->find(klass);
738 DCHECK(it != visited->end());
739 visited->erase(it);
740 // Only store result if it is true or none of the calls early exited due to circular
741 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
742 // a child call and we can remember the result.
743 if (result == true || !my_early_exit || visited->empty()) {
744 prune_class_memo_[klass] = result;
745 }
746 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800747 return result;
748}
749
750bool ImageWriter::KeepClass(Class* klass) {
751 if (klass == nullptr) {
752 return false;
753 }
754 if (compile_app_image_) {
755 // For app images, we need to prune boot loader classes that are not in the boot image since
756 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800757 // Keep classes in the boot image space since we don't want to re-resolve these.
758 return Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass) ||
759 !ContainsBootClassLoaderNonImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800760 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700761 std::string temp;
762 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700763}
764
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700765class NonImageClassesVisitor : public ClassVisitor {
766 public:
767 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
768
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800769 bool operator()(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800770 if (!image_writer_->KeepClass(klass)) {
771 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700772 }
773 return true;
774 }
775
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800776 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700777 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700778};
779
780void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700781 Runtime* runtime = Runtime::Current();
782 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700783 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700784
785 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700786 NonImageClassesVisitor visitor(this);
787 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700788
789 // Remove the undesired classes from the class roots.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800790 for (mirror::Class* klass : visitor.classes_to_prune_) {
791 std::string temp;
792 const char* name = klass->GetDescriptor(&temp);
793 VLOG(compiler) << "Pruning class " << name;
794 if (!compile_app_image_) {
795 DCHECK(IsBootClassLoaderClass(klass));
796 }
797 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800798 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700799 }
800
801 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100802 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700803
804 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
805 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
806 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800807 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
808 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700809 if (dex_cache == nullptr) {
810 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700811 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700812 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
813 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800814 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700815 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700816 }
817 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100818 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
819 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
820 ArtMethod* method =
821 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800822 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
823 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800824 // 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 -0800825 // declaring class which is an image class. Set it to the resolution method to be safe and
826 // prevent dangling pointers.
Alex Lightfcea56f2016-02-17 11:59:05 -0800827 if (method->MightBeCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800828 mirror::DexCache::SetElementPtrSize(resolved_methods,
829 i,
830 resolution_method,
831 target_ptr_size_);
832 } else {
833 // Check that the class is still in the classes table.
834 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
835 << PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700836 }
837 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800838 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700839 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800840 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800841 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700842 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700843 }
844 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700845 // Clean the dex field. It might have been populated during the initialization phase, but
846 // contains data only valid during a real run.
847 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700848 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700849
850 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
851 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800852
853 // Clear to save RAM.
854 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700855}
856
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800857void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700858 if (compiler_driver_.GetImageClasses() != nullptr) {
859 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700860 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700861 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700862}
863
864void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
865 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800866 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700867 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800868 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700869 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700870 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800871 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
872 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700873 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700874 }
875}
876
877void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700878 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700879 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700880 for (const std::string& image_class : *image_classes) {
881 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700882 }
883}
884
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800885mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
886 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +0000887 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800888 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
889 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
890 << string->ToModifiedUtf8();
891 if (found != nullptr) {
892 return found;
893 }
894 }
895 if (compile_app_image_) {
896 Runtime* const runtime = Runtime::Current();
897 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
898 // If we found it in the runtime intern table it could either be in the boot image or interned
899 // during app image compilation. If it was in the boot image return that, otherwise return null
900 // since it belongs to another image space.
901 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
902 return found;
903 }
904 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
905 << string->ToModifiedUtf8();
906 }
907 return nullptr;
908}
909
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800910void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700911 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700912 // if it is a string, we want to intern it if its not interned.
913 if (obj->GetClass()->IsStringClass()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000914 size_t oat_index = GetOatIndex(obj);
915 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800916
Brian Carlstrom7940e442013-07-12 13:46:57 -0700917 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800918 if (IsImageBinSlotAssigned(obj)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800919 DCHECK_EQ(obj, FindInternedString(obj->AsString()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700920 return;
921 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800922 // Need to check if the string is already interned in another image info so that we don't have
923 // the intern tables of two different images contain the same string.
924 mirror::String* interned = FindInternedString(obj->AsString());
925 if (interned == nullptr) {
926 // Not in another image space, insert to our table.
927 interned = image_info.intern_table_->InternStrongImageString(obj->AsString());
928 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700929 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800930 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700931 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800932 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700933 }
934 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800935 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700936 return;
937 }
938 // else (obj == interned), nothing to do but fall through to the normal case
939 }
940
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800941 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700942}
943
Vladimir Marko944da602016-02-19 12:27:55 +0000944ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700945 Runtime* runtime = Runtime::Current();
946 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700947 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700948 StackHandleScope<3> hs(self);
949 Handle<Class> object_array_class(hs.NewHandle(
950 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700951
Jeff Haodcdc85b2015-12-04 14:06:18 -0800952 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +0000953 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800954 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +0000955 size_t image_oat_index = pair.second;
956 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800957 image_dex_files.insert(image_dex_file);
958 }
959 }
960
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700961 // build an Object[] of all the DexCaches used in the source_space_.
962 // Since we can't hold the dex lock when allocating the dex_caches
963 // ObjectArray, we lock the dex lock twice, first to get the number
964 // of dex caches first and then lock it again to copy the dex
965 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800966 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700967 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700968 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800969 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800970 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
971 mirror::DexCache* dex_cache =
972 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800973 const DexFile* dex_file = dex_cache->GetDexFile();
974 if (!IsInBootImage(dex_cache)) {
975 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
976 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800977 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700978 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700979 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800980 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700981 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
982 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700983 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800984 size_t non_image_dex_caches = 0;
985 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800986 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
987 mirror::DexCache* dex_cache =
988 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800989 const DexFile* dex_file = dex_cache->GetDexFile();
990 if (!IsInBootImage(dex_cache)) {
991 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
992 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800993 }
994 CHECK_EQ(dex_cache_count, non_image_dex_caches)
995 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700996 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800997 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
998 mirror::DexCache* dex_cache =
999 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001000 const DexFile* dex_file = dex_cache->GetDexFile();
1001 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001002 dex_caches->Set<false>(i, dex_cache);
1003 ++i;
1004 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001005 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001006 }
1007
1008 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001009 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001010 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001011 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001012 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001013 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001014 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001015 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001016 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001017}
1018
Mathieu Chartier590fee92013-09-13 13:46:47 -07001019// Walk instance fields of the given Class. Separate function to allow recursion on the super
1020// class.
1021void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1022 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001023 StackHandleScope<1> hs(Thread::Current());
1024 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1025 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001026 if (super != nullptr) {
1027 WalkInstanceFields(obj, super);
1028 }
1029 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001030 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +00001031 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001032 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001033 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001034 if (value != nullptr) {
1035 WalkFieldsInOrder(value);
1036 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001037 field_offset = MemberOffset(field_offset.Uint32Value() +
1038 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001039 }
1040}
1041
1042// For an unvisited object, visit it then all its children found via fields.
1043void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001044 if (IsInBootImage(obj)) {
1045 // Object is in the image, don't need to fix it up.
1046 return;
1047 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001048 // Use our own visitor routine (instead of GC visitor) to get better locality between
1049 // an object and its fields
1050 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001051 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001052 StackHandleScope<2> hs(Thread::Current());
1053 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1054 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001055 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001056 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001057 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001058 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001059 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001060 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001061 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001062 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001063 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001064 if (value != nullptr) {
1065 WalkFieldsInOrder(value);
1066 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001067 field_offset = MemberOffset(field_offset.Uint32Value() +
1068 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001069 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001070 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001071 auto* as_klass = h_obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001072 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001073 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1074 if (compile_app_image_) {
1075 // Extra sanity, no boot loader classes should be left!
1076 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1077 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001078 LengthPrefixedArray<ArtField>* fields[] = {
1079 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1080 };
Vladimir Marko944da602016-02-19 12:27:55 +00001081 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1082 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001083 {
1084 // Note: This table is only accessed from the image writer, so the lock is technically
1085 // unnecessary.
1086 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1087 // Insert in the class table for this iamge.
1088 image_info.class_table_->Insert(as_klass);
1089 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001090 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1091 // Total array length including header.
1092 if (cur_fields != nullptr) {
1093 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1094 // Forward the entire array at once.
1095 auto it = native_object_relocations_.find(cur_fields);
1096 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1097 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001098 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001099 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001100 native_object_relocations_.emplace(
1101 cur_fields,
1102 NativeObjectRelocation {
1103 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1104 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001105 offset += header_size;
1106 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001107 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001108 // Need to forward arrays separate of fields.
1109 ArtField* field = &cur_fields->At(i);
1110 auto it2 = native_object_relocations_.find(field);
1111 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1112 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001113 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001114 native_object_relocations_.emplace(
1115 field,
1116 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001117 offset += sizeof(ArtField);
1118 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001119 }
1120 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001121 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001122 size_t num_methods = as_klass->NumMethods();
1123 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001124 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001125 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1126 if (WillMethodBeDirty(&m)) {
1127 any_dirty = true;
1128 break;
1129 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001130 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001131 NativeObjectRelocationType type = any_dirty
1132 ? kNativeObjectRelocationTypeArtMethodDirty
1133 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001134 Bin bin_type = BinTypeForNativeRelocationType(type);
1135 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001136 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1137 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001138 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1139 method_size,
1140 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001141 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001142 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001143 CHECK(it == native_object_relocations_.end())
1144 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001145 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001146 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001147 native_object_relocations_.emplace(array,
1148 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001149 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001150 offset,
1151 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1152 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001153 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001154 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001155 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001156 }
Alex Lighte64300b2015-12-15 15:02:47 -08001157 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001158 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001159 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001160 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001161 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001162 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001163 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001164 mirror::Object* value = obj_array->Get(i);
1165 if (value != nullptr) {
1166 WalkFieldsInOrder(value);
1167 }
1168 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001169 } else if (h_obj->IsClassLoader()) {
1170 // Register the class loader if it has a class table.
1171 // The fake boot class loader should not get registered and we should end up with only one
1172 // class loader.
1173 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1174 if (class_loader->GetClassTable() != nullptr) {
1175 class_loaders_.insert(class_loader);
1176 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001177 }
1178 }
1179}
1180
Jeff Haodcdc85b2015-12-04 14:06:18 -08001181void ImageWriter::AssignMethodOffset(ArtMethod* method,
1182 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001183 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001184 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001185 auto it = native_object_relocations_.find(method);
1186 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001187 << PrettyMethod(method);
Vladimir Marko944da602016-02-19 12:27:55 +00001188 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001189 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001190 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001191 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001192}
1193
Mathieu Chartier590fee92013-09-13 13:46:47 -07001194void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1195 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1196 DCHECK(writer != nullptr);
1197 writer->WalkFieldsInOrder(obj);
1198}
1199
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001200void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1201 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1202 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001203 if (!writer->IsInBootImage(obj)) {
1204 writer->UnbinObjectsIntoOffset(obj);
1205 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001206}
1207
1208void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001209 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001210 CHECK(obj != nullptr);
1211
1212 // We know the bin slot, and the total bin sizes for all objects by now,
1213 // so calculate the object's final image offset.
1214
1215 DCHECK(IsImageBinSlotAssigned(obj));
1216 BinSlot bin_slot = GetImageBinSlot(obj);
1217 // Change the lockword from a bin slot into an offset
1218 AssignImageOffset(obj, bin_slot);
1219}
1220
Vladimir Markof4da6752014-08-01 19:04:18 +01001221void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001222 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001223 StackHandleScopeCollection handles(self);
1224 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001225 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1226 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001227 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001228
Mathieu Chartiere401d142015-04-22 13:56:20 -07001229 auto* runtime = Runtime::Current();
1230 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001231
Mathieu Chartier31e89252013-08-28 11:29:12 -07001232 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001233 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001234 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001235
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001236 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1237 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001238 // Write the image runtime methods.
1239 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1240 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1241 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1242 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1243 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1244 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1245 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1246 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001247
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001248 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001249 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1250 auto it = native_object_relocations_.find(&image_method_array_);
1251 CHECK(it == native_object_relocations_.end());
Vladimir Marko944da602016-02-19 12:27:55 +00001252 ImageInfo& default_image_info = GetImageInfo(GetDefaultOatIndex());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001253 size_t& offset =
1254 default_image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001255 if (!compile_app_image_) {
1256 native_object_relocations_.emplace(&image_method_array_,
Vladimir Marko944da602016-02-19 12:27:55 +00001257 NativeObjectRelocation { GetDefaultOatIndex(), offset, image_method_type });
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001258 }
Vladimir Marko14632852015-08-17 12:07:23 +01001259 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001260 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001261 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001262 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001263 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001264 for (auto* m : image_methods_) {
1265 CHECK(m != nullptr);
1266 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001267 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1268 if (!IsInBootImage(m)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001269 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001270 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001271 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001272 // Calculate size of the dex cache arrays slot and prepare offsets.
1273 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001274
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001275 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001276 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001277 // Calculate how big the intern table will be after being serialized.
1278 InternTable* const intern_table = image_info.intern_table_.get();
1279 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1280 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001281 // Calculate the size of the class table.
1282 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1283 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001284 }
1285
Vladimir Markocf36d492015-08-12 19:27:26 +01001286 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001287 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001288 size_t bin_offset = image_objects_offset_begin_;
1289 for (size_t i = 0; i != kBinSize; ++i) {
1290 image_info.bin_slot_offsets_[i] = bin_offset;
1291 bin_offset += image_info.bin_slot_sizes_[i];
1292 if (i == kBinArtField) {
1293 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1294 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1295 DCHECK_ALIGNED(bin_offset, 4u);
1296 DCHECK(method_alignment == 4u || method_alignment == 8u);
1297 bin_offset = RoundUp(bin_offset, method_alignment);
1298 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001299 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001300 // NOTE: There may be additional padding between the bin slots and the intern table.
1301 DCHECK_EQ(image_info.image_end_,
1302 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001303 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001304
Jeff Haodcdc85b2015-12-04 14:06:18 -08001305 // Calculate image offsets.
1306 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001307 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001308 image_info.image_begin_ = global_image_begin_ + image_offset;
1309 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001310 ImageSection unused_sections[ImageHeader::kSectionCount];
1311 image_info.image_size_ = RoundUp(
1312 image_info.CreateImageSections(target_ptr_size_, unused_sections),
1313 kPageSize);
1314 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001315 image_offset += image_info.image_size_;
1316 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001317
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001318 // Transform each object's bin slot into an offset which will be used to do the final copy.
1319 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001320
Jeff Haodcdc85b2015-12-04 14:06:18 -08001321 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001322
Jeff Haodcdc85b2015-12-04 14:06:18 -08001323 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001324 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001325 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1326 i++;
1327 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001328
Mathieu Chartiere401d142015-04-22 13:56:20 -07001329 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001330 for (auto& pair : native_object_relocations_) {
1331 NativeObjectRelocation& relocation = pair.second;
1332 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001333 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001334 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001335 }
1336
Jeff Haodcdc85b2015-12-04 14:06:18 -08001337 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001338}
1339
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001340size_t ImageWriter::ImageInfo::CreateImageSections(size_t target_ptr_size,
1341 ImageSection* out_sections) const {
1342 DCHECK(out_sections != nullptr);
1343 // Objects section
1344 auto* objects_section = &out_sections[ImageHeader::kSectionObjects];
1345 *objects_section = ImageSection(0u, image_end_);
1346 size_t cur_pos = objects_section->End();
1347 // Add field section.
1348 auto* field_section = &out_sections[ImageHeader::kSectionArtFields];
1349 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
1350 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
1351 cur_pos = field_section->End();
1352 // Round up to the alignment the required by the method section.
1353 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size));
1354 // Add method section.
1355 auto* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1356 *methods_section = ImageSection(cur_pos,
1357 bin_slot_sizes_[kBinArtMethodClean] +
1358 bin_slot_sizes_[kBinArtMethodDirty]);
1359 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
1360 cur_pos = methods_section->End();
1361 // Add dex cache arrays section.
1362 auto* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1363 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1364 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1365 cur_pos = dex_cache_arrays_section->End();
1366 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1367 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1368 // Calculate the size of the interned strings.
1369 auto* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
1370 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1371 cur_pos = interned_strings_section->End();
1372 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1373 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1374 // Calculate the size of the class table section.
1375 auto* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001376 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001377 cur_pos = class_table_section->End();
1378 // Image end goes right before the start of the image bitmap.
1379 return cur_pos;
1380}
1381
Vladimir Marko944da602016-02-19 12:27:55 +00001382void ImageWriter::CreateHeader(size_t oat_index) {
1383 ImageInfo& image_info = GetImageInfo(oat_index);
1384 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1385 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1386 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001387
1388 // Create the image sections.
1389 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001390 const size_t image_end = image_info.CreateImageSections(target_ptr_size_, sections);
1391
Mathieu Chartiere401d142015-04-22 13:56:20 -07001392 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001393 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001394 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001395 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001396 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001397 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001398 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001399 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001400 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1401 ++idx;
1402 }
1403 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001404 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1405 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1406 << " Image offset=" << image_info.image_offset_ << std::dec;
1407 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1408 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1409 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1410 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001411 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001412 // Store boot image info for app image so that we can relocate.
1413 uint32_t boot_image_begin = 0;
1414 uint32_t boot_image_end = 0;
1415 uint32_t boot_oat_begin = 0;
1416 uint32_t boot_oat_end = 0;
1417 gc::Heap* const heap = Runtime::Current()->GetHeap();
1418 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001419
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001420 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1421 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001422 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1423 image_end,
1424 sections,
1425 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001426 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001427 PointerToLowMemUInt32(oat_file_begin),
1428 PointerToLowMemUInt32(image_info.oat_data_begin_),
1429 PointerToLowMemUInt32(oat_data_end),
1430 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001431 boot_image_begin,
1432 boot_image_end - boot_image_begin,
1433 boot_oat_begin,
1434 boot_oat_end - boot_oat_begin,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001435 target_ptr_size_,
1436 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001437 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001438 image_storage_mode_,
1439 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001440}
1441
1442ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001443 auto it = native_object_relocations_.find(method);
1444 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001445 size_t oat_index = GetOatIndex(method->GetDexCache());
1446 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001447 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1448 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001449}
1450
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001451class FixupRootVisitor : public RootVisitor {
1452 public:
1453 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1454 }
1455
1456 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001457 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001458 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001459 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001460 }
1461 }
1462
1463 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1464 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001465 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001466 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001467 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001468 }
1469 }
1470
1471 private:
1472 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001473};
1474
Vladimir Marko944da602016-02-19 12:27:55 +00001475void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
1476 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001477 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001478 for (auto& pair : native_object_relocations_) {
1479 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001480 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001481 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001482 continue;
1483 }
1484 auto* dest = image_info.image_->Begin() + relocation.offset;
1485 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001486 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001487 switch (relocation.type) {
1488 case kNativeObjectRelocationTypeArtField: {
1489 memcpy(dest, pair.first, sizeof(ArtField));
1490 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1491 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1492 break;
1493 }
1494 case kNativeObjectRelocationTypeArtMethodClean:
1495 case kNativeObjectRelocationTypeArtMethodDirty: {
1496 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001497 reinterpret_cast<ArtMethod*>(dest),
1498 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001499 break;
1500 }
1501 // For arrays, copy just the header since the elements will get copied by their corresponding
1502 // relocations.
1503 case kNativeObjectRelocationTypeArtFieldArray: {
1504 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1505 break;
1506 }
1507 case kNativeObjectRelocationTypeArtMethodArrayClean:
1508 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001509 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1510 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001511 ArtMethod::Size(target_ptr_size_),
1512 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001513 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001514 case kNativeObjectRelocationTypeDexCacheArray:
1515 // Nothing to copy here, everything is done in FixupDexCache().
1516 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001517 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001518 }
1519 }
1520 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001521 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001522 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001523 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001524 ArtMethod* method = image_methods_[i];
1525 CHECK(method != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001526 // Only place runtime methods in the image of the default oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001527 if (method->IsRuntimeMethod() && oat_index != GetDefaultOatIndex()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001528 continue;
1529 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001530 if (!IsInBootImage(method)) {
1531 auto it = native_object_relocations_.find(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001532 CHECK(it != native_object_relocations_.end()) << "No forwarding for " << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001533 NativeObjectRelocation& relocation = it->second;
1534 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1535 << methods_section;
1536 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001537 method = reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001538 }
1539 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001540 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001541 FixupRootVisitor root_visitor(this);
1542
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001543 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001544 if (image_info.intern_table_bytes_ > 0) {
1545 const ImageSection& intern_table_section = image_header->GetImageSection(
1546 ImageHeader::kSectionInternedStrings);
1547 InternTable* const intern_table = image_info.intern_table_.get();
1548 uint8_t* const intern_table_memory_ptr =
1549 image_info.image_->Begin() + intern_table_section.Offset();
1550 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1551 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1552 // Fixup the pointers in the newly written intern table to contain image addresses.
1553 InternTable temp_intern_table;
1554 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1555 // the VisitRoots() will update the memory directly rather than the copies.
1556 // This also relies on visit roots not doing any verification which could fail after we update
1557 // the roots to be the image addresses.
1558 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1559 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1560 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1561 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001562 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1563 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001564 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001565 const ImageSection& class_table_section = image_header->GetImageSection(
1566 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001567 uint8_t* const class_table_memory_ptr =
1568 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001569 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001570
1571 ClassTable* table = image_info.class_table_.get();
1572 CHECK(table != nullptr);
1573 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1574 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1575 // Fixup the pointers in the newly written class table to contain image addresses. See
1576 // above comment for intern tables.
1577 ClassTable temp_class_table;
1578 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1579 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1580 table->NumZygoteClasses());
1581 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1582 RootInfo(kRootUnknown));
1583 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001584 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001585}
1586
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001587void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001588 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001589 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1590 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001591 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001592 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001593 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1594 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001595 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001596 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001597}
1598
Mathieu Chartier590fee92013-09-13 13:46:47 -07001599void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001600 DCHECK(obj != nullptr);
1601 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001602 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1603}
1604
Mathieu Chartiere401d142015-04-22 13:56:20 -07001605void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1606 mirror::Class* klass, Bin array_type) {
1607 CHECK(klass->IsArrayClass());
1608 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1609 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001610 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001611 dst->SetClass(GetImageAddress(arr->GetClass()));
1612 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001613 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001614 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1615 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001616 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001617 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001618 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001619 auto* method = reinterpret_cast<ArtMethod*>(elem);
1620 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1621 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1622 << PrettyClass(method->GetDeclaringClass());
1623 } else {
1624 CHECK_EQ(array_type, kBinArtField);
1625 auto* field = reinterpret_cast<ArtField*>(elem);
1626 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1627 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1628 << PrettyClass(field->GetDeclaringClass());
1629 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001630 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001631 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001632 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001633 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001634 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001635 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001636 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001637 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001638}
1639
1640void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001641 if (IsInBootImage(obj)) {
1642 return;
1643 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001644 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001645 size_t oat_index = GetOatIndex(obj);
1646 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001647 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1648 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001649 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001650
Jeff Haodcdc85b2015-12-04 14:06:18 -08001651 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001652
1653 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001654 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001655 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001656
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001657 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1658 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001659 const auto it = saved_hashcode_map_.find(obj);
1660 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1661 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001662 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001663}
1664
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001665// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001666class FixupVisitor {
1667 public:
1668 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1669 }
1670
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001671 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1672 // with other logic.
1673 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1674 const {}
1675 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1676
1677
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001678 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001679 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001680 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001681 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1682 // image.
1683 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001684 offset,
1685 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001686 }
1687
1688 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001689 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001690 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001691 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001692 mirror::Reference::ReferentOffset(),
1693 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001694 }
1695
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001696 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001697 ImageWriter* const image_writer_;
1698 mirror::Object* const copy_;
1699};
1700
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001701class FixupClassVisitor FINAL : public FixupVisitor {
1702 public:
1703 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1704 }
1705
Mathieu Chartierc7853442015-03-27 14:35:38 -07001706 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001707 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001708 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001709 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001710 }
1711
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001712 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1713 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001714 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001715 LOG(FATAL) << "Reference not expected here.";
1716 }
1717};
1718
Vladimir Marko05792b92015-08-03 11:56:49 +01001719uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1720 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001721 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001722 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001723 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1724 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001725 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001726 return relocation.offset;
1727}
1728
1729template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001730T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001731 if (obj == nullptr || IsInBootImage(obj)) {
1732 return obj;
1733 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001734 auto it = native_object_relocations_.find(obj);
1735 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1736 << Runtime::Current()->GetHeap()->DumpSpaces();
1737 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00001738 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001739 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001740 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001741}
1742
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001743template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001744T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1745 if (obj == nullptr || IsInBootImage(obj)) {
1746 return obj;
1747 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001748 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1749 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001750 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1751 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001752}
1753
1754class NativeLocationVisitor {
1755 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001756 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001757
1758 template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001759 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001760 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001761 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001762
1763 private:
1764 ImageWriter* const image_writer_;
1765};
1766
1767void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001768 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001769 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001770 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001771
1772 // Remove the clinitThreadId. This is required for image determinism.
1773 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001774}
1775
Ian Rogersef7d42f2014-01-06 12:55:46 -08001776void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001777 DCHECK(orig != nullptr);
1778 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001779 if (kUseBakerOrBrooksReadBarrier) {
1780 orig->AssertReadBarrierPointer();
1781 if (kUseBrooksReadBarrier) {
1782 // Note the address 'copy' isn't the same as the image address of 'orig'.
1783 copy->SetReadBarrierPointer(GetImageAddress(orig));
1784 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1785 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001786 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001787 auto* klass = orig->GetClass();
1788 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001789 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001790 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1791 if (it != pointer_arrays_.end()) {
1792 // Should only need to fixup every pointer array exactly once.
1793 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1794 pointer_arrays_.erase(it);
1795 return;
1796 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001797 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001798 if (orig->IsClass()) {
1799 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001800 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001801 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1802 // Need to go update the ArtMethod.
1803 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1804 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1805 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001806 auto it = native_object_relocations_.find(src_method);
1807 CHECK(it != native_object_relocations_.end())
1808 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001809 dest->SetArtMethod(
Jeff Haodcdc85b2015-12-04 14:06:18 -08001810 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001811 } else if (!klass->IsArrayClass()) {
1812 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1813 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1814 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001815 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001816 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01001817 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1818 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001819 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001820 // Also set allocator to null to be safe. The allocator is created when we create the class
1821 // table. We also never expect to unload things in the image since they are held live as
1822 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001823 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001824 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001825 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001826 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001827 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001828 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001829}
1830
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001831
1832class ImageAddressVisitor {
1833 public:
1834 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1835
1836 template <typename T>
1837 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1838 return image_writer_->GetImageAddress(ptr);
1839 }
1840
1841 private:
1842 ImageWriter* const image_writer_;
1843};
1844
1845
Vladimir Marko05792b92015-08-03 11:56:49 +01001846void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1847 mirror::DexCache* copy_dex_cache) {
1848 // Though the DexCache array fields are usually treated as native pointers, we set the full
1849 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1850 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1851 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1852 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1853 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001854 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001855 NativeLocationInImage(orig_strings),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001856 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001857 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
1858 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001859 }
1860 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1861 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001862 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001863 NativeLocationInImage(orig_types),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001864 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001865 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
1866 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001867 }
1868 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1869 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001870 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001871 NativeLocationInImage(orig_methods),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001872 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001873 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001874 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1875 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001876 // NativeLocationInImage also handles runtime methods since these have relocation info.
1877 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001878 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1879 }
1880 }
1881 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1882 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001883 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001884 NativeLocationInImage(orig_fields),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001885 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001886 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001887 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1888 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001889 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001890 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1891 }
1892 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001893
1894 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
1895 // compiler pointers in here will make the output non-deterministic.
1896 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001897}
1898
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001899const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1900 DCHECK_LT(type, kOatAddressCount);
1901 // If we are compiling an app image, we need to use the stubs of the boot image.
1902 if (compile_app_image_) {
1903 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001904 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08001905 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1906 DCHECK(!image_spaces.empty());
1907 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001908 CHECK(oat_file != nullptr);
1909 const OatHeader& header = oat_file->GetOatHeader();
1910 switch (type) {
1911 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1912 case kOatAddressQuickGenericJNITrampoline:
1913 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1914 case kOatAddressInterpreterToInterpreterBridge:
1915 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1916 case kOatAddressInterpreterToCompiledCodeBridge:
1917 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1918 case kOatAddressJNIDlsymLookup:
1919 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1920 case kOatAddressQuickIMTConflictTrampoline:
1921 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1922 case kOatAddressQuickResolutionTrampoline:
1923 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1924 case kOatAddressQuickToInterpreterBridge:
1925 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1926 default:
1927 UNREACHABLE();
1928 }
1929 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001930 const ImageInfo& primary_image_info = GetImageInfo(0);
1931 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001932}
1933
Jeff Haodcdc85b2015-12-04 14:06:18 -08001934const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
1935 const ImageInfo& image_info,
1936 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001937 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
1938 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
1939 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07001940 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001941 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001942
1943 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1944 // trampoline.
1945
1946 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001947 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1948 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001949 const uint8_t* quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001950 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001951 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
1952 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001953 // We have code for a non-static or initialized method, just use the code.
1954 } else if (quick_code == nullptr && method->IsNative() &&
1955 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1956 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001957 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001958 } else if (quick_code == nullptr && !method->IsNative()) {
1959 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001960 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001961 *quick_is_interpreted = true;
1962 } else {
1963 CHECK(!method->GetDeclaringClass()->IsInitialized());
1964 // We have code for a static method, but need to go through the resolution stub for class
1965 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001966 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
1967 }
1968 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001969 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001970 }
1971 return quick_code;
1972}
1973
Jeff Haodcdc85b2015-12-04 14:06:18 -08001974void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
1975 ArtMethod* copy,
1976 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01001977 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001978
1979 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01001980
1981 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001982 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01001983 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001984 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001985
Ian Rogers848871b2013-08-05 10:56:33 -07001986 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1987 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07001988
Ian Rogers848871b2013-08-05 10:56:33 -07001989 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001990 Runtime* runtime = Runtime::Current();
1991 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001992 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001993 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001994 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1995 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001996 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001997 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001998 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
1999 bool found_one = false;
2000 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2001 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2002 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2003 found_one = true;
2004 break;
2005 }
2006 }
2007 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2008 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002009 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002010 // We assume all methods have code. If they don't currently then we set them to the use the
2011 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2012 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002013 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002014 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002015 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002016 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002017 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002018 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002019 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002020
Sebastien Hertze1d07812014-05-21 15:44:09 +02002021 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002022 if (orig->IsNative()) {
2023 // The native method's pointer is set to a stub to lookup via dlsym.
2024 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002025 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002026 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002027 }
2028 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002029 }
2030}
2031
Jeff Haodcdc85b2015-12-04 14:06:18 -08002032size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002033 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002034 return std::accumulate(&image_info.bin_slot_sizes_[0],
2035 &image_info.bin_slot_sizes_[up_to],
2036 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002037}
2038
2039ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2040 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002041 static_assert(kBinBits == 3, "wrong number of bin bits");
2042 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002043 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2044
2045 DCHECK_LT(GetBin(), kBinSize);
2046 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2047}
2048
2049ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2050 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2051 DCHECK_EQ(index, GetIndex());
2052}
2053
2054ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2055 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2056}
2057
2058uint32_t ImageWriter::BinSlot::GetIndex() const {
2059 return lockword_ & ~kBinMask;
2060}
2061
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002062ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2063 switch (type) {
2064 case kNativeObjectRelocationTypeArtField:
2065 case kNativeObjectRelocationTypeArtFieldArray:
2066 return kBinArtField;
2067 case kNativeObjectRelocationTypeArtMethodClean:
2068 case kNativeObjectRelocationTypeArtMethodArrayClean:
2069 return kBinArtMethodClean;
2070 case kNativeObjectRelocationTypeArtMethodDirty:
2071 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2072 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002073 case kNativeObjectRelocationTypeDexCacheArray:
2074 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002075 }
2076 UNREACHABLE();
2077}
2078
Vladimir Marko944da602016-02-19 12:27:55 +00002079size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002080 if (compile_app_image_) {
Vladimir Marko944da602016-02-19 12:27:55 +00002081 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002082 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002083 mirror::DexCache* dex_cache =
2084 obj->IsDexCache() ? obj->AsDexCache()
2085 : obj->IsClass() ? obj->AsClass()->GetDexCache()
2086 : obj->GetClass()->GetDexCache();
2087 return GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002088 }
2089}
2090
Vladimir Marko944da602016-02-19 12:27:55 +00002091size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
2092 if (compile_app_image_) {
2093 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002094 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002095 auto it = dex_file_oat_index_map_.find(dex_file);
2096 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002097 return it->second;
2098 }
2099}
2100
Vladimir Marko944da602016-02-19 12:27:55 +00002101size_t ImageWriter::GetOatIndexForDexCache(mirror::DexCache* dex_cache) const {
2102 if (dex_cache == nullptr) {
2103 return GetDefaultOatIndex();
2104 } else {
2105 return GetOatIndexForDexFile(dex_cache->GetDexFile());
2106 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002107}
2108
Vladimir Marko944da602016-02-19 12:27:55 +00002109void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2110 size_t oat_loaded_size,
2111 size_t oat_data_offset,
2112 size_t oat_data_size) {
2113 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2114 for (const ImageInfo& info : image_infos_) {
2115 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2116 }
2117 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002118
Vladimir Marko944da602016-02-19 12:27:55 +00002119 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2120 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2121 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2122 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2123 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002124
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002125 if (compile_app_image_) {
2126 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2127 return;
2128 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002129
2130 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002131 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002132 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002133 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002134 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2135 }
2136}
2137
Vladimir Marko944da602016-02-19 12:27:55 +00002138void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2139 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2140 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2141
2142 if (oat_index == GetDefaultOatIndex()) {
2143 // Primary oat file, read the trampolines.
2144 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2145 oat_header.GetInterpreterToInterpreterBridgeOffset();
2146 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2147 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2148 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2149 oat_header.GetJniDlsymLookupOffset();
2150 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2151 oat_header.GetQuickGenericJniTrampolineOffset();
2152 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2153 oat_header.GetQuickImtConflictTrampolineOffset();
2154 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2155 oat_header.GetQuickResolutionTrampolineOffset();
2156 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2157 oat_header.GetQuickToInterpreterBridgeOffset();
2158 }
2159}
2160
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002161ImageWriter::ImageWriter(
2162 const CompilerDriver& compiler_driver,
2163 uintptr_t image_begin,
2164 bool compile_pic,
2165 bool compile_app_image,
2166 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002167 const std::vector<const char*>& oat_filenames,
2168 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002169 : compiler_driver_(compiler_driver),
2170 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2171 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002172 compile_pic_(compile_pic),
2173 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002174 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002175 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002176 image_method_array_(ImageHeader::kImageMethodsCount),
2177 dirty_methods_(0u),
2178 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002179 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002180 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002181 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002182 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002183 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
2184}
2185
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002186ImageWriter::ImageInfo::ImageInfo()
2187 : intern_table_(new InternTable),
2188 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002189
Brian Carlstrom7940e442013-07-12 13:46:57 -07002190} // namespace art