blob: b1b971f6bae0d0c7aa07dfeea8ed688040613b9e [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "image_writer.h"
18
19#include <sys/stat.h>
Mathieu Chartierceb07b32015-12-10 09:33:21 -080020#include <lz4.h>
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -080021#include <lz4hc.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
Ian Rogers700a4022014-05-19 16:49:03 -070023#include <memory>
Vladimir Marko20f85592015-03-19 10:07:02 +000024#include <numeric>
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080025#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070026#include <vector>
27
Mathieu Chartierc7853442015-03-27 14:35:38 -070028#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070029#include "art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070030#include "base/logging.h"
31#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010032#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070033#include "compiled_method.h"
34#include "dex_file-inl.h"
35#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070036#include "elf_file.h"
37#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "elf_writer.h"
39#include "gc/accounting/card_table-inl.h"
40#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070041#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070042#include "gc/heap.h"
43#include "gc/space/large_object_space.h"
44#include "gc/space/space-inl.h"
45#include "globals.h"
46#include "image.h"
47#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070048#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070049#include "lock_word.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070050#include "mirror/abstract_method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "mirror/array-inl.h"
52#include "mirror/class-inl.h"
53#include "mirror/class_loader.h"
54#include "mirror/dex_cache-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070055#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "mirror/object-inl.h"
57#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070058#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "oat.h"
60#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070061#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "runtime.h"
63#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070064#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000065#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070067using ::art::mirror::Class;
68using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070069using ::art::mirror::Object;
70using ::art::mirror::ObjectArray;
71using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070072
73namespace art {
74
Igor Murashkinf5b4c502014-11-14 15:01:59 -080075// Separate objects into multiple bins to optimize dirty memory use.
76static constexpr bool kBinObjects = true;
77
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080078// Return true if an object is already in an image space.
79bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080080 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080081 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080082 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080083 return false;
84 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080085 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
86 const uint8_t* image_begin = boot_image_space->Begin();
87 // Real image end including ArtMethods and ArtField sections.
88 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
89 if (image_begin <= obj && obj < image_end) {
90 return true;
91 }
92 }
93 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080094}
95
96bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080097 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080098 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080099 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800100 return false;
101 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800102 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
103 const ImageHeader& image_header = boot_image_space->GetImageHeader();
104 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
105 return true;
106 }
107 }
108 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800109}
110
Andreas Gampedd9d0552015-03-09 12:57:41 -0700111static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700112 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700113 Class* klass = obj->GetClass();
114 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
115}
116
117static void CheckNoDexObjects() {
118 ScopedObjectAccess soa(Thread::Current());
119 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
120}
121
Vladimir Markof4da6752014-08-01 19:04:18 +0100122bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800123 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800124 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100125 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700126 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100127 PruneNonImageClasses(); // Remove junk
Mathieu Chartier901e0702016-02-19 13:42:48 -0800128 if (!compile_app_image_) {
129 // Avoid for app image since this may increase RAM and image size.
130 ComputeLazyFieldsForImageClasses(); // Add useful information
131 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100132 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100133 heap->CollectGarbage(false); // Remove garbage.
134
Andreas Gampedd9d0552015-03-09 12:57:41 -0700135 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
136 // dex files.
137 //
138 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
139 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
140 // true.
141 if (kIsDebugBuild) {
142 CheckNoDexObjects();
143 }
144
Vladimir Markof4da6752014-08-01 19:04:18 +0100145 if (kIsDebugBuild) {
146 ScopedObjectAccess soa(Thread::Current());
147 CheckNonImageClassesRemoved();
148 }
149
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700150 {
151 ScopedObjectAccess soa(Thread::Current());
152 CalculateNewObjectOffsets();
153 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100154
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700155 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
156 // bin size sums being calculated.
157 if (!AllocMemory()) {
158 return false;
159 }
160
Vladimir Markof4da6752014-08-01 19:04:18 +0100161 return true;
162}
163
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700164bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800165 const std::vector<const char*>& image_filenames,
Vladimir Marko944da602016-02-19 12:27:55 +0000166 const std::vector<const char*>& oat_filenames) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800167 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
168 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800169 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800170 if (image_fd != kInvalidFd) {
171 CHECK_EQ(image_filenames.size(), 1u);
172 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800173 CHECK(!oat_filenames.empty());
174 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700175
Vladimir Marko944da602016-02-19 12:27:55 +0000176 {
177 ScopedObjectAccess soa(Thread::Current());
178 for (size_t i = 0; i < oat_filenames.size(); ++i) {
179 CreateHeader(i);
180 CopyAndFixupNativeData(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800181 }
182 }
Alex Light53cb16b2014-06-12 11:26:29 -0700183
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700184 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700185 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800186 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700187 Runtime::Current()->GetHeap()->DisableObjectValidation();
188 CopyAndFixupObjects();
189 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190
Jeff Haodcdc85b2015-12-04 14:06:18 -0800191 for (size_t i = 0; i < image_filenames.size(); ++i) {
192 const char* image_filename = image_filenames[i];
Vladimir Marko944da602016-02-19 12:27:55 +0000193 ImageInfo& image_info = GetImageInfo(i);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800194 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800195 if (image_fd != kInvalidFd) {
196 if (strlen(image_filename) == 0u) {
197 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800198 // Empty the file in case it already exists.
199 if (image_file != nullptr) {
200 TEMP_FAILURE_RETRY(image_file->SetLength(0));
201 TEMP_FAILURE_RETRY(image_file->Flush());
202 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800203 } else {
204 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
205 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800206 } else {
207 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800208 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800209
Jeff Haodcdc85b2015-12-04 14:06:18 -0800210 if (image_file == nullptr) {
211 LOG(ERROR) << "Failed to open image file " << image_filename;
212 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800213 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800214
215 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800216 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
217 image_file->Erase();
218 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800219 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800220
Jeff Haodcdc85b2015-12-04 14:06:18 -0800221 std::unique_ptr<char[]> compressed_data;
222 // Image data size excludes the bitmap and the header.
223 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
224 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
225 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
226 size_t data_size;
227 const char* image_data_to_write;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800228 const uint64_t compress_start_time = NanoTime();
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000229
Jeff Haodcdc85b2015-12-04 14:06:18 -0800230 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
231 switch (image_storage_mode_) {
232 case ImageHeader::kStorageModeLZ4: {
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800233 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800234 compressed_data.reset(new char[compressed_max_size]);
235 data_size = LZ4_compress(
236 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
237 &compressed_data[0],
238 image_data_size);
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800239
240 break;
241 }
242 case ImageHeader::kStorageModeLZ4HC: {
243 // Bound is same as non HC.
244 const size_t compressed_max_size = LZ4_compressBound(image_data_size);
245 compressed_data.reset(new char[compressed_max_size]);
246 data_size = LZ4_compressHC(
247 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
248 &compressed_data[0],
249 image_data_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800250 break;
251 }
252 case ImageHeader::kStorageModeUncompressed: {
253 data_size = image_data_size;
254 image_data_to_write = image_data;
255 break;
256 }
257 default: {
258 LOG(FATAL) << "Unsupported";
259 UNREACHABLE();
260 }
261 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800262
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800263 if (compressed_data != nullptr) {
264 image_data_to_write = &compressed_data[0];
265 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
266 << PrettyDuration(NanoTime() - compress_start_time);
267 }
268
Jeff Haodcdc85b2015-12-04 14:06:18 -0800269 // Write out the image + fields + methods.
270 const bool is_compressed = compressed_data != nullptr;
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800271 if (!image_file->PwriteFully(image_data_to_write, data_size, sizeof(ImageHeader))) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800272 PLOG(ERROR) << "Failed to write image file data " << image_filename;
273 image_file->Erase();
274 return false;
275 }
276
277 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
278 // convenience.
279 const ImageSection& bitmap_section = image_header->GetImageSection(
280 ImageHeader::kSectionImageBitmap);
281 // Align up since data size may be unaligned if the image is compressed.
282 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
283 if (!is_compressed) {
284 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
285 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800286 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
287 bitmap_section.Size(),
288 bitmap_position_in_file)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800289 PLOG(ERROR) << "Failed to write image file " << image_filename;
290 image_file->Erase();
291 return false;
292 }
Mathieu Chartier6f6b1342016-03-09 11:14:50 -0800293
294 int err = image_file->Flush();
295 if (err < 0) {
296 PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
297 image_file->Erase();
298 return false;
299 }
300
301 // Write header last in case the compiler gets killed in the middle of image writing.
302 // We do not want to have a corrupted image with a valid header.
303 // The header is uncompressed since it contains whether the image is compressed or not.
304 image_header->data_size_ = data_size;
305 if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
306 sizeof(ImageHeader),
307 0)) {
308 PLOG(ERROR) << "Failed to write image file header " << image_filename;
309 image_file->Erase();
310 return false;
311 }
312
Jeff Haodcdc85b2015-12-04 14:06:18 -0800313 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
314 static_cast<size_t>(image_file->GetLength()));
315 if (image_file->FlushCloseOrErase() != 0) {
316 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
317 return false;
318 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800319 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700320 return true;
321}
322
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700323void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700324 DCHECK(object != nullptr);
325 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800326
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800327 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700328 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700329 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700330 DCHECK(IsImageOffsetAssigned(object));
331}
332
Mathieu Chartiere401d142015-04-22 13:56:20 -0700333void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
334 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
335 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
336 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
337}
338
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800339void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700340 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800341 DCHECK_NE(image_objects_offset_begin_, 0u);
342
Vladimir Marko944da602016-02-19 12:27:55 +0000343 size_t oat_index = GetOatIndex(object);
344 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800345 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100346 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800347 DCHECK_ALIGNED(new_offset, kObjectAlignment);
348
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700349 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800350 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700351}
352
Ian Rogersef7d42f2014-01-06 12:55:46 -0800353bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800354 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700355 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700356 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700357}
358
Ian Rogersef7d42f2014-01-06 12:55:46 -0800359size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700360 DCHECK(object != nullptr);
361 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700362 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700363 size_t offset = lock_word.ForwardingAddress();
Vladimir Marko944da602016-02-19 12:27:55 +0000364 size_t oat_index = GetOatIndex(object);
365 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800366 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700367 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700368}
369
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800370void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
371 DCHECK(object != nullptr);
372 DCHECK(!IsImageOffsetAssigned(object));
373 DCHECK(!IsImageBinSlotAssigned(object));
374
375 // Before we stomp over the lock word, save the hash code for later.
376 Monitor::Deflate(Thread::Current(), object);;
377 LockWord lw(object->GetLockWord(false));
378 switch (lw.GetState()) {
379 case LockWord::kFatLocked: {
380 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
381 break;
382 }
383 case LockWord::kThinLocked: {
384 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
385 break;
386 }
387 case LockWord::kUnlocked:
388 // No hash, don't need to save it.
389 break;
390 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700391 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
392 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800393 break;
394 default:
395 LOG(FATAL) << "Unreachable.";
396 UNREACHABLE();
397 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700398 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700399 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800400 DCHECK(IsImageBinSlotAssigned(object));
401}
402
Vladimir Marko20f85592015-03-19 10:07:02 +0000403void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000404 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000405 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
406 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800407 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000408 auto it = dex_file_oat_index_map_.find(dex_file);
409 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800410 ImageInfo& image_info = GetImageInfo(it->second);
411 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
412 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
413 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
414 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000415
Vladimir Marko20f85592015-03-19 10:07:02 +0000416 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700417 Thread* const self = Thread::Current();
418 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800419 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700420 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800421 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800422 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700423 continue;
424 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000425 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700426 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000427 DCHECK(layout.Valid());
Vladimir Marko944da602016-02-19 12:27:55 +0000428 size_t oat_index = GetOatIndexForDexCache(dex_cache);
429 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800430 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100431 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800432 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
433 start + layout.TypesOffset(),
434 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100435 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800436 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
437 start + layout.MethodsOffset(),
438 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100439 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800440 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
441 start + layout.FieldsOffset(),
442 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100443 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800444 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000445 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000446}
447
Jeff Haodcdc85b2015-12-04 14:06:18 -0800448void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100449 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800450 DCHECK(!IsInBootImage(array));
Vladimir Marko944da602016-02-19 12:27:55 +0000451 size_t oat_index = GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800452 native_object_relocations_.emplace(array,
Vladimir Marko944da602016-02-19 12:27:55 +0000453 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100454 }
455}
456
Mathieu Chartiere401d142015-04-22 13:56:20 -0700457void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
458 DCHECK(arr != nullptr);
459 if (kIsDebugBuild) {
460 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800461 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700462 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800463 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800464 CHECK(klass == nullptr || KeepClass(klass))
465 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700466 }
467 }
468 }
469 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
470 // ArtMethods.
471 pointer_arrays_.emplace(arr, kBinArtMethodClean);
472}
473
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800474void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
475 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800476 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800477
478 // The magic happens here. We segregate objects into different bins based
479 // on how likely they are to get dirty at runtime.
480 //
481 // Likely-to-dirty objects get packed together into the same bin so that
482 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
483 // maximized.
484 //
485 // This means more pages will stay either clean or shared dirty (with zygote) and
486 // the app will use less of its own (private) memory.
487 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000488 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800489
490 if (kBinObjects) {
491 //
492 // Changing the bin of an object is purely a memory-use tuning.
493 // It has no change on runtime correctness.
494 //
495 // Memory analysis has determined that the following types of objects get dirtied
496 // the most:
497 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000498 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
499 // a fixed layout which helps improve generated code (using PC-relative addressing),
500 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
501 // Since these arrays are huge, most pages do not overlap other objects and it's not
502 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100503 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800504 // * Class'es which are verified [their clinit runs only at runtime]
505 // - classes in general [because their static fields get overwritten]
506 // - initialized classes with all-final statics are unlikely to be ever dirty,
507 // so bin them separately
508 // * Art Methods that are:
509 // - native [their native entry point is not looked up until runtime]
510 // - have declaring classes that aren't initialized
511 // [their interpreter/quick entry points are trampolines until the class
512 // becomes initialized]
513 //
514 // We also assume the following objects get dirtied either never or extremely rarely:
515 // * Strings (they are immutable)
516 // * Art methods that aren't native and have initialized declared classes
517 //
518 // We assume that "regular" bin objects are highly unlikely to become dirtied,
519 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
520 //
521 if (object->IsClass()) {
522 bin = kBinClassVerified;
523 mirror::Class* klass = object->AsClass();
524
Mathieu Chartiere401d142015-04-22 13:56:20 -0700525 // Add non-embedded vtable to the pointer array table if there is one.
526 auto* vtable = klass->GetVTable();
527 if (vtable != nullptr) {
528 AddMethodPointerArray(vtable);
529 }
530 auto* iftable = klass->GetIfTable();
531 if (iftable != nullptr) {
532 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
533 if (iftable->GetMethodArrayCount(i) > 0) {
534 AddMethodPointerArray(iftable->GetMethodArray(i));
535 }
536 }
537 }
538
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800539 if (klass->GetStatus() == Class::kStatusInitialized) {
540 bin = kBinClassInitialized;
541
542 // If the class's static fields are all final, put it into a separate bin
543 // since it's very likely it will stay clean.
544 uint32_t num_static_fields = klass->NumStaticFields();
545 if (num_static_fields == 0) {
546 bin = kBinClassInitializedFinalStatics;
547 } else {
548 // Maybe all the statics are final?
549 bool all_final = true;
550 for (uint32_t i = 0; i < num_static_fields; ++i) {
551 ArtField* field = klass->GetStaticField(i);
552 if (!field->IsFinal()) {
553 all_final = false;
554 break;
555 }
556 }
557
558 if (all_final) {
559 bin = kBinClassInitializedFinalStatics;
560 }
561 }
562 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800563 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
564 bin = kBinString; // Strings are almost always immutable (except for object header).
565 } // else bin = kBinRegular
566 }
567
Vladimir Marko944da602016-02-19 12:27:55 +0000568 size_t oat_index = GetOatIndex(object);
569 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800570
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800571 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800572 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
573 // Move the current bin size up to accommodate the object we just assigned a bin slot.
574 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800575
576 BinSlot new_bin_slot(bin, current_offset);
577 SetImageBinSlot(object, new_bin_slot);
578
Jeff Haodcdc85b2015-12-04 14:06:18 -0800579 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800580
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800581 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800582 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800583}
584
Mathieu Chartiere401d142015-04-22 13:56:20 -0700585bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
586 if (m->IsNative()) {
587 return true;
588 }
589 mirror::Class* declaring_class = m->GetDeclaringClass();
590 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
591 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
592}
593
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800594bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
595 DCHECK(object != nullptr);
596
597 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
598 // If it's in some other state, then we haven't yet assigned an image bin slot.
599 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
600 return false;
601 } else if (kIsDebugBuild) {
602 LockWord lock_word = object->GetLockWord(false);
603 size_t offset = lock_word.ForwardingAddress();
604 BinSlot bin_slot(offset);
Vladimir Marko944da602016-02-19 12:27:55 +0000605 size_t oat_index = GetOatIndex(object);
606 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800607 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800608 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800609 }
610 return true;
611}
612
613ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
614 DCHECK(object != nullptr);
615 DCHECK(IsImageBinSlotAssigned(object));
616
617 LockWord lock_word = object->GetLockWord(false);
618 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
619 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
620
621 BinSlot bin_slot(static_cast<uint32_t>(offset));
Vladimir Marko944da602016-02-19 12:27:55 +0000622 size_t oat_index = GetOatIndex(object);
623 const ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800624 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800625
626 return bin_slot;
627}
628
Brian Carlstrom7940e442013-07-12 13:46:57 -0700629bool ImageWriter::AllocMemory() {
Vladimir Marko944da602016-02-19 12:27:55 +0000630 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800631 ImageSection unused_sections[ImageHeader::kSectionCount];
632 const size_t length = RoundUp(
633 image_info.CreateImageSections(target_ptr_size_, unused_sections),
634 kPageSize);
635
Jeff Haodcdc85b2015-12-04 14:06:18 -0800636 std::string error_msg;
637 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
638 nullptr,
639 length,
640 PROT_READ | PROT_WRITE,
641 false,
642 false,
643 &error_msg));
644 if (UNLIKELY(image_info.image_.get() == nullptr)) {
645 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
646 return false;
647 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700648
Jeff Haodcdc85b2015-12-04 14:06:18 -0800649 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
650 CHECK_LE(image_info.image_end_, length);
651 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
652 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
653 if (image_info.image_bitmap_.get() == nullptr) {
654 LOG(ERROR) << "Failed to allocate memory for image bitmap";
655 return false;
656 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700657 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700658 return true;
659}
660
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700661class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
662 public:
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800663 bool operator()(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700664 StackHandleScope<1> hs(Thread::Current());
665 mirror::Class::ComputeName(hs.NewHandle(c));
666 return true;
667 }
668};
669
Brian Carlstrom7940e442013-07-12 13:46:57 -0700670void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700671 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700672 ComputeLazyFieldsForClassesVisitor visitor;
673 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700674}
675
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800676static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
677 return klass->GetClassLoader() == nullptr;
678}
679
680bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
681 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
682}
683
Mathieu Chartier901e0702016-02-19 13:42:48 -0800684bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800685 bool early_exit = false;
686 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800687 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800688}
689
Mathieu Chartier901e0702016-02-19 13:42:48 -0800690bool ImageWriter::PruneAppImageClassInternal(
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800691 mirror::Class* klass,
692 bool* early_exit,
693 std::unordered_set<mirror::Class*>* visited) {
694 DCHECK(early_exit != nullptr);
695 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800696 DCHECK(compile_app_image_);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800697 if (klass == nullptr || IsInBootImage(klass)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700698 return false;
699 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800700 auto found = prune_class_memo_.find(klass);
701 if (found != prune_class_memo_.end()) {
702 // Already computed, return the found value.
703 return found->second;
704 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800705 // Circular dependencies, return false but do not store the result in the memoization table.
706 if (visited->find(klass) != visited->end()) {
707 *early_exit = true;
708 return false;
709 }
710 visited->emplace(klass);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800711 bool result = IsBootClassLoaderClass(klass);
712 std::string temp;
713 // Prune if not an image class, this handles any broken sets of image classes such as having a
714 // class in the set but not it's superclass.
715 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800716 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800717 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
718 // app image.
719 if (klass->GetStatus() == mirror::Class::kStatusError) {
720 result = true;
721 } else {
722 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
723 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800724 if (!result) {
725 // Check interfaces since these wont be visited through VisitReferences.)
726 mirror::IfTable* if_table = klass->GetIfTable();
727 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800728 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
729 &my_early_exit,
730 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800731 }
732 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800733 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800734 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
735 &my_early_exit,
736 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800737 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800738 // Check static fields and their classes.
739 size_t num_static_fields = klass->NumReferenceStaticFields();
740 if (num_static_fields != 0 && klass->IsResolved()) {
741 // Presumably GC can happen when we are cross compiling, it should not cause performance
742 // problems to do pointer size logic.
743 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
744 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
745 for (size_t i = 0u; i < num_static_fields; ++i) {
746 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
747 if (ref != nullptr) {
748 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800749 result = result || PruneAppImageClassInternal(ref->AsClass(),
750 &my_early_exit,
751 visited);
752 } else {
753 result = result || PruneAppImageClassInternal(ref->GetClass(),
754 &my_early_exit,
755 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800756 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800757 }
758 field_offset = MemberOffset(field_offset.Uint32Value() +
759 sizeof(mirror::HeapReference<mirror::Object>));
760 }
761 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800762 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
763 &my_early_exit,
764 visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800765 // Erase the element we stored earlier since we are exiting the function.
766 auto it = visited->find(klass);
767 DCHECK(it != visited->end());
768 visited->erase(it);
769 // Only store result if it is true or none of the calls early exited due to circular
770 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
771 // a child call and we can remember the result.
772 if (result == true || !my_early_exit || visited->empty()) {
773 prune_class_memo_[klass] = result;
774 }
775 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800776 return result;
777}
778
779bool ImageWriter::KeepClass(Class* klass) {
780 if (klass == nullptr) {
781 return false;
782 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800783 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
784 // Already in boot image, return true.
785 return true;
786 }
787 std::string temp;
788 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
789 return false;
790 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800791 if (compile_app_image_) {
792 // For app images, we need to prune boot loader classes that are not in the boot image since
793 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800794 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800795 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800796 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800797 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700798}
799
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700800class NonImageClassesVisitor : public ClassVisitor {
801 public:
802 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
803
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800804 bool operator()(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800805 if (!image_writer_->KeepClass(klass)) {
806 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700807 }
808 return true;
809 }
810
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800811 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700812 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700813};
814
815void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700816 Runtime* runtime = Runtime::Current();
817 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700818 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700819
820 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700821 NonImageClassesVisitor visitor(this);
822 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700823
824 // Remove the undesired classes from the class roots.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800825 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800826 for (mirror::Class* klass : visitor.classes_to_prune_) {
827 std::string temp;
828 const char* name = klass->GetDescriptor(&temp);
829 VLOG(compiler) << "Pruning class " << name;
830 if (!compile_app_image_) {
831 DCHECK(IsBootClassLoaderClass(klass));
832 }
833 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800834 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700835 }
836
837 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100838 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700839
840 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
841 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
842 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800843 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800844 if (self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700845 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700846 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800847 mirror::DexCache* dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700848 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
849 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800850 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700851 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700852 }
853 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100854 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
855 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
856 ArtMethod* method =
857 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800858 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
859 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800860 // 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 -0800861 // declaring class which is an image class. Set it to the resolution method to be safe and
862 // prevent dangling pointers.
Alex Light36121492016-02-22 13:43:29 -0800863 if (method->IsCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800864 mirror::DexCache::SetElementPtrSize(resolved_methods,
865 i,
866 resolution_method,
867 target_ptr_size_);
868 } else {
869 // Check that the class is still in the classes table.
870 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
871 << PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700872 }
873 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800874 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700875 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800876 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800877 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700878 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700879 }
880 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700881 // Clean the dex field. It might have been populated during the initialization phase, but
882 // contains data only valid during a real run.
883 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700884 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700885
886 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
887 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800888
889 // Clear to save RAM.
890 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700891}
892
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800893void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700894 if (compiler_driver_.GetImageClasses() != nullptr) {
895 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700896 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700897 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700898}
899
900void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
901 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800902 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700903 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800904 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700905 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700906 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800907 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
908 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700909 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700910 }
911}
912
913void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700914 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700915 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700916 for (const std::string& image_class : *image_classes) {
917 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700918 }
919}
920
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800921mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
922 Thread* const self = Thread::Current();
Vladimir Marko944da602016-02-19 12:27:55 +0000923 for (const ImageInfo& image_info : image_infos_) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800924 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
925 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
926 << string->ToModifiedUtf8();
927 if (found != nullptr) {
928 return found;
929 }
930 }
931 if (compile_app_image_) {
932 Runtime* const runtime = Runtime::Current();
933 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
934 // If we found it in the runtime intern table it could either be in the boot image or interned
935 // during app image compilation. If it was in the boot image return that, otherwise return null
936 // since it belongs to another image space.
937 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
938 return found;
939 }
940 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
941 << string->ToModifiedUtf8();
942 }
943 return nullptr;
944}
945
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800946void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700947 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700948 // if it is a string, we want to intern it if its not interned.
949 if (obj->GetClass()->IsStringClass()) {
Vladimir Marko944da602016-02-19 12:27:55 +0000950 size_t oat_index = GetOatIndex(obj);
951 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800952
Brian Carlstrom7940e442013-07-12 13:46:57 -0700953 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800954 if (IsImageBinSlotAssigned(obj)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800955 DCHECK_EQ(obj, FindInternedString(obj->AsString()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700956 return;
957 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800958 // Need to check if the string is already interned in another image info so that we don't have
959 // the intern tables of two different images contain the same string.
960 mirror::String* interned = FindInternedString(obj->AsString());
961 if (interned == nullptr) {
962 // Not in another image space, insert to our table.
963 interned = image_info.intern_table_->InternStrongImageString(obj->AsString());
964 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700965 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800966 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700967 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800968 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700969 }
970 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800971 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700972 return;
973 }
974 // else (obj == interned), nothing to do but fall through to the normal case
975 }
976
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800977 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700978}
979
Vladimir Marko944da602016-02-19 12:27:55 +0000980ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700981 Runtime* runtime = Runtime::Current();
982 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700983 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700984 StackHandleScope<3> hs(self);
985 Handle<Class> object_array_class(hs.NewHandle(
986 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700987
Jeff Haodcdc85b2015-12-04 14:06:18 -0800988 std::unordered_set<const DexFile*> image_dex_files;
Vladimir Marko944da602016-02-19 12:27:55 +0000989 for (auto& pair : dex_file_oat_index_map_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800990 const DexFile* image_dex_file = pair.first;
Vladimir Marko944da602016-02-19 12:27:55 +0000991 size_t image_oat_index = pair.second;
992 if (oat_index == image_oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800993 image_dex_files.insert(image_dex_file);
994 }
995 }
996
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700997 // build an Object[] of all the DexCaches used in the source_space_.
998 // Since we can't hold the dex lock when allocating the dex_caches
999 // ObjectArray, we lock the dex lock twice, first to get the number
1000 // of dex caches first and then lock it again to copy the dex
1001 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001002 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001003 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001004 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001005 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001006 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1007 mirror::DexCache* dex_cache =
1008 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001009 const DexFile* dex_file = dex_cache->GetDexFile();
1010 if (!IsInBootImage(dex_cache)) {
1011 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1012 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001013 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001014 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001015 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001016 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001017 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1018 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001019 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001020 size_t non_image_dex_caches = 0;
1021 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001022 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1023 mirror::DexCache* dex_cache =
1024 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001025 const DexFile* dex_file = dex_cache->GetDexFile();
1026 if (!IsInBootImage(dex_cache)) {
1027 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1028 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001029 }
1030 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1031 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001032 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001033 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1034 mirror::DexCache* dex_cache =
1035 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001036 const DexFile* dex_file = dex_cache->GetDexFile();
1037 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001038 dex_caches->Set<false>(i, dex_cache);
1039 ++i;
1040 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001041 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001042 }
1043
1044 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001045 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001046 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001047 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001048 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001049 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001050 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001051 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001052 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001053}
1054
Mathieu Chartier590fee92013-09-13 13:46:47 -07001055// Walk instance fields of the given Class. Separate function to allow recursion on the super
1056// class.
1057void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1058 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001059 StackHandleScope<1> hs(Thread::Current());
1060 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1061 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001062 if (super != nullptr) {
1063 WalkInstanceFields(obj, super);
1064 }
1065 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001066 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +00001067 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001068 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001069 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001070 if (value != nullptr) {
1071 WalkFieldsInOrder(value);
1072 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001073 field_offset = MemberOffset(field_offset.Uint32Value() +
1074 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001075 }
1076}
1077
1078// For an unvisited object, visit it then all its children found via fields.
1079void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001080 if (IsInBootImage(obj)) {
1081 // Object is in the image, don't need to fix it up.
1082 return;
1083 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001084 // Use our own visitor routine (instead of GC visitor) to get better locality between
1085 // an object and its fields
1086 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001087 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001088 StackHandleScope<2> hs(Thread::Current());
1089 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1090 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001091 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001092 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001093 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001094 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001095 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001096 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001097 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001098 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001099 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001100 if (value != nullptr) {
1101 WalkFieldsInOrder(value);
1102 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001103 field_offset = MemberOffset(field_offset.Uint32Value() +
1104 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001105 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001106 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001107 auto* as_klass = h_obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001108 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001109 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1110 if (compile_app_image_) {
1111 // Extra sanity, no boot loader classes should be left!
1112 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1113 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001114 LengthPrefixedArray<ArtField>* fields[] = {
1115 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1116 };
Vladimir Marko944da602016-02-19 12:27:55 +00001117 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1118 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001119 {
1120 // Note: This table is only accessed from the image writer, so the lock is technically
1121 // unnecessary.
1122 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1123 // Insert in the class table for this iamge.
1124 image_info.class_table_->Insert(as_klass);
1125 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001126 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1127 // Total array length including header.
1128 if (cur_fields != nullptr) {
1129 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1130 // Forward the entire array at once.
1131 auto it = native_object_relocations_.find(cur_fields);
1132 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1133 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001134 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001135 DCHECK(!IsInBootImage(cur_fields));
Vladimir Marko944da602016-02-19 12:27:55 +00001136 native_object_relocations_.emplace(
1137 cur_fields,
1138 NativeObjectRelocation {
1139 oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1140 });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001141 offset += header_size;
1142 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001143 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001144 // Need to forward arrays separate of fields.
1145 ArtField* field = &cur_fields->At(i);
1146 auto it2 = native_object_relocations_.find(field);
1147 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1148 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001149 DCHECK(!IsInBootImage(field));
Vladimir Marko944da602016-02-19 12:27:55 +00001150 native_object_relocations_.emplace(
1151 field,
1152 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001153 offset += sizeof(ArtField);
1154 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001155 }
1156 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001157 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001158 size_t num_methods = as_klass->NumMethods();
1159 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001160 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001161 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1162 if (WillMethodBeDirty(&m)) {
1163 any_dirty = true;
1164 break;
1165 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001166 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001167 NativeObjectRelocationType type = any_dirty
1168 ? kNativeObjectRelocationTypeArtMethodDirty
1169 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001170 Bin bin_type = BinTypeForNativeRelocationType(type);
1171 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001172 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1173 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001174 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1175 method_size,
1176 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001177 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001178 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001179 CHECK(it == native_object_relocations_.end())
1180 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001181 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001182 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001183 native_object_relocations_.emplace(array,
1184 NativeObjectRelocation {
Vladimir Marko944da602016-02-19 12:27:55 +00001185 oat_index,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001186 offset,
1187 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1188 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001189 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001190 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001191 AssignMethodOffset(&m, type, oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001192 }
Alex Lighte64300b2015-12-15 15:02:47 -08001193 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001194 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001195 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001196 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001197 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001198 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001199 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001200 mirror::Object* value = obj_array->Get(i);
1201 if (value != nullptr) {
1202 WalkFieldsInOrder(value);
1203 }
1204 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001205 } else if (h_obj->IsClassLoader()) {
1206 // Register the class loader if it has a class table.
1207 // The fake boot class loader should not get registered and we should end up with only one
1208 // class loader.
1209 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1210 if (class_loader->GetClassTable() != nullptr) {
1211 class_loaders_.insert(class_loader);
1212 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001213 }
1214 }
1215}
1216
Jeff Haodcdc85b2015-12-04 14:06:18 -08001217void ImageWriter::AssignMethodOffset(ArtMethod* method,
1218 NativeObjectRelocationType type,
Vladimir Marko944da602016-02-19 12:27:55 +00001219 size_t oat_index) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001220 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001221 auto it = native_object_relocations_.find(method);
1222 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001223 << PrettyMethod(method);
Vladimir Marko944da602016-02-19 12:27:55 +00001224 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001225 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
Vladimir Marko944da602016-02-19 12:27:55 +00001226 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001227 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001228}
1229
Mathieu Chartier590fee92013-09-13 13:46:47 -07001230void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1231 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1232 DCHECK(writer != nullptr);
1233 writer->WalkFieldsInOrder(obj);
1234}
1235
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001236void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1237 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1238 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001239 if (!writer->IsInBootImage(obj)) {
1240 writer->UnbinObjectsIntoOffset(obj);
1241 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001242}
1243
1244void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001245 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001246 CHECK(obj != nullptr);
1247
1248 // We know the bin slot, and the total bin sizes for all objects by now,
1249 // so calculate the object's final image offset.
1250
1251 DCHECK(IsImageBinSlotAssigned(obj));
1252 BinSlot bin_slot = GetImageBinSlot(obj);
1253 // Change the lockword from a bin slot into an offset
1254 AssignImageOffset(obj, bin_slot);
1255}
1256
Vladimir Markof4da6752014-08-01 19:04:18 +01001257void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001258 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001259 StackHandleScopeCollection handles(self);
1260 std::vector<Handle<ObjectArray<Object>>> image_roots;
Vladimir Marko944da602016-02-19 12:27:55 +00001261 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1262 image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001263 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001264
Mathieu Chartiere401d142015-04-22 13:56:20 -07001265 auto* runtime = Runtime::Current();
1266 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001267
Mathieu Chartier31e89252013-08-28 11:29:12 -07001268 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001269 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001270 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001271
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001272 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1273 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001274 // Write the image runtime methods.
1275 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1276 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1277 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1278 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1279 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1280 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1281 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1282 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001283
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001284 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001285 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1286 auto it = native_object_relocations_.find(&image_method_array_);
1287 CHECK(it == native_object_relocations_.end());
Vladimir Marko944da602016-02-19 12:27:55 +00001288 ImageInfo& default_image_info = GetImageInfo(GetDefaultOatIndex());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001289 size_t& offset =
1290 default_image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001291 if (!compile_app_image_) {
1292 native_object_relocations_.emplace(&image_method_array_,
Vladimir Marko944da602016-02-19 12:27:55 +00001293 NativeObjectRelocation { GetDefaultOatIndex(), offset, image_method_type });
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001294 }
Vladimir Marko14632852015-08-17 12:07:23 +01001295 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001296 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001297 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001298 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001299 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001300 for (auto* m : image_methods_) {
1301 CHECK(m != nullptr);
1302 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001303 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1304 if (!IsInBootImage(m)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001305 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean, GetDefaultOatIndex());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001306 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001307 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001308 // Calculate size of the dex cache arrays slot and prepare offsets.
1309 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001310
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001311 // Calculate the sizes of the intern tables and class tables.
Vladimir Marko944da602016-02-19 12:27:55 +00001312 for (ImageInfo& image_info : image_infos_) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001313 // Calculate how big the intern table will be after being serialized.
1314 InternTable* const intern_table = image_info.intern_table_.get();
1315 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1316 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001317 // Calculate the size of the class table.
1318 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1319 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001320 }
1321
Vladimir Markocf36d492015-08-12 19:27:26 +01001322 // Calculate bin slot offsets.
Vladimir Marko944da602016-02-19 12:27:55 +00001323 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001324 size_t bin_offset = image_objects_offset_begin_;
1325 for (size_t i = 0; i != kBinSize; ++i) {
1326 image_info.bin_slot_offsets_[i] = bin_offset;
1327 bin_offset += image_info.bin_slot_sizes_[i];
1328 if (i == kBinArtField) {
1329 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1330 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1331 DCHECK_ALIGNED(bin_offset, 4u);
1332 DCHECK(method_alignment == 4u || method_alignment == 8u);
1333 bin_offset = RoundUp(bin_offset, method_alignment);
1334 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001335 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001336 // NOTE: There may be additional padding between the bin slots and the intern table.
1337 DCHECK_EQ(image_info.image_end_,
1338 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001339 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001340
Jeff Haodcdc85b2015-12-04 14:06:18 -08001341 // Calculate image offsets.
1342 size_t image_offset = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001343 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001344 image_info.image_begin_ = global_image_begin_ + image_offset;
1345 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001346 ImageSection unused_sections[ImageHeader::kSectionCount];
1347 image_info.image_size_ = RoundUp(
1348 image_info.CreateImageSections(target_ptr_size_, unused_sections),
1349 kPageSize);
1350 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001351 image_offset += image_info.image_size_;
1352 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001353
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001354 // Transform each object's bin slot into an offset which will be used to do the final copy.
1355 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001356
Jeff Haodcdc85b2015-12-04 14:06:18 -08001357 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001358
Jeff Haodcdc85b2015-12-04 14:06:18 -08001359 size_t i = 0;
Vladimir Marko944da602016-02-19 12:27:55 +00001360 for (ImageInfo& image_info : image_infos_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001361 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1362 i++;
1363 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001364
Mathieu Chartiere401d142015-04-22 13:56:20 -07001365 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001366 for (auto& pair : native_object_relocations_) {
1367 NativeObjectRelocation& relocation = pair.second;
1368 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Marko944da602016-02-19 12:27:55 +00001369 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001370 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001371 }
1372
Jeff Haodcdc85b2015-12-04 14:06:18 -08001373 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001374}
1375
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001376size_t ImageWriter::ImageInfo::CreateImageSections(size_t target_ptr_size,
1377 ImageSection* out_sections) const {
1378 DCHECK(out_sections != nullptr);
1379 // Objects section
1380 auto* objects_section = &out_sections[ImageHeader::kSectionObjects];
1381 *objects_section = ImageSection(0u, image_end_);
1382 size_t cur_pos = objects_section->End();
1383 // Add field section.
1384 auto* field_section = &out_sections[ImageHeader::kSectionArtFields];
1385 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
1386 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
1387 cur_pos = field_section->End();
1388 // Round up to the alignment the required by the method section.
1389 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size));
1390 // Add method section.
1391 auto* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1392 *methods_section = ImageSection(cur_pos,
1393 bin_slot_sizes_[kBinArtMethodClean] +
1394 bin_slot_sizes_[kBinArtMethodDirty]);
1395 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
1396 cur_pos = methods_section->End();
1397 // Add dex cache arrays section.
1398 auto* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1399 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1400 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1401 cur_pos = dex_cache_arrays_section->End();
1402 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1403 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1404 // Calculate the size of the interned strings.
1405 auto* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
1406 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1407 cur_pos = interned_strings_section->End();
1408 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1409 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1410 // Calculate the size of the class table section.
1411 auto* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001412 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001413 cur_pos = class_table_section->End();
1414 // Image end goes right before the start of the image bitmap.
1415 return cur_pos;
1416}
1417
Vladimir Marko944da602016-02-19 12:27:55 +00001418void ImageWriter::CreateHeader(size_t oat_index) {
1419 ImageInfo& image_info = GetImageInfo(oat_index);
1420 const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1421 const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1422 const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001423
1424 // Create the image sections.
1425 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001426 const size_t image_end = image_info.CreateImageSections(target_ptr_size_, sections);
1427
Mathieu Chartiere401d142015-04-22 13:56:20 -07001428 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001429 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001430 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001431 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001432 if (VLOG_IS_ON(compiler)) {
Vladimir Marko944da602016-02-19 12:27:55 +00001433 LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001434 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001435 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001436 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1437 ++idx;
1438 }
1439 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001440 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1441 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1442 << " Image offset=" << image_info.image_offset_ << std::dec;
1443 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1444 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1445 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1446 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001447 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001448 // Store boot image info for app image so that we can relocate.
1449 uint32_t boot_image_begin = 0;
1450 uint32_t boot_image_end = 0;
1451 uint32_t boot_oat_begin = 0;
1452 uint32_t boot_oat_end = 0;
1453 gc::Heap* const heap = Runtime::Current()->GetHeap();
1454 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001455
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001456 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1457 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001458 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1459 image_end,
1460 sections,
1461 image_info.image_roots_address_,
Vladimir Marko944da602016-02-19 12:27:55 +00001462 image_info.oat_checksum_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001463 PointerToLowMemUInt32(oat_file_begin),
1464 PointerToLowMemUInt32(image_info.oat_data_begin_),
1465 PointerToLowMemUInt32(oat_data_end),
1466 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001467 boot_image_begin,
1468 boot_image_end - boot_image_begin,
1469 boot_oat_begin,
1470 boot_oat_end - boot_oat_begin,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001471 target_ptr_size_,
1472 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001473 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001474 image_storage_mode_,
1475 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001476}
1477
1478ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001479 auto it = native_object_relocations_.find(method);
1480 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Vladimir Marko944da602016-02-19 12:27:55 +00001481 size_t oat_index = GetOatIndex(method->GetDexCache());
1482 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001483 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1484 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001485}
1486
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001487class FixupRootVisitor : public RootVisitor {
1488 public:
1489 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1490 }
1491
1492 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001493 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001494 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001495 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001496 }
1497 }
1498
1499 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1500 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001501 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001502 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001503 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001504 }
1505 }
1506
1507 private:
1508 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001509};
1510
Vladimir Marko944da602016-02-19 12:27:55 +00001511void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
1512 ImageInfo& image_info = GetImageInfo(oat_index);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001513 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001514 for (auto& pair : native_object_relocations_) {
1515 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001516 // Only work with fields and methods that are in the current oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001517 if (relocation.oat_index != oat_index) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001518 continue;
1519 }
1520 auto* dest = image_info.image_->Begin() + relocation.offset;
1521 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001522 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001523 switch (relocation.type) {
1524 case kNativeObjectRelocationTypeArtField: {
1525 memcpy(dest, pair.first, sizeof(ArtField));
1526 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1527 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1528 break;
1529 }
1530 case kNativeObjectRelocationTypeArtMethodClean:
1531 case kNativeObjectRelocationTypeArtMethodDirty: {
1532 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001533 reinterpret_cast<ArtMethod*>(dest),
1534 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001535 break;
1536 }
1537 // For arrays, copy just the header since the elements will get copied by their corresponding
1538 // relocations.
1539 case kNativeObjectRelocationTypeArtFieldArray: {
1540 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1541 break;
1542 }
1543 case kNativeObjectRelocationTypeArtMethodArrayClean:
1544 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001545 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1546 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001547 ArtMethod::Size(target_ptr_size_),
1548 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001549 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001550 case kNativeObjectRelocationTypeDexCacheArray:
1551 // Nothing to copy here, everything is done in FixupDexCache().
1552 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001553 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001554 }
1555 }
1556 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001557 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001558 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001559 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001560 ArtMethod* method = image_methods_[i];
1561 CHECK(method != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001562 // Only place runtime methods in the image of the default oat file.
Vladimir Marko944da602016-02-19 12:27:55 +00001563 if (method->IsRuntimeMethod() && oat_index != GetDefaultOatIndex()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001564 continue;
1565 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001566 if (!IsInBootImage(method)) {
1567 auto it = native_object_relocations_.find(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001568 CHECK(it != native_object_relocations_.end()) << "No forwarding for " << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001569 NativeObjectRelocation& relocation = it->second;
1570 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1571 << methods_section;
1572 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001573 method = reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001574 }
1575 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001576 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001577 FixupRootVisitor root_visitor(this);
1578
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001579 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001580 if (image_info.intern_table_bytes_ > 0) {
1581 const ImageSection& intern_table_section = image_header->GetImageSection(
1582 ImageHeader::kSectionInternedStrings);
1583 InternTable* const intern_table = image_info.intern_table_.get();
1584 uint8_t* const intern_table_memory_ptr =
1585 image_info.image_->Begin() + intern_table_section.Offset();
1586 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1587 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1588 // Fixup the pointers in the newly written intern table to contain image addresses.
1589 InternTable temp_intern_table;
1590 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1591 // the VisitRoots() will update the memory directly rather than the copies.
1592 // This also relies on visit roots not doing any verification which could fail after we update
1593 // the roots to be the image addresses.
1594 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1595 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1596 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1597 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001598 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1599 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001600 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001601 const ImageSection& class_table_section = image_header->GetImageSection(
1602 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001603 uint8_t* const class_table_memory_ptr =
1604 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001605 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001606
1607 ClassTable* table = image_info.class_table_.get();
1608 CHECK(table != nullptr);
1609 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1610 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1611 // Fixup the pointers in the newly written class table to contain image addresses. See
1612 // above comment for intern tables.
1613 ClassTable temp_class_table;
1614 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1615 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1616 table->NumZygoteClasses());
1617 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1618 RootInfo(kRootUnknown));
1619 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001620 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001621}
1622
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001623void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001624 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001625 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1626 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001627 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001628 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001629 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1630 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001631 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001632 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001633}
1634
Mathieu Chartier590fee92013-09-13 13:46:47 -07001635void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001636 DCHECK(obj != nullptr);
1637 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001638 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1639}
1640
Mathieu Chartiere401d142015-04-22 13:56:20 -07001641void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1642 mirror::Class* klass, Bin array_type) {
1643 CHECK(klass->IsArrayClass());
1644 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1645 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001646 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001647 dst->SetClass(GetImageAddress(arr->GetClass()));
1648 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001649 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001650 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1651 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001652 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001653 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001654 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001655 auto* method = reinterpret_cast<ArtMethod*>(elem);
1656 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1657 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1658 << PrettyClass(method->GetDeclaringClass());
1659 } else {
1660 CHECK_EQ(array_type, kBinArtField);
1661 auto* field = reinterpret_cast<ArtField*>(elem);
1662 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1663 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1664 << PrettyClass(field->GetDeclaringClass());
1665 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001666 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001667 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001668 ImageInfo& image_info = GetImageInfo(it->second.oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001669 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001670 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001671 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001672 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001673 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001674}
1675
1676void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001677 if (IsInBootImage(obj)) {
1678 return;
1679 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001680 size_t offset = GetImageOffset(obj);
Vladimir Marko944da602016-02-19 12:27:55 +00001681 size_t oat_index = GetOatIndex(obj);
1682 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001683 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1684 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001685 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001686
Jeff Haodcdc85b2015-12-04 14:06:18 -08001687 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001688
1689 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001690 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001691 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001692
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001693 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1694 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001695 const auto it = saved_hashcode_map_.find(obj);
1696 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1697 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001698 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001699}
1700
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001701// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001702class FixupVisitor {
1703 public:
1704 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1705 }
1706
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001707 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1708 // with other logic.
1709 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1710 const {}
1711 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1712
1713
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001714 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001715 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001716 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001717 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1718 // image.
1719 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001720 offset,
1721 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001722 }
1723
1724 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001725 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001726 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001727 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001728 mirror::Reference::ReferentOffset(),
1729 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001730 }
1731
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001732 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001733 ImageWriter* const image_writer_;
1734 mirror::Object* const copy_;
1735};
1736
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001737class FixupClassVisitor FINAL : public FixupVisitor {
1738 public:
1739 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1740 }
1741
Mathieu Chartierc7853442015-03-27 14:35:38 -07001742 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001743 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001744 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001745 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001746 }
1747
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001748 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1749 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001750 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001751 LOG(FATAL) << "Reference not expected here.";
1752 }
1753};
1754
Vladimir Marko05792b92015-08-03 11:56:49 +01001755uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1756 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001757 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001758 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001759 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1760 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001761 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001762 return relocation.offset;
1763}
1764
1765template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001766T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001767 if (obj == nullptr || IsInBootImage(obj)) {
1768 return obj;
1769 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001770 auto it = native_object_relocations_.find(obj);
1771 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1772 << Runtime::Current()->GetHeap()->DumpSpaces();
1773 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko944da602016-02-19 12:27:55 +00001774 ImageInfo& image_info = GetImageInfo(relocation.oat_index);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001775 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001776 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001777}
1778
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001779template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001780T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1781 if (obj == nullptr || IsInBootImage(obj)) {
1782 return obj;
1783 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00001784 size_t oat_index = GetOatIndexForDexCache(dex_cache);
1785 ImageInfo& image_info = GetImageInfo(oat_index);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001786 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1787 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001788}
1789
1790class NativeLocationVisitor {
1791 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001792 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001793
1794 template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001795 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001796 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001797 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001798
1799 private:
1800 ImageWriter* const image_writer_;
1801};
1802
1803void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001804 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001805 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001806 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001807
1808 // Remove the clinitThreadId. This is required for image determinism.
1809 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001810}
1811
Ian Rogersef7d42f2014-01-06 12:55:46 -08001812void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001813 DCHECK(orig != nullptr);
1814 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001815 if (kUseBakerOrBrooksReadBarrier) {
1816 orig->AssertReadBarrierPointer();
1817 if (kUseBrooksReadBarrier) {
1818 // Note the address 'copy' isn't the same as the image address of 'orig'.
1819 copy->SetReadBarrierPointer(GetImageAddress(orig));
1820 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1821 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001822 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001823 auto* klass = orig->GetClass();
1824 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001825 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001826 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1827 if (it != pointer_arrays_.end()) {
1828 // Should only need to fixup every pointer array exactly once.
1829 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1830 pointer_arrays_.erase(it);
1831 return;
1832 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001833 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001834 if (orig->IsClass()) {
1835 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001836 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001837 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1838 // Need to go update the ArtMethod.
1839 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1840 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1841 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001842 auto it = native_object_relocations_.find(src_method);
1843 CHECK(it != native_object_relocations_.end())
1844 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001845 dest->SetArtMethod(
Jeff Haodcdc85b2015-12-04 14:06:18 -08001846 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001847 } else if (!klass->IsArrayClass()) {
1848 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1849 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1850 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001851 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001852 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01001853 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1854 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001855 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001856 // Also set allocator to null to be safe. The allocator is created when we create the class
1857 // table. We also never expect to unload things in the image since they are held live as
1858 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001859 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001860 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001861 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001862 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001863 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001864 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001865}
1866
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001867
1868class ImageAddressVisitor {
1869 public:
1870 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1871
1872 template <typename T>
1873 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1874 return image_writer_->GetImageAddress(ptr);
1875 }
1876
1877 private:
1878 ImageWriter* const image_writer_;
1879};
1880
1881
Vladimir Marko05792b92015-08-03 11:56:49 +01001882void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1883 mirror::DexCache* copy_dex_cache) {
1884 // Though the DexCache array fields are usually treated as native pointers, we set the full
1885 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1886 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1887 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1888 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1889 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001890 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001891 NativeLocationInImage(orig_strings),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001892 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001893 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
1894 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001895 }
1896 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1897 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001898 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001899 NativeLocationInImage(orig_types),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001900 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001901 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
1902 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001903 }
1904 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1905 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001906 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001907 NativeLocationInImage(orig_methods),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001908 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001909 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001910 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1911 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001912 // NativeLocationInImage also handles runtime methods since these have relocation info.
1913 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001914 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1915 }
1916 }
1917 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1918 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001919 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001920 NativeLocationInImage(orig_fields),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001921 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001922 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001923 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1924 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001925 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001926 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1927 }
1928 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001929
1930 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
1931 // compiler pointers in here will make the output non-deterministic.
1932 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001933}
1934
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001935const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1936 DCHECK_LT(type, kOatAddressCount);
1937 // If we are compiling an app image, we need to use the stubs of the boot image.
1938 if (compile_app_image_) {
1939 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001940 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08001941 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1942 DCHECK(!image_spaces.empty());
1943 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001944 CHECK(oat_file != nullptr);
1945 const OatHeader& header = oat_file->GetOatHeader();
1946 switch (type) {
1947 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1948 case kOatAddressQuickGenericJNITrampoline:
1949 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1950 case kOatAddressInterpreterToInterpreterBridge:
1951 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1952 case kOatAddressInterpreterToCompiledCodeBridge:
1953 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1954 case kOatAddressJNIDlsymLookup:
1955 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1956 case kOatAddressQuickIMTConflictTrampoline:
1957 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1958 case kOatAddressQuickResolutionTrampoline:
1959 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1960 case kOatAddressQuickToInterpreterBridge:
1961 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1962 default:
1963 UNREACHABLE();
1964 }
1965 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001966 const ImageInfo& primary_image_info = GetImageInfo(0);
1967 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001968}
1969
Jeff Haodcdc85b2015-12-04 14:06:18 -08001970const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
1971 const ImageInfo& image_info,
1972 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001973 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
1974 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
1975 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07001976 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001977 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001978
1979 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1980 // trampoline.
1981
1982 // Quick entrypoint:
Igor Murashkin0ccfe2c2016-02-19 16:41:44 -08001983 const void* quick_oat_entry_point =
1984 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
1985 const uint8_t* quick_code;
1986
1987 if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
1988 DCHECK(method->IsCopied());
1989 // If the code is not in the oat file corresponding to this image (e.g. default methods)
1990 quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
1991 } else {
1992 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
1993 quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
1994 }
1995
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001996 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001997 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
1998 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001999 // We have code for a non-static or initialized method, just use the code.
2000 } else if (quick_code == nullptr && method->IsNative() &&
2001 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2002 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002003 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002004 } else if (quick_code == nullptr && !method->IsNative()) {
2005 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002006 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002007 *quick_is_interpreted = true;
2008 } else {
2009 CHECK(!method->GetDeclaringClass()->IsInitialized());
2010 // We have code for a static method, but need to go through the resolution stub for class
2011 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002012 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2013 }
2014 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002015 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002016 }
2017 return quick_code;
2018}
2019
Jeff Haodcdc85b2015-12-04 14:06:18 -08002020void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2021 ArtMethod* copy,
2022 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002023 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002024
2025 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002026
2027 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002028 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002029 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002030 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002031
Ian Rogers848871b2013-08-05 10:56:33 -07002032 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2033 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002034
Ian Rogers848871b2013-08-05 10:56:33 -07002035 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002036 Runtime* runtime = Runtime::Current();
2037 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002038 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002039 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002040 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
2041 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002042 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002043 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002044 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
2045 bool found_one = false;
2046 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2047 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2048 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2049 found_one = true;
2050 break;
2051 }
2052 }
2053 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2054 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002055 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002056 // We assume all methods have code. If they don't currently then we set them to the use the
2057 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2058 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002059 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002060 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002061 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002062 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002063 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002064 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002065 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002066
Sebastien Hertze1d07812014-05-21 15:44:09 +02002067 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002068 if (orig->IsNative()) {
2069 // The native method's pointer is set to a stub to lookup via dlsym.
2070 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002071 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002072 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002073 }
2074 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002075 }
2076}
2077
Jeff Haodcdc85b2015-12-04 14:06:18 -08002078size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002079 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002080 return std::accumulate(&image_info.bin_slot_sizes_[0],
2081 &image_info.bin_slot_sizes_[up_to],
2082 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002083}
2084
2085ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2086 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002087 static_assert(kBinBits == 3, "wrong number of bin bits");
2088 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002089 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2090
2091 DCHECK_LT(GetBin(), kBinSize);
2092 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2093}
2094
2095ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2096 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2097 DCHECK_EQ(index, GetIndex());
2098}
2099
2100ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2101 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2102}
2103
2104uint32_t ImageWriter::BinSlot::GetIndex() const {
2105 return lockword_ & ~kBinMask;
2106}
2107
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002108ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2109 switch (type) {
2110 case kNativeObjectRelocationTypeArtField:
2111 case kNativeObjectRelocationTypeArtFieldArray:
2112 return kBinArtField;
2113 case kNativeObjectRelocationTypeArtMethodClean:
2114 case kNativeObjectRelocationTypeArtMethodArrayClean:
2115 return kBinArtMethodClean;
2116 case kNativeObjectRelocationTypeArtMethodDirty:
2117 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2118 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002119 case kNativeObjectRelocationTypeDexCacheArray:
2120 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002121 }
2122 UNREACHABLE();
2123}
2124
Vladimir Marko944da602016-02-19 12:27:55 +00002125size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002126 if (compile_app_image_) {
Vladimir Marko944da602016-02-19 12:27:55 +00002127 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002128 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002129 mirror::DexCache* dex_cache =
2130 obj->IsDexCache() ? obj->AsDexCache()
2131 : obj->IsClass() ? obj->AsClass()->GetDexCache()
2132 : obj->GetClass()->GetDexCache();
2133 return GetOatIndexForDexCache(dex_cache);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002134 }
2135}
2136
Vladimir Marko944da602016-02-19 12:27:55 +00002137size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
2138 if (compile_app_image_) {
2139 return GetDefaultOatIndex();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002140 } else {
Vladimir Marko944da602016-02-19 12:27:55 +00002141 auto it = dex_file_oat_index_map_.find(dex_file);
2142 DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -08002143 return it->second;
2144 }
2145}
2146
Vladimir Marko944da602016-02-19 12:27:55 +00002147size_t ImageWriter::GetOatIndexForDexCache(mirror::DexCache* dex_cache) const {
2148 if (dex_cache == nullptr) {
2149 return GetDefaultOatIndex();
2150 } else {
2151 return GetOatIndexForDexFile(dex_cache->GetDexFile());
2152 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002153}
2154
Vladimir Marko944da602016-02-19 12:27:55 +00002155void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2156 size_t oat_loaded_size,
2157 size_t oat_data_offset,
2158 size_t oat_data_size) {
2159 const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2160 for (const ImageInfo& info : image_infos_) {
2161 DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2162 }
2163 DCHECK(images_end != nullptr); // Image space must be ready.
Jeff Haodcdc85b2015-12-04 14:06:18 -08002164
Vladimir Marko944da602016-02-19 12:27:55 +00002165 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2166 cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2167 cur_image_info.oat_loaded_size_ = oat_loaded_size;
2168 cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2169 cur_image_info.oat_size_ = oat_data_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002170
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002171 if (compile_app_image_) {
2172 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2173 return;
2174 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002175
2176 // Update the oat_offset of the next image info.
Vladimir Marko944da602016-02-19 12:27:55 +00002177 if (oat_index + 1u != oat_filenames_.size()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002178 // There is a following one.
Vladimir Marko944da602016-02-19 12:27:55 +00002179 ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002180 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2181 }
2182}
2183
Vladimir Marko944da602016-02-19 12:27:55 +00002184void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2185 ImageInfo& cur_image_info = GetImageInfo(oat_index);
2186 cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2187
2188 if (oat_index == GetDefaultOatIndex()) {
2189 // Primary oat file, read the trampolines.
2190 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2191 oat_header.GetInterpreterToInterpreterBridgeOffset();
2192 cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2193 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2194 cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2195 oat_header.GetJniDlsymLookupOffset();
2196 cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2197 oat_header.GetQuickGenericJniTrampolineOffset();
2198 cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2199 oat_header.GetQuickImtConflictTrampolineOffset();
2200 cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2201 oat_header.GetQuickResolutionTrampolineOffset();
2202 cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2203 oat_header.GetQuickToInterpreterBridgeOffset();
2204 }
2205}
2206
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002207ImageWriter::ImageWriter(
2208 const CompilerDriver& compiler_driver,
2209 uintptr_t image_begin,
2210 bool compile_pic,
2211 bool compile_app_image,
2212 ImageHeader::StorageMode image_storage_mode,
Vladimir Marko944da602016-02-19 12:27:55 +00002213 const std::vector<const char*>& oat_filenames,
2214 const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002215 : compiler_driver_(compiler_driver),
2216 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2217 image_objects_offset_begin_(0),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002218 compile_pic_(compile_pic),
2219 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002220 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
Vladimir Marko944da602016-02-19 12:27:55 +00002221 image_infos_(oat_filenames.size()),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002222 image_method_array_(ImageHeader::kImageMethodsCount),
2223 dirty_methods_(0u),
2224 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002225 image_storage_mode_(image_storage_mode),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002226 oat_filenames_(oat_filenames),
Vladimir Marko944da602016-02-19 12:27:55 +00002227 dex_file_oat_index_map_(dex_file_oat_index_map) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002228 CHECK_NE(image_begin, 0U);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002229 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002230 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2231 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002232}
2233
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002234ImageWriter::ImageInfo::ImageInfo()
2235 : intern_table_(new InternTable),
2236 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002237
Brian Carlstrom7940e442013-07-12 13:46:57 -07002238} // namespace art