blob: 5eff8f37ec01a9cfed55a02f617a65369068750e [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
Mathieu Chartier901e0702016-02-19 13:42:48 -0800127 if (!compile_app_image_) {
128 // Avoid for app image since this may increase RAM and image size.
129 ComputeLazyFieldsForImageClasses(); // Add useful information
130 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100131 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100132 heap->CollectGarbage(false); // Remove garbage.
133
Andreas Gampedd9d0552015-03-09 12:57:41 -0700134 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
135 // dex files.
136 //
137 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
138 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
139 // true.
140 if (kIsDebugBuild) {
141 CheckNoDexObjects();
142 }
143
Vladimir Markof4da6752014-08-01 19:04:18 +0100144 if (kIsDebugBuild) {
145 ScopedObjectAccess soa(Thread::Current());
146 CheckNonImageClassesRemoved();
147 }
148
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700149 {
150 ScopedObjectAccess soa(Thread::Current());
151 CalculateNewObjectOffsets();
152 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100153
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700154 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
155 // bin size sums being calculated.
156 if (!AllocMemory()) {
157 return false;
158 }
159
Vladimir Markof4da6752014-08-01 19:04:18 +0100160 return true;
161}
162
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700163bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800164 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000165 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800166 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
167 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800168 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800169 if (image_fd != kInvalidFd) {
170 CHECK_EQ(image_filenames.size(), 1u);
171 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800172 CHECK(!oat_filenames.empty());
173 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700174
Vladimir Marko944da602016-02-19 12:27:55 +0000175 {
176 ScopedObjectAccess soa(Thread::Current());
177 for (size_t i = 0; i < oat_filenames.size(); ++i) {
178 CreateHeader(i);
179 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800180 }
181 }
Alex Light53cb16b2014-06-12 11:26:29 -0700182
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700183 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700184 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800185 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700186 Runtime::Current()->GetHeap()->DisableObjectValidation();
187 CopyAndFixupObjects();
188 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700189
Jeff Haodcdc85b2015-12-04 14:06:18 -0800190 for (size_t i = 0; i < image_filenames.size(); ++i) {
191 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000192 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800193 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800194 if (image_fd != kInvalidFd) {
195 if (strlen(image_filename) == 0u) {
196 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800197 // Empty the file in case it already exists.
198 if (image_file != nullptr) {
199 TEMP_FAILURE_RETRY(image_file->SetLength(0));
200 TEMP_FAILURE_RETRY(image_file->Flush());
201 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800202 } else {
203 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
204 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800205 } else {
206 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800207 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800208
Jeff Haodcdc85b2015-12-04 14:06:18 -0800209 if (image_file == nullptr) {
210 LOG(ERROR) << "Failed to open image file " << image_filename;
211 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800212 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800213
214 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800215 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
216 image_file->Erase();
217 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800218 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800219
Jeff Haodcdc85b2015-12-04 14:06:18 -0800220 std::unique_ptr<char[]> compressed_data;
221 // Image data size excludes the bitmap and the header.
222 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
223 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
224 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
225 size_t data_size;
226 const char* image_data_to_write;
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000227
Jeff Haodcdc85b2015-12-04 14:06:18 -0800228 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
229 switch (image_storage_mode_) {
230 case ImageHeader::kStorageModeLZ4: {
231 size_t compressed_max_size = LZ4_compressBound(image_data_size);
232 compressed_data.reset(new char[compressed_max_size]);
233 data_size = LZ4_compress(
234 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
235 &compressed_data[0],
236 image_data_size);
237 image_data_to_write = &compressed_data[0];
238 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size;
239 break;
240 }
241 case ImageHeader::kStorageModeUncompressed: {
242 data_size = image_data_size;
243 image_data_to_write = image_data;
244 break;
245 }
246 default: {
247 LOG(FATAL) << "Unsupported";
248 UNREACHABLE();
249 }
250 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800251
Jeff Haodcdc85b2015-12-04 14:06:18 -0800252 // Write header first, as uncompressed.
253 image_header->data_size_ = data_size;
254 if (!image_file->WriteFully(image_info.image_->Begin(), sizeof(ImageHeader))) {
255 PLOG(ERROR) << "Failed to write image file header " << image_filename;
256 image_file->Erase();
257 return false;
258 }
259
260 // Write out the image + fields + methods.
261 const bool is_compressed = compressed_data != nullptr;
262 if (!image_file->WriteFully(image_data_to_write, data_size)) {
263 PLOG(ERROR) << "Failed to write image file data " << image_filename;
264 image_file->Erase();
265 return false;
266 }
267
268 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
269 // convenience.
270 const ImageSection& bitmap_section = image_header->GetImageSection(
271 ImageHeader::kSectionImageBitmap);
272 // Align up since data size may be unaligned if the image is compressed.
273 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
274 if (!is_compressed) {
275 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
276 }
277 if (!image_file->Write(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
278 bitmap_section.Size(),
279 bitmap_position_in_file)) {
280 PLOG(ERROR) << "Failed to write image file " << image_filename;
281 image_file->Erase();
282 return false;
283 }
284 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
285 static_cast<size_t>(image_file->GetLength()));
286 if (image_file->FlushCloseOrErase() != 0) {
287 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
288 return false;
289 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800290 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291 return true;
292}
293
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700294void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700295 DCHECK(object != nullptr);
296 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800297
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800298 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700299 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700300 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700301 DCHECK(IsImageOffsetAssigned(object));
302}
303
Mathieu Chartiere401d142015-04-22 13:56:20 -0700304void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
305 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
306 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
307 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
308}
309
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800310void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700311 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800312 DCHECK_NE(image_objects_offset_begin_, 0u);
313
Vladimir Marko944da602016-02-19 12:27:55 +0000314 size_t oat_index = GetOatIndex(object);
315 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800316 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100317 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800318 DCHECK_ALIGNED(new_offset, kObjectAlignment);
319
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700320 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800321 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700322}
323
Ian Rogersef7d42f2014-01-06 12:55:46 -0800324bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800325 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700326 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700327 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700328}
329
Ian Rogersef7d42f2014-01-06 12:55:46 -0800330size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700331 DCHECK(object != nullptr);
332 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700333 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700334 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000335 size_t oat_index = GetOatIndex(object);
336 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800337 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700338 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700339}
340
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800341void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
342 DCHECK(object != nullptr);
343 DCHECK(!IsImageOffsetAssigned(object));
344 DCHECK(!IsImageBinSlotAssigned(object));
345
346 // Before we stomp over the lock word, save the hash code for later.
347 Monitor::Deflate(Thread::Current(), object);;
348 LockWord lw(object->GetLockWord(false));
349 switch (lw.GetState()) {
350 case LockWord::kFatLocked: {
351 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
352 break;
353 }
354 case LockWord::kThinLocked: {
355 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
356 break;
357 }
358 case LockWord::kUnlocked:
359 // No hash, don't need to save it.
360 break;
361 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700362 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
363 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800364 break;
365 default:
366 LOG(FATAL) << "Unreachable.";
367 UNREACHABLE();
368 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700369 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700370 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800371 DCHECK(IsImageBinSlotAssigned(object));
372}
373
Vladimir Marko20f85592015-03-19 10:07:02 +0000374void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000375 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000376 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
377 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800378 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000379 auto it = dex_file_oat_index_map_.find(dex_file);
380 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800381 ImageInfo& image_info = GetImageInfo(it->second);
382 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
383 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
384 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
385 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000386
Vladimir Marko20f85592015-03-19 10:07:02 +0000387 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700388 Thread* const self = Thread::Current();
389 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800390 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700391 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800392 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800393 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700394 continue;
395 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000396 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700397 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000398 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000399 size_t oat_index = GetOatIndexForDexCache(dex_cache);
400 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800401 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100402 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800403 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
404 start + layout.TypesOffset(),
405 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100406 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800407 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
408 start + layout.MethodsOffset(),
409 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100410 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800411 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
412 start + layout.FieldsOffset(),
413 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100414 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800415 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000416 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000417}
418
Jeff Haodcdc85b2015-12-04 14:06:18 -0800419void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100420 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800421 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000422 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800423 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000424 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100425 }
426}
427
Mathieu Chartiere401d142015-04-22 13:56:20 -0700428void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
429 DCHECK(arr != nullptr);
430 if (kIsDebugBuild) {
431 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800432 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700433 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800434 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800435 CHECK(klass == nullptr || KeepClass(klass))
436 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700437 }
438 }
439 }
440 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
441 // ArtMethods.
442 pointer_arrays_.emplace(arr, kBinArtMethodClean);
443}
444
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800445void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
446 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800447 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800448
449 // The magic happens here. We segregate objects into different bins based
450 // on how likely they are to get dirty at runtime.
451 //
452 // Likely-to-dirty objects get packed together into the same bin so that
453 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
454 // maximized.
455 //
456 // This means more pages will stay either clean or shared dirty (with zygote) and
457 // the app will use less of its own (private) memory.
458 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000459 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800460
461 if (kBinObjects) {
462 //
463 // Changing the bin of an object is purely a memory-use tuning.
464 // It has no change on runtime correctness.
465 //
466 // Memory analysis has determined that the following types of objects get dirtied
467 // the most:
468 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000469 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
470 // a fixed layout which helps improve generated code (using PC-relative addressing),
471 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
472 // Since these arrays are huge, most pages do not overlap other objects and it's not
473 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100474 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800475 // * Class'es which are verified [their clinit runs only at runtime]
476 // - classes in general [because their static fields get overwritten]
477 // - initialized classes with all-final statics are unlikely to be ever dirty,
478 // so bin them separately
479 // * Art Methods that are:
480 // - native [their native entry point is not looked up until runtime]
481 // - have declaring classes that aren't initialized
482 // [their interpreter/quick entry points are trampolines until the class
483 // becomes initialized]
484 //
485 // We also assume the following objects get dirtied either never or extremely rarely:
486 // * Strings (they are immutable)
487 // * Art methods that aren't native and have initialized declared classes
488 //
489 // We assume that "regular" bin objects are highly unlikely to become dirtied,
490 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
491 //
492 if (object->IsClass()) {
493 bin = kBinClassVerified;
494 mirror::Class* klass = object->AsClass();
495
Mathieu Chartiere401d142015-04-22 13:56:20 -0700496 // Add non-embedded vtable to the pointer array table if there is one.
497 auto* vtable = klass->GetVTable();
498 if (vtable != nullptr) {
499 AddMethodPointerArray(vtable);
500 }
501 auto* iftable = klass->GetIfTable();
502 if (iftable != nullptr) {
503 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
504 if (iftable->GetMethodArrayCount(i) > 0) {
505 AddMethodPointerArray(iftable->GetMethodArray(i));
506 }
507 }
508 }
509
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800510 if (klass->GetStatus() == Class::kStatusInitialized) {
511 bin = kBinClassInitialized;
512
513 // If the class's static fields are all final, put it into a separate bin
514 // since it's very likely it will stay clean.
515 uint32_t num_static_fields = klass->NumStaticFields();
516 if (num_static_fields == 0) {
517 bin = kBinClassInitializedFinalStatics;
518 } else {
519 // Maybe all the statics are final?
520 bool all_final = true;
521 for (uint32_t i = 0; i < num_static_fields; ++i) {
522 ArtField* field = klass->GetStaticField(i);
523 if (!field->IsFinal()) {
524 all_final = false;
525 break;
526 }
527 }
528
529 if (all_final) {
530 bin = kBinClassInitializedFinalStatics;
531 }
532 }
533 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800534 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
535 bin = kBinString; // Strings are almost always immutable (except for object header).
536 } // else bin = kBinRegular
537 }
538
Vladimir Marko944da602016-02-19 12:27:55 +0000539 size_t oat_index = GetOatIndex(object);
540 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800541
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800542 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800543 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
544 // Move the current bin size up to accommodate the object we just assigned a bin slot.
545 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800546
547 BinSlot new_bin_slot(bin, current_offset);
548 SetImageBinSlot(object, new_bin_slot);
549
Jeff Haodcdc85b2015-12-04 14:06:18 -0800550 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800551
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800552 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800553 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800554}
555
Mathieu Chartiere401d142015-04-22 13:56:20 -0700556bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
557 if (m->IsNative()) {
558 return true;
559 }
560 mirror::Class* declaring_class = m->GetDeclaringClass();
561 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
562 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
563}
564
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800565bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
566 DCHECK(object != nullptr);
567
568 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
569 // If it's in some other state, then we haven't yet assigned an image bin slot.
570 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
571 return false;
572 } else if (kIsDebugBuild) {
573 LockWord lock_word = object->GetLockWord(false);
574 size_t offset = lock_word.ForwardingAddress();
575 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000576 size_t oat_index = GetOatIndex(object);
577 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800578 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800579 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800580 }
581 return true;
582}
583
584ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
585 DCHECK(object != nullptr);
586 DCHECK(IsImageBinSlotAssigned(object));
587
588 LockWord lock_word = object->GetLockWord(false);
589 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
590 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
591
592 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000593 size_t oat_index = GetOatIndex(object);
594 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800595 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800596
597 return bin_slot;
598}
599
Brian Carlstrom7940e442013-07-12 13:46:57 -0700600bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000601 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800602 ImageSection unused_sections[ImageHeader::kSectionCount];
603 const size_t length = RoundUp(
604 image_info.CreateImageSections(target_ptr_size_, unused_sections),
605 kPageSize);
606
Jeff Haodcdc85b2015-12-04 14:06:18 -0800607 std::string error_msg;
608 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
609 nullptr,
610 length,
611 PROT_READ | PROT_WRITE,
612 false,
613 false,
614 &error_msg));
615 if (UNLIKELY(image_info.image_.get() == nullptr)) {
616 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
617 return false;
618 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700619
Jeff Haodcdc85b2015-12-04 14:06:18 -0800620 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
621 CHECK_LE(image_info.image_end_, length);
622 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
623 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
624 if (image_info.image_bitmap_.get() == nullptr) {
625 LOG(ERROR) << "Failed to allocate memory for image bitmap";
626 return false;
627 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700628 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700629 return true;
630}
631
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700632class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
633 public:
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800634 bool operator()(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700635 StackHandleScope<1> hs(Thread::Current());
636 mirror::Class::ComputeName(hs.NewHandle(c));
637 return true;
638 }
639};
640
Brian Carlstrom7940e442013-07-12 13:46:57 -0700641void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700642 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700643 ComputeLazyFieldsForClassesVisitor visitor;
644 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700645}
646
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800647static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
648 return klass->GetClassLoader() == nullptr;
649}
650
651bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
652 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
653}
654
Mathieu Chartier901e0702016-02-19 13:42:48 -0800655bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800656 bool early_exit = false;
657 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800658 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800659}
660
Mathieu Chartier901e0702016-02-19 13:42:48 -0800661bool ImageWriter::PruneAppImageClassInternal(
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800662 mirror::Class* klass,
663 bool* early_exit,
664 std::unordered_set<mirror::Class*>* visited) {
665 DCHECK(early_exit != nullptr);
666 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800667 DCHECK(compile_app_image_);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800668 if (klass == nullptr || IsInBootImage(klass)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700669 return false;
670 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800671 auto found = prune_class_memo_.find(klass);
672 if (found != prune_class_memo_.end()) {
673 // Already computed, return the found value.
674 return found->second;
675 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800676 // Circular dependencies, return false but do not store the result in the memoization table.
677 if (visited->find(klass) != visited->end()) {
678 *early_exit = true;
679 return false;
680 }
681 visited->emplace(klass);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800682 bool result = IsBootClassLoaderClass(klass);
683 std::string temp;
684 // Prune if not an image class, this handles any broken sets of image classes such as having a
685 // class in the set but not it's superclass.
686 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800687 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800688 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
689 // app image.
690 if (klass->GetStatus() == mirror::Class::kStatusError) {
691 result = true;
692 } else {
693 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
694 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800695 if (!result) {
696 // Check interfaces since these wont be visited through VisitReferences.)
697 mirror::IfTable* if_table = klass->GetIfTable();
698 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800699 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
700 &my_early_exit,
701 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800702 }
703 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800704 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800705 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
706 &my_early_exit,
707 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800708 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800709 // Check static fields and their classes.
710 size_t num_static_fields = klass->NumReferenceStaticFields();
711 if (num_static_fields != 0 && klass->IsResolved()) {
712 // Presumably GC can happen when we are cross compiling, it should not cause performance
713 // problems to do pointer size logic.
714 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
715 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
716 for (size_t i = 0u; i < num_static_fields; ++i) {
717 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
718 if (ref != nullptr) {
719 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800720 result = result || PruneAppImageClassInternal(ref->AsClass(),
721 &my_early_exit,
722 visited);
723 } else {
724 result = result || PruneAppImageClassInternal(ref->GetClass(),
725 &my_early_exit,
726 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800727 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800728 }
729 field_offset = MemberOffset(field_offset.Uint32Value() +
730 sizeof(mirror::HeapReference<mirror::Object>));
731 }
732 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800733 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
734 &my_early_exit,
735 visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800736 // 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 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800754 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
755 // Already in boot image, return true.
756 return true;
757 }
758 std::string temp;
759 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
760 return false;
761 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800762 if (compile_app_image_) {
763 // For app images, we need to prune boot loader classes that are not in the boot image since
764 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800765 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800766 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800767 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800768 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700769}
770
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700771class NonImageClassesVisitor : public ClassVisitor {
772 public:
773 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
774
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800775 bool operator()(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800776 if (!image_writer_->KeepClass(klass)) {
777 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700778 }
779 return true;
780 }
781
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800782 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700783 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700784};
785
786void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700787 Runtime* runtime = Runtime::Current();
788 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700789 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700790
791 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700792 NonImageClassesVisitor visitor(this);
793 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700794
795 // Remove the undesired classes from the class roots.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800796 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800797 for (mirror::Class* klass : visitor.classes_to_prune_) {
798 std::string temp;
799 const char* name = klass->GetDescriptor(&temp);
800 VLOG(compiler) << "Pruning class " << name;
801 if (!compile_app_image_) {
802 DCHECK(IsBootClassLoaderClass(klass));
803 }
804 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800805 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700806 }
807
808 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100809 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700810
811 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
812 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
813 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800814 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800815 if (self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700816 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700817 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800818 mirror::DexCache* dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700819 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
820 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800821 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700822 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700823 }
824 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100825 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
826 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
827 ArtMethod* method =
828 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800829 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
830 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800831 // 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 -0800832 // declaring class which is an image class. Set it to the resolution method to be safe and
833 // prevent dangling pointers.
Alex Light36121492016-02-22 13:43:29 -0800834 if (method->IsCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800835 mirror::DexCache::SetElementPtrSize(resolved_methods,
836 i,
837 resolution_method,
838 target_ptr_size_);
839 } else {
840 // Check that the class is still in the classes table.
841 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
842 << PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700843 }
844 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800845 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700846 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800847 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800848 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700849 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700850 }
851 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700852 // Clean the dex field. It might have been populated during the initialization phase, but
853 // contains data only valid during a real run.
854 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700855 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700856
857 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
858 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800859
860 // Clear to save RAM.
861 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700862}
863
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800864void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700865 if (compiler_driver_.GetImageClasses() != nullptr) {
866 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700867 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700868 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700869}
870
871void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
872 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800873 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700874 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800875 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700876 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700877 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800878 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
879 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700880 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700881 }
882}
883
884void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700885 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700886 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700887 for (const std::string& image_class : *image_classes) {
888 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700889 }
890}
891
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800892mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
893 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +0000894 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800895 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
896 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
897 << string->ToModifiedUtf8();
898 if (found != nullptr) {
899 return found;
900 }
901 }
902 if (compile_app_image_) {
903 Runtime* const runtime = Runtime::Current();
904 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
905 // If we found it in the runtime intern table it could either be in the boot image or interned
906 // during app image compilation. If it was in the boot image return that, otherwise return null
907 // since it belongs to another image space.
908 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
909 return found;
910 }
911 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
912 << string->ToModifiedUtf8();
913 }
914 return nullptr;
915}
916
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800917void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700918 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700919 // if it is a string, we want to intern it if its not interned.
920 if (obj->GetClass()->IsStringClass()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000921 size_t oat_index = GetOatIndex(obj);
922 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800923
Brian Carlstrom7940e442013-07-12 13:46:57 -0700924 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800925 if (IsImageBinSlotAssigned(obj)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800926 DCHECK_EQ(obj, FindInternedString(obj->AsString()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700927 return;
928 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800929 // Need to check if the string is already interned in another image info so that we don't have
930 // the intern tables of two different images contain the same string.
931 mirror::String* interned = FindInternedString(obj->AsString());
932 if (interned == nullptr) {
933 // Not in another image space, insert to our table.
934 interned = image_info.intern_table_->InternStrongImageString(obj->AsString());
935 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700936 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800937 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700938 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800939 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700940 }
941 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800942 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700943 return;
944 }
945 // else (obj == interned), nothing to do but fall through to the normal case
946 }
947
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800948 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700949}
950
Vladimir Marko944da602016-02-19 12:27:55 +0000951ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700952 Runtime* runtime = Runtime::Current();
953 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700954 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700955 StackHandleScope<3> hs(self);
956 Handle<Class> object_array_class(hs.NewHandle(
957 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700958
Jeff Haodcdc85b2015-12-04 14:06:18 -0800959 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +0000960 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800961 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +0000962 size_t image_oat_index = pair.second;
963 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800964 image_dex_files.insert(image_dex_file);
965 }
966 }
967
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700968 // build an Object[] of all the DexCaches used in the source_space_.
969 // Since we can't hold the dex lock when allocating the dex_caches
970 // ObjectArray, we lock the dex lock twice, first to get the number
971 // of dex caches first and then lock it again to copy the dex
972 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800973 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700974 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700975 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800976 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800977 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
978 mirror::DexCache* dex_cache =
979 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800980 const DexFile* dex_file = dex_cache->GetDexFile();
981 if (!IsInBootImage(dex_cache)) {
982 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
983 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800984 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700985 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700986 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800987 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700988 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
989 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700990 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800991 size_t non_image_dex_caches = 0;
992 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800993 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
994 mirror::DexCache* dex_cache =
995 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800996 const DexFile* dex_file = dex_cache->GetDexFile();
997 if (!IsInBootImage(dex_cache)) {
998 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
999 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001000 }
1001 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1002 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001003 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001004 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1005 mirror::DexCache* dex_cache =
1006 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001007 const DexFile* dex_file = dex_cache->GetDexFile();
1008 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001009 dex_caches->Set<false>(i, dex_cache);
1010 ++i;
1011 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001012 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001013 }
1014
1015 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001016 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001017 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001018 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001019 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001020 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001021 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001022 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001023 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001024}
1025
Mathieu Chartier590fee92013-09-13 13:46:47 -07001026// Walk instance fields of the given Class. Separate function to allow recursion on the super
1027// class.
1028void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1029 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001030 StackHandleScope<1> hs(Thread::Current());
1031 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1032 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001033 if (super != nullptr) {
1034 WalkInstanceFields(obj, super);
1035 }
1036 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001037 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +00001038 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001039 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001040 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001041 if (value != nullptr) {
1042 WalkFieldsInOrder(value);
1043 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001044 field_offset = MemberOffset(field_offset.Uint32Value() +
1045 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001046 }
1047}
1048
1049// For an unvisited object, visit it then all its children found via fields.
1050void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001051 if (IsInBootImage(obj)) {
1052 // Object is in the image, don't need to fix it up.
1053 return;
1054 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001055 // Use our own visitor routine (instead of GC visitor) to get better locality between
1056 // an object and its fields
1057 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001058 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001059 StackHandleScope<2> hs(Thread::Current());
1060 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1061 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001062 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001063 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001064 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001065 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001066 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001067 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001068 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001069 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001070 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001071 if (value != nullptr) {
1072 WalkFieldsInOrder(value);
1073 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001074 field_offset = MemberOffset(field_offset.Uint32Value() +
1075 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001076 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001077 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001078 auto* as_klass = h_obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001079 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001080 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1081 if (compile_app_image_) {
1082 // Extra sanity, no boot loader classes should be left!
1083 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1084 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001085 LengthPrefixedArray<ArtField>* fields[] = {
1086 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1087 };
Vladimir Marko944da602016-02-19 12:27:55 +00001088 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1089 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001090 {
1091 // Note: This table is only accessed from the image writer, so the lock is technically
1092 // unnecessary.
1093 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1094 // Insert in the class table for this iamge.
1095 image_info.class_table_->Insert(as_klass);
1096 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001097 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1098 // Total array length including header.
1099 if (cur_fields != nullptr) {
1100 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1101 // Forward the entire array at once.
1102 auto it = native_object_relocations_.find(cur_fields);
1103 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1104 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001105 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001106 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001107 native_object_relocations_.emplace(
1108 cur_fields,
1109 NativeObjectRelocation {
1110 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1111 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001112 offset += header_size;
1113 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001114 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001115 // Need to forward arrays separate of fields.
1116 ArtField* field = &cur_fields->At(i);
1117 auto it2 = native_object_relocations_.find(field);
1118 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1119 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001120 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001121 native_object_relocations_.emplace(
1122 field,
1123 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001124 offset += sizeof(ArtField);
1125 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001126 }
1127 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001128 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001129 size_t num_methods = as_klass->NumMethods();
1130 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001131 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001132 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1133 if (WillMethodBeDirty(&m)) {
1134 any_dirty = true;
1135 break;
1136 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001137 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001138 NativeObjectRelocationType type = any_dirty
1139 ? kNativeObjectRelocationTypeArtMethodDirty
1140 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001141 Bin bin_type = BinTypeForNativeRelocationType(type);
1142 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001143 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1144 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001145 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1146 method_size,
1147 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001148 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001149 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001150 CHECK(it == native_object_relocations_.end())
1151 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001152 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001153 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001154 native_object_relocations_.emplace(array,
1155 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001156 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001157 offset,
1158 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1159 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001160 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001161 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001162 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001163 }
Alex Lighte64300b2015-12-15 15:02:47 -08001164 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001165 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001166 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001167 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001168 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001169 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001170 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001171 mirror::Object* value = obj_array->Get(i);
1172 if (value != nullptr) {
1173 WalkFieldsInOrder(value);
1174 }
1175 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001176 } else if (h_obj->IsClassLoader()) {
1177 // Register the class loader if it has a class table.
1178 // The fake boot class loader should not get registered and we should end up with only one
1179 // class loader.
1180 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1181 if (class_loader->GetClassTable() != nullptr) {
1182 class_loaders_.insert(class_loader);
1183 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001184 }
1185 }
1186}
1187
Jeff Haodcdc85b2015-12-04 14:06:18 -08001188void ImageWriter::AssignMethodOffset(ArtMethod* method,
1189 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001190 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001191 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001192 auto it = native_object_relocations_.find(method);
1193 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001194 << PrettyMethod(method);
Vladimir Marko944da602016-02-19 12:27:55 +00001195 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001196 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001197 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001198 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001199}
1200
Mathieu Chartier590fee92013-09-13 13:46:47 -07001201void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1202 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1203 DCHECK(writer != nullptr);
1204 writer->WalkFieldsInOrder(obj);
1205}
1206
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001207void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1208 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1209 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001210 if (!writer->IsInBootImage(obj)) {
1211 writer->UnbinObjectsIntoOffset(obj);
1212 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001213}
1214
1215void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001216 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001217 CHECK(obj != nullptr);
1218
1219 // We know the bin slot, and the total bin sizes for all objects by now,
1220 // so calculate the object's final image offset.
1221
1222 DCHECK(IsImageBinSlotAssigned(obj));
1223 BinSlot bin_slot = GetImageBinSlot(obj);
1224 // Change the lockword from a bin slot into an offset
1225 AssignImageOffset(obj, bin_slot);
1226}
1227
Vladimir Markof4da6752014-08-01 19:04:18 +01001228void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001229 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001230 StackHandleScopeCollection handles(self);
1231 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001232 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1233 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001234 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001235
Mathieu Chartiere401d142015-04-22 13:56:20 -07001236 auto* runtime = Runtime::Current();
1237 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001238
Mathieu Chartier31e89252013-08-28 11:29:12 -07001239 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001240 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001241 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001242
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001243 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1244 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001245 // Write the image runtime methods.
1246 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1247 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1248 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1249 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1250 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1251 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1252 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1253 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001254
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001255 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001256 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1257 auto it = native_object_relocations_.find(&image_method_array_);
1258 CHECK(it == native_object_relocations_.end());
Vladimir Marko944da602016-02-19 12:27:55 +00001259 ImageInfo& default_image_info = GetImageInfo(GetDefaultOatIndex());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001260 size_t& offset =
1261 default_image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001262 if (!compile_app_image_) {
1263 native_object_relocations_.emplace(&image_method_array_,
Vladimir Marko944da602016-02-19 12:27:55 +00001264 NativeObjectRelocation { GetDefaultOatIndex(), offset, image_method_type });
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001265 }
Vladimir Marko14632852015-08-17 12:07:23 +01001266 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001267 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001268 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001269 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001270 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001271 for (auto* m : image_methods_) {
1272 CHECK(m != nullptr);
1273 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001274 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1275 if (!IsInBootImage(m)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001276 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001277 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001278 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001279 // Calculate size of the dex cache arrays slot and prepare offsets.
1280 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001281
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001282 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001283 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001284 // Calculate how big the intern table will be after being serialized.
1285 InternTable* const intern_table = image_info.intern_table_.get();
1286 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1287 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001288 // Calculate the size of the class table.
1289 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1290 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001291 }
1292
Vladimir Markocf36d492015-08-12 19:27:26 +01001293 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001294 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001295 size_t bin_offset = image_objects_offset_begin_;
1296 for (size_t i = 0; i != kBinSize; ++i) {
1297 image_info.bin_slot_offsets_[i] = bin_offset;
1298 bin_offset += image_info.bin_slot_sizes_[i];
1299 if (i == kBinArtField) {
1300 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1301 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1302 DCHECK_ALIGNED(bin_offset, 4u);
1303 DCHECK(method_alignment == 4u || method_alignment == 8u);
1304 bin_offset = RoundUp(bin_offset, method_alignment);
1305 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001306 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001307 // NOTE: There may be additional padding between the bin slots and the intern table.
1308 DCHECK_EQ(image_info.image_end_,
1309 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001310 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001311
Jeff Haodcdc85b2015-12-04 14:06:18 -08001312 // Calculate image offsets.
1313 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001314 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001315 image_info.image_begin_ = global_image_begin_ + image_offset;
1316 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001317 ImageSection unused_sections[ImageHeader::kSectionCount];
1318 image_info.image_size_ = RoundUp(
1319 image_info.CreateImageSections(target_ptr_size_, unused_sections),
1320 kPageSize);
1321 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001322 image_offset += image_info.image_size_;
1323 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001324
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001325 // Transform each object's bin slot into an offset which will be used to do the final copy.
1326 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001327
Jeff Haodcdc85b2015-12-04 14:06:18 -08001328 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001329
Jeff Haodcdc85b2015-12-04 14:06:18 -08001330 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001331 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001332 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1333 i++;
1334 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001335
Mathieu Chartiere401d142015-04-22 13:56:20 -07001336 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001337 for (auto& pair : native_object_relocations_) {
1338 NativeObjectRelocation& relocation = pair.second;
1339 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001340 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001341 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001342 }
1343
Jeff Haodcdc85b2015-12-04 14:06:18 -08001344 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001345}
1346
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001347size_t ImageWriter::ImageInfo::CreateImageSections(size_t target_ptr_size,
1348 ImageSection* out_sections) const {
1349 DCHECK(out_sections != nullptr);
1350 // Objects section
1351 auto* objects_section = &out_sections[ImageHeader::kSectionObjects];
1352 *objects_section = ImageSection(0u, image_end_);
1353 size_t cur_pos = objects_section->End();
1354 // Add field section.
1355 auto* field_section = &out_sections[ImageHeader::kSectionArtFields];
1356 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
1357 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
1358 cur_pos = field_section->End();
1359 // Round up to the alignment the required by the method section.
1360 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size));
1361 // Add method section.
1362 auto* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1363 *methods_section = ImageSection(cur_pos,
1364 bin_slot_sizes_[kBinArtMethodClean] +
1365 bin_slot_sizes_[kBinArtMethodDirty]);
1366 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
1367 cur_pos = methods_section->End();
1368 // Add dex cache arrays section.
1369 auto* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1370 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1371 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1372 cur_pos = dex_cache_arrays_section->End();
1373 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1374 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1375 // Calculate the size of the interned strings.
1376 auto* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
1377 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1378 cur_pos = interned_strings_section->End();
1379 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1380 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1381 // Calculate the size of the class table section.
1382 auto* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001383 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001384 cur_pos = class_table_section->End();
1385 // Image end goes right before the start of the image bitmap.
1386 return cur_pos;
1387}
1388
Vladimir Marko944da602016-02-19 12:27:55 +00001389void ImageWriter::CreateHeader(size_t oat_index) {
1390 ImageInfo& image_info = GetImageInfo(oat_index);
1391 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1392 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1393 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001394
1395 // Create the image sections.
1396 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001397 const size_t image_end = image_info.CreateImageSections(target_ptr_size_, sections);
1398
Mathieu Chartiere401d142015-04-22 13:56:20 -07001399 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001400 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001401 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001402 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001403 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001404 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001405 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001406 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001407 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1408 ++idx;
1409 }
1410 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001411 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1412 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1413 << " Image offset=" << image_info.image_offset_ << std::dec;
1414 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1415 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1416 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1417 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001418 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001419 // Store boot image info for app image so that we can relocate.
1420 uint32_t boot_image_begin = 0;
1421 uint32_t boot_image_end = 0;
1422 uint32_t boot_oat_begin = 0;
1423 uint32_t boot_oat_end = 0;
1424 gc::Heap* const heap = Runtime::Current()->GetHeap();
1425 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001426
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001427 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1428 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001429 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1430 image_end,
1431 sections,
1432 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001433 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001434 PointerToLowMemUInt32(oat_file_begin),
1435 PointerToLowMemUInt32(image_info.oat_data_begin_),
1436 PointerToLowMemUInt32(oat_data_end),
1437 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001438 boot_image_begin,
1439 boot_image_end - boot_image_begin,
1440 boot_oat_begin,
1441 boot_oat_end - boot_oat_begin,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001442 target_ptr_size_,
1443 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001444 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001445 image_storage_mode_,
1446 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001447}
1448
1449ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001450 auto it = native_object_relocations_.find(method);
1451 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001452 size_t oat_index = GetOatIndex(method->GetDexCache());
1453 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001454 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1455 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001456}
1457
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001458class FixupRootVisitor : public RootVisitor {
1459 public:
1460 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1461 }
1462
1463 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001464 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001465 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001466 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001467 }
1468 }
1469
1470 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1471 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001472 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001473 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001474 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001475 }
1476 }
1477
1478 private:
1479 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001480};
1481
Vladimir Marko944da602016-02-19 12:27:55 +00001482void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
1483 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001484 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001485 for (auto& pair : native_object_relocations_) {
1486 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001487 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001488 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001489 continue;
1490 }
1491 auto* dest = image_info.image_->Begin() + relocation.offset;
1492 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001493 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001494 switch (relocation.type) {
1495 case kNativeObjectRelocationTypeArtField: {
1496 memcpy(dest, pair.first, sizeof(ArtField));
1497 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1498 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1499 break;
1500 }
1501 case kNativeObjectRelocationTypeArtMethodClean:
1502 case kNativeObjectRelocationTypeArtMethodDirty: {
1503 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001504 reinterpret_cast<ArtMethod*>(dest),
1505 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001506 break;
1507 }
1508 // For arrays, copy just the header since the elements will get copied by their corresponding
1509 // relocations.
1510 case kNativeObjectRelocationTypeArtFieldArray: {
1511 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1512 break;
1513 }
1514 case kNativeObjectRelocationTypeArtMethodArrayClean:
1515 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001516 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1517 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001518 ArtMethod::Size(target_ptr_size_),
1519 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001520 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001521 case kNativeObjectRelocationTypeDexCacheArray:
1522 // Nothing to copy here, everything is done in FixupDexCache().
1523 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001524 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001525 }
1526 }
1527 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001528 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001529 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001530 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001531 ArtMethod* method = image_methods_[i];
1532 CHECK(method != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001533 // Only place runtime methods in the image of the default oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001534 if (method->IsRuntimeMethod() && oat_index != GetDefaultOatIndex()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001535 continue;
1536 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001537 if (!IsInBootImage(method)) {
1538 auto it = native_object_relocations_.find(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001539 CHECK(it != native_object_relocations_.end()) << "No forwarding for " << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001540 NativeObjectRelocation& relocation = it->second;
1541 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1542 << methods_section;
1543 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001544 method = reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001545 }
1546 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001547 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001548 FixupRootVisitor root_visitor(this);
1549
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001550 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001551 if (image_info.intern_table_bytes_ > 0) {
1552 const ImageSection& intern_table_section = image_header->GetImageSection(
1553 ImageHeader::kSectionInternedStrings);
1554 InternTable* const intern_table = image_info.intern_table_.get();
1555 uint8_t* const intern_table_memory_ptr =
1556 image_info.image_->Begin() + intern_table_section.Offset();
1557 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1558 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1559 // Fixup the pointers in the newly written intern table to contain image addresses.
1560 InternTable temp_intern_table;
1561 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1562 // the VisitRoots() will update the memory directly rather than the copies.
1563 // This also relies on visit roots not doing any verification which could fail after we update
1564 // the roots to be the image addresses.
1565 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1566 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1567 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1568 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001569 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1570 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001571 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001572 const ImageSection& class_table_section = image_header->GetImageSection(
1573 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001574 uint8_t* const class_table_memory_ptr =
1575 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001576 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001577
1578 ClassTable* table = image_info.class_table_.get();
1579 CHECK(table != nullptr);
1580 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1581 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1582 // Fixup the pointers in the newly written class table to contain image addresses. See
1583 // above comment for intern tables.
1584 ClassTable temp_class_table;
1585 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1586 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1587 table->NumZygoteClasses());
1588 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1589 RootInfo(kRootUnknown));
1590 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001591 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001592}
1593
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001594void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001595 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001596 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1597 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001598 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001599 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001600 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1601 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001602 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001603 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001604}
1605
Mathieu Chartier590fee92013-09-13 13:46:47 -07001606void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001607 DCHECK(obj != nullptr);
1608 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001609 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1610}
1611
Mathieu Chartiere401d142015-04-22 13:56:20 -07001612void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1613 mirror::Class* klass, Bin array_type) {
1614 CHECK(klass->IsArrayClass());
1615 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1616 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001617 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001618 dst->SetClass(GetImageAddress(arr->GetClass()));
1619 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001620 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001621 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1622 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001623 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001624 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001625 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001626 auto* method = reinterpret_cast<ArtMethod*>(elem);
1627 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1628 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1629 << PrettyClass(method->GetDeclaringClass());
1630 } else {
1631 CHECK_EQ(array_type, kBinArtField);
1632 auto* field = reinterpret_cast<ArtField*>(elem);
1633 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1634 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1635 << PrettyClass(field->GetDeclaringClass());
1636 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001637 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001638 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001639 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001640 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001641 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001642 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001643 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001644 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001645}
1646
1647void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001648 if (IsInBootImage(obj)) {
1649 return;
1650 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001651 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001652 size_t oat_index = GetOatIndex(obj);
1653 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001654 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1655 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001656 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001657
Jeff Haodcdc85b2015-12-04 14:06:18 -08001658 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001659
1660 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001661 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001662 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001663
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001664 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1665 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001666 const auto it = saved_hashcode_map_.find(obj);
1667 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1668 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001669 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001670}
1671
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001672// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001673class FixupVisitor {
1674 public:
1675 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1676 }
1677
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001678 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1679 // with other logic.
1680 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1681 const {}
1682 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1683
1684
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001685 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001686 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001687 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001688 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1689 // image.
1690 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001691 offset,
1692 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001693 }
1694
1695 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001696 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001697 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001698 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001699 mirror::Reference::ReferentOffset(),
1700 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001701 }
1702
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001703 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001704 ImageWriter* const image_writer_;
1705 mirror::Object* const copy_;
1706};
1707
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001708class FixupClassVisitor FINAL : public FixupVisitor {
1709 public:
1710 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1711 }
1712
Mathieu Chartierc7853442015-03-27 14:35:38 -07001713 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001714 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001715 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001716 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001717 }
1718
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001719 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1720 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001721 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001722 LOG(FATAL) << "Reference not expected here.";
1723 }
1724};
1725
Vladimir Marko05792b92015-08-03 11:56:49 +01001726uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1727 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001728 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001729 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001730 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1731 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001732 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001733 return relocation.offset;
1734}
1735
1736template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001737T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001738 if (obj == nullptr || IsInBootImage(obj)) {
1739 return obj;
1740 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001741 auto it = native_object_relocations_.find(obj);
1742 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1743 << Runtime::Current()->GetHeap()->DumpSpaces();
1744 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00001745 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001746 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001747 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001748}
1749
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001750template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001751T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1752 if (obj == nullptr || IsInBootImage(obj)) {
1753 return obj;
1754 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001755 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1756 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001757 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1758 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001759}
1760
1761class NativeLocationVisitor {
1762 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001763 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001764
1765 template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001766 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001767 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001768 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001769
1770 private:
1771 ImageWriter* const image_writer_;
1772};
1773
1774void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001775 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001776 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001777 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001778
1779 // Remove the clinitThreadId. This is required for image determinism.
1780 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001781}
1782
Ian Rogersef7d42f2014-01-06 12:55:46 -08001783void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001784 DCHECK(orig != nullptr);
1785 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001786 if (kUseBakerOrBrooksReadBarrier) {
1787 orig->AssertReadBarrierPointer();
1788 if (kUseBrooksReadBarrier) {
1789 // Note the address 'copy' isn't the same as the image address of 'orig'.
1790 copy->SetReadBarrierPointer(GetImageAddress(orig));
1791 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1792 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001793 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001794 auto* klass = orig->GetClass();
1795 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001796 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001797 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1798 if (it != pointer_arrays_.end()) {
1799 // Should only need to fixup every pointer array exactly once.
1800 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1801 pointer_arrays_.erase(it);
1802 return;
1803 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001804 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001805 if (orig->IsClass()) {
1806 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001807 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001808 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1809 // Need to go update the ArtMethod.
1810 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1811 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1812 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001813 auto it = native_object_relocations_.find(src_method);
1814 CHECK(it != native_object_relocations_.end())
1815 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001816 dest->SetArtMethod(
Jeff Haodcdc85b2015-12-04 14:06:18 -08001817 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001818 } else if (!klass->IsArrayClass()) {
1819 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1820 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1821 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001822 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001823 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01001824 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1825 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001826 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001827 // Also set allocator to null to be safe. The allocator is created when we create the class
1828 // table. We also never expect to unload things in the image since they are held live as
1829 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001830 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001831 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001832 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001833 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001834 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001835 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001836}
1837
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001838
1839class ImageAddressVisitor {
1840 public:
1841 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1842
1843 template <typename T>
1844 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1845 return image_writer_->GetImageAddress(ptr);
1846 }
1847
1848 private:
1849 ImageWriter* const image_writer_;
1850};
1851
1852
Vladimir Marko05792b92015-08-03 11:56:49 +01001853void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1854 mirror::DexCache* copy_dex_cache) {
1855 // Though the DexCache array fields are usually treated as native pointers, we set the full
1856 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1857 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1858 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1859 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1860 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001861 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001862 NativeLocationInImage(orig_strings),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001863 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001864 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
1865 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001866 }
1867 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1868 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001869 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001870 NativeLocationInImage(orig_types),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001871 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001872 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
1873 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001874 }
1875 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1876 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001877 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001878 NativeLocationInImage(orig_methods),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001879 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001880 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001881 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1882 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001883 // NativeLocationInImage also handles runtime methods since these have relocation info.
1884 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001885 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1886 }
1887 }
1888 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1889 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001890 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001891 NativeLocationInImage(orig_fields),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001892 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001893 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001894 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1895 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001896 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001897 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1898 }
1899 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001900
1901 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
1902 // compiler pointers in here will make the output non-deterministic.
1903 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001904}
1905
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001906const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1907 DCHECK_LT(type, kOatAddressCount);
1908 // If we are compiling an app image, we need to use the stubs of the boot image.
1909 if (compile_app_image_) {
1910 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001911 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08001912 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1913 DCHECK(!image_spaces.empty());
1914 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001915 CHECK(oat_file != nullptr);
1916 const OatHeader& header = oat_file->GetOatHeader();
1917 switch (type) {
1918 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1919 case kOatAddressQuickGenericJNITrampoline:
1920 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1921 case kOatAddressInterpreterToInterpreterBridge:
1922 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1923 case kOatAddressInterpreterToCompiledCodeBridge:
1924 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1925 case kOatAddressJNIDlsymLookup:
1926 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1927 case kOatAddressQuickIMTConflictTrampoline:
1928 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1929 case kOatAddressQuickResolutionTrampoline:
1930 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1931 case kOatAddressQuickToInterpreterBridge:
1932 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1933 default:
1934 UNREACHABLE();
1935 }
1936 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001937 const ImageInfo& primary_image_info = GetImageInfo(0);
1938 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001939}
1940
Jeff Haodcdc85b2015-12-04 14:06:18 -08001941const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
1942 const ImageInfo& image_info,
1943 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001944 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
1945 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
1946 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07001947 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001948 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001949
1950 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1951 // trampoline.
1952
1953 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08001954 const void* quick_oat_entry_point =
1955 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
1956 const uint8_t* quick_code;
1957
1958 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
1959 DCHECK(method->IsCopied());
1960 // If the code is not in the oat file corresponding to this image (e.g. default methods)
1961 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
1962 } else {
1963 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
1964 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
1965 }
1966
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001967 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001968 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
1969 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001970 // We have code for a non-static or initialized method, just use the code.
1971 } else if (quick_code == nullptr && method->IsNative() &&
1972 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1973 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001974 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001975 } else if (quick_code == nullptr && !method->IsNative()) {
1976 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001977 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001978 *quick_is_interpreted = true;
1979 } else {
1980 CHECK(!method->GetDeclaringClass()->IsInitialized());
1981 // We have code for a static method, but need to go through the resolution stub for class
1982 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001983 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
1984 }
1985 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001986 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001987 }
1988 return quick_code;
1989}
1990
Jeff Haodcdc85b2015-12-04 14:06:18 -08001991void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
1992 ArtMethod* copy,
1993 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01001994 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001995
1996 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01001997
1998 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001999 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002000 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002001 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002002
Ian Rogers848871b2013-08-05 10:56:33 -07002003 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2004 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002005
Ian Rogers848871b2013-08-05 10:56:33 -07002006 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002007 Runtime* runtime = Runtime::Current();
2008 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002009 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002010 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002011 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
2012 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002013 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002014 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002015 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
2016 bool found_one = false;
2017 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2018 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2019 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2020 found_one = true;
2021 break;
2022 }
2023 }
2024 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2025 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002026 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002027 // We assume all methods have code. If they don't currently then we set them to the use the
2028 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2029 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002030 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002031 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002032 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002033 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002034 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002035 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002036 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002037
Sebastien Hertze1d07812014-05-21 15:44:09 +02002038 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002039 if (orig->IsNative()) {
2040 // The native method's pointer is set to a stub to lookup via dlsym.
2041 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002042 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002043 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002044 }
2045 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002046 }
2047}
2048
Jeff Haodcdc85b2015-12-04 14:06:18 -08002049size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002050 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002051 return std::accumulate(&image_info.bin_slot_sizes_[0],
2052 &image_info.bin_slot_sizes_[up_to],
2053 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002054}
2055
2056ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2057 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002058 static_assert(kBinBits == 3, "wrong number of bin bits");
2059 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002060 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2061
2062 DCHECK_LT(GetBin(), kBinSize);
2063 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2064}
2065
2066ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2067 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2068 DCHECK_EQ(index, GetIndex());
2069}
2070
2071ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2072 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2073}
2074
2075uint32_t ImageWriter::BinSlot::GetIndex() const {
2076 return lockword_ & ~kBinMask;
2077}
2078
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002079ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2080 switch (type) {
2081 case kNativeObjectRelocationTypeArtField:
2082 case kNativeObjectRelocationTypeArtFieldArray:
2083 return kBinArtField;
2084 case kNativeObjectRelocationTypeArtMethodClean:
2085 case kNativeObjectRelocationTypeArtMethodArrayClean:
2086 return kBinArtMethodClean;
2087 case kNativeObjectRelocationTypeArtMethodDirty:
2088 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2089 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002090 case kNativeObjectRelocationTypeDexCacheArray:
2091 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002092 }
2093 UNREACHABLE();
2094}
2095
Vladimir Marko944da602016-02-19 12:27:55 +00002096size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002097 if (compile_app_image_) {
Vladimir Marko944da602016-02-19 12:27:55 +00002098 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002099 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002100 mirror::DexCache* dex_cache =
2101 obj->IsDexCache() ? obj->AsDexCache()
2102 : obj->IsClass() ? obj->AsClass()->GetDexCache()
2103 : obj->GetClass()->GetDexCache();
2104 return GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002105 }
2106}
2107
Vladimir Marko944da602016-02-19 12:27:55 +00002108size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
2109 if (compile_app_image_) {
2110 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002111 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002112 auto it = dex_file_oat_index_map_.find(dex_file);
2113 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002114 return it->second;
2115 }
2116}
2117
Vladimir Marko944da602016-02-19 12:27:55 +00002118size_t ImageWriter::GetOatIndexForDexCache(mirror::DexCache* dex_cache) const {
2119 if (dex_cache == nullptr) {
2120 return GetDefaultOatIndex();
2121 } else {
2122 return GetOatIndexForDexFile(dex_cache->GetDexFile());
2123 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002124}
2125
Vladimir Marko944da602016-02-19 12:27:55 +00002126void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2127 size_t oat_loaded_size,
2128 size_t oat_data_offset,
2129 size_t oat_data_size) {
2130 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2131 for (const ImageInfo& info : image_infos_) {
2132 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2133 }
2134 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002135
Vladimir Marko944da602016-02-19 12:27:55 +00002136 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2137 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2138 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2139 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2140 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002141
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002142 if (compile_app_image_) {
2143 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2144 return;
2145 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002146
2147 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002148 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002149 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002150 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002151 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2152 }
2153}
2154
Vladimir Marko944da602016-02-19 12:27:55 +00002155void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2156 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2157 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2158
2159 if (oat_index == GetDefaultOatIndex()) {
2160 // Primary oat file, read the trampolines.
2161 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2162 oat_header.GetInterpreterToInterpreterBridgeOffset();
2163 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2164 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2165 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2166 oat_header.GetJniDlsymLookupOffset();
2167 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2168 oat_header.GetQuickGenericJniTrampolineOffset();
2169 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2170 oat_header.GetQuickImtConflictTrampolineOffset();
2171 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2172 oat_header.GetQuickResolutionTrampolineOffset();
2173 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2174 oat_header.GetQuickToInterpreterBridgeOffset();
2175 }
2176}
2177
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002178ImageWriter::ImageWriter(
2179 const CompilerDriver& compiler_driver,
2180 uintptr_t image_begin,
2181 bool compile_pic,
2182 bool compile_app_image,
2183 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002184 const std::vector<const char*>& oat_filenames,
2185 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002186 : compiler_driver_(compiler_driver),
2187 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2188 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002189 compile_pic_(compile_pic),
2190 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002191 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002192 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002193 image_method_array_(ImageHeader::kImageMethodsCount),
2194 dirty_methods_(0u),
2195 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002196 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002197 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002198 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002199 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002200 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002201 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2202 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002203}
2204
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002205ImageWriter::ImageInfo::ImageInfo()
2206 : intern_table_(new InternTable),
2207 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002208
Brian Carlstrom7940e442013-07-12 13:46:57 -07002209} // namespace art