blob: d0bb201d6977c968681ae08146a2a4907b41d155 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "image_writer.h"
18
19#include <sys/stat.h>
Mathieu Chartierceb07b32015-12-10 09:33:21 -080020#include <lz4.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
Ian Rogers700a4022014-05-19 16:49:03 -070022#include <memory>
Vladimir Marko20f85592015-03-19 10:07:02 +000023#include <numeric>
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080024#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070025#include <vector>
26
Mathieu Chartierc7853442015-03-27 14:35:38 -070027#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070028#include "art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070029#include "base/logging.h"
30#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010031#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "compiled_method.h"
33#include "dex_file-inl.h"
34#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070035#include "elf_file.h"
36#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070037#include "elf_writer.h"
38#include "gc/accounting/card_table-inl.h"
39#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070040#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "gc/heap.h"
42#include "gc/space/large_object_space.h"
43#include "gc/space/space-inl.h"
44#include "globals.h"
45#include "image.h"
46#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070047#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070048#include "lock_word.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070049#include "mirror/abstract_method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "mirror/array-inl.h"
51#include "mirror/class-inl.h"
52#include "mirror/class_loader.h"
53#include "mirror/dex_cache-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070054#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "mirror/object-inl.h"
56#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070057#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "oat.h"
59#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070060#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "runtime.h"
62#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070063#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000064#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070066using ::art::mirror::Class;
67using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070068using ::art::mirror::Object;
69using ::art::mirror::ObjectArray;
70using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070071
72namespace art {
73
Igor Murashkinf5b4c502014-11-14 15:01:59 -080074// Separate objects into multiple bins to optimize dirty memory use.
75static constexpr bool kBinObjects = true;
76
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080077// Return true if an object is already in an image space.
78bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080079 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080080 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080081 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080082 return false;
83 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080084 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
85 const uint8_t* image_begin = boot_image_space->Begin();
86 // Real image end including ArtMethods and ArtField sections.
87 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
88 if (image_begin <= obj && obj < image_end) {
89 return true;
90 }
91 }
92 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080093}
94
95bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080096 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080097 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080098 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080099 return false;
100 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800101 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
102 const ImageHeader& image_header = boot_image_space->GetImageHeader();
103 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
104 return true;
105 }
106 }
107 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800108}
109
Andreas Gampedd9d0552015-03-09 12:57:41 -0700110static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700111 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700112 Class* klass = obj->GetClass();
113 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
114}
115
116static void CheckNoDexObjects() {
117 ScopedObjectAccess soa(Thread::Current());
118 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
119}
120
Vladimir Markof4da6752014-08-01 19:04:18 +0100121bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800122 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800123 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100124 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700125 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100126 PruneNonImageClasses(); // Remove junk
127 ComputeLazyFieldsForImageClasses(); // Add useful information
Vladimir Markof4da6752014-08-01 19:04:18 +0100128 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100129 heap->CollectGarbage(false); // Remove garbage.
130
Andreas Gampedd9d0552015-03-09 12:57:41 -0700131 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
132 // dex files.
133 //
134 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
135 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
136 // true.
137 if (kIsDebugBuild) {
138 CheckNoDexObjects();
139 }
140
Vladimir Markof4da6752014-08-01 19:04:18 +0100141 if (kIsDebugBuild) {
142 ScopedObjectAccess soa(Thread::Current());
143 CheckNonImageClassesRemoved();
144 }
145
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700146 {
147 ScopedObjectAccess soa(Thread::Current());
148 CalculateNewObjectOffsets();
149 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100150
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700151 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
152 // bin size sums being calculated.
153 if (!AllocMemory()) {
154 return false;
155 }
156
Vladimir Markof4da6752014-08-01 19:04:18 +0100157 return true;
158}
159
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700160bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800161 const std::vector<const char*>& image_filenames,
162 const std::vector<const char*>& oat_filenames) {
163 CHECK(!image_filenames.empty());
164 CHECK(!oat_filenames.empty());
165 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700166
Jeff Haodcdc85b2015-12-04 14:06:18 -0800167 size_t oat_file_offset = 0;
168
169 for (size_t i = 0; i < oat_filenames.size(); ++i) {
170 const char* oat_filename = oat_filenames[i];
171 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
172 if (oat_file.get() == nullptr) {
173 PLOG(ERROR) << "Failed to open oat file " << oat_filename;
174 return false;
175 }
176 std::string error_msg;
177 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_filename, nullptr, &error_msg);
178 if (oat_file_ == nullptr) {
179 PLOG(ERROR) << "Failed to open writable oat file " << oat_filename;
180 oat_file->Erase();
181 return false;
182 }
183 Runtime::Current()->GetOatFileManager().RegisterOatFile(
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700184 std::unique_ptr<const OatFile>(oat_file_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700185
Jeff Haodcdc85b2015-12-04 14:06:18 -0800186 const OatHeader& oat_header = oat_file_->GetOatHeader();
187 ImageInfo& image_info = GetImageInfo(oat_filename);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188
Jeff Haodcdc85b2015-12-04 14:06:18 -0800189 size_t oat_loaded_size = 0;
190 size_t oat_data_offset = 0;
191 ElfWriter::GetOatElfInformation(oat_file.get(), &oat_loaded_size, &oat_data_offset);
192
193 DCHECK_EQ(image_info.oat_offset_, oat_file_offset);
194 oat_file_offset += oat_loaded_size;
195
196 if (i == 0) {
197 // Primary oat file, read the trampolines.
198 image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
199 oat_header.GetInterpreterToInterpreterBridgeOffset();
200 image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
201 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
202 image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
203 oat_header.GetJniDlsymLookupOffset();
204 image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
205 oat_header.GetQuickGenericJniTrampolineOffset();
206 image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
207 oat_header.GetQuickImtConflictTrampolineOffset();
208 image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
209 oat_header.GetQuickResolutionTrampolineOffset();
210 image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
211 oat_header.GetQuickToInterpreterBridgeOffset();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800212 }
213
214
215 {
216 ScopedObjectAccess soa(Thread::Current());
217 CreateHeader(oat_loaded_size, oat_data_offset);
218 CopyAndFixupNativeData();
219 }
220
221 SetOatChecksumFromElfFile(oat_file.get());
222
223 if (oat_file->FlushCloseOrErase() != 0) {
224 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename;
225 return false;
226 }
227 }
Alex Light53cb16b2014-06-12 11:26:29 -0700228
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700229 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700230 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800231 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700232 Runtime::Current()->GetHeap()->DisableObjectValidation();
233 CopyAndFixupObjects();
234 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700235
Jeff Haodcdc85b2015-12-04 14:06:18 -0800236 for (size_t i = 0; i < image_filenames.size(); ++i) {
237 const char* image_filename = image_filenames[i];
238 const char* oat_filename = oat_filenames[i];
239 ImageInfo& image_info = GetImageInfo(oat_filename);
240 std::unique_ptr<File> image_file;
241 if (image_fd != kInvalidImageFd) {
242 image_file.reset(new File(image_fd, image_filename, unix_file::kCheckSafeUsage));
243 } else {
244 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800245 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800246 if (image_file == nullptr) {
247 LOG(ERROR) << "Failed to open image file " << image_filename;
248 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800249 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800250 if (fchmod(image_file->Fd(), 0644) != 0) {
251 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
252 image_file->Erase();
253 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800254 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800255
Jeff Haodcdc85b2015-12-04 14:06:18 -0800256 std::unique_ptr<char[]> compressed_data;
257 // Image data size excludes the bitmap and the header.
258 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
259 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
260 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
261 size_t data_size;
262 const char* image_data_to_write;
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000263
Jeff Haodcdc85b2015-12-04 14:06:18 -0800264 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
265 switch (image_storage_mode_) {
266 case ImageHeader::kStorageModeLZ4: {
267 size_t compressed_max_size = LZ4_compressBound(image_data_size);
268 compressed_data.reset(new char[compressed_max_size]);
269 data_size = LZ4_compress(
270 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
271 &compressed_data[0],
272 image_data_size);
273 image_data_to_write = &compressed_data[0];
274 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size;
275 break;
276 }
277 case ImageHeader::kStorageModeUncompressed: {
278 data_size = image_data_size;
279 image_data_to_write = image_data;
280 break;
281 }
282 default: {
283 LOG(FATAL) << "Unsupported";
284 UNREACHABLE();
285 }
286 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800287
Jeff Haodcdc85b2015-12-04 14:06:18 -0800288 // Write header first, as uncompressed.
289 image_header->data_size_ = data_size;
290 if (!image_file->WriteFully(image_info.image_->Begin(), sizeof(ImageHeader))) {
291 PLOG(ERROR) << "Failed to write image file header " << image_filename;
292 image_file->Erase();
293 return false;
294 }
295
296 // Write out the image + fields + methods.
297 const bool is_compressed = compressed_data != nullptr;
298 if (!image_file->WriteFully(image_data_to_write, data_size)) {
299 PLOG(ERROR) << "Failed to write image file data " << image_filename;
300 image_file->Erase();
301 return false;
302 }
303
304 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
305 // convenience.
306 const ImageSection& bitmap_section = image_header->GetImageSection(
307 ImageHeader::kSectionImageBitmap);
308 // Align up since data size may be unaligned if the image is compressed.
309 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
310 if (!is_compressed) {
311 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
312 }
313 if (!image_file->Write(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
314 bitmap_section.Size(),
315 bitmap_position_in_file)) {
316 PLOG(ERROR) << "Failed to write image file " << image_filename;
317 image_file->Erase();
318 return false;
319 }
320 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
321 static_cast<size_t>(image_file->GetLength()));
322 if (image_file->FlushCloseOrErase() != 0) {
323 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
324 return false;
325 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800326 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700327 return true;
328}
329
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700330void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700331 DCHECK(object != nullptr);
332 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800333
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800334 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700335 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700336 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700337 DCHECK(IsImageOffsetAssigned(object));
338}
339
Mathieu Chartiere401d142015-04-22 13:56:20 -0700340void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
341 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
342 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
343 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
344}
345
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800346void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700347 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800348 DCHECK_NE(image_objects_offset_begin_, 0u);
349
Jeff Haodcdc85b2015-12-04 14:06:18 -0800350 const char* oat_filename = GetOatFilename(object);
351 ImageInfo& image_info = GetImageInfo(oat_filename);
352 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100353 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800354 DCHECK_ALIGNED(new_offset, kObjectAlignment);
355
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700356 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800357 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700358}
359
Ian Rogersef7d42f2014-01-06 12:55:46 -0800360bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800361 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700362 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700363 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700364}
365
Ian Rogersef7d42f2014-01-06 12:55:46 -0800366size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700367 DCHECK(object != nullptr);
368 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700369 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700370 size_t offset = lock_word.ForwardingAddress();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800371 const char* oat_filename = GetOatFilename(object);
372 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
373 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700374 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700375}
376
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800377void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
378 DCHECK(object != nullptr);
379 DCHECK(!IsImageOffsetAssigned(object));
380 DCHECK(!IsImageBinSlotAssigned(object));
381
382 // Before we stomp over the lock word, save the hash code for later.
383 Monitor::Deflate(Thread::Current(), object);;
384 LockWord lw(object->GetLockWord(false));
385 switch (lw.GetState()) {
386 case LockWord::kFatLocked: {
387 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
388 break;
389 }
390 case LockWord::kThinLocked: {
391 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
392 break;
393 }
394 case LockWord::kUnlocked:
395 // No hash, don't need to save it.
396 break;
397 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700398 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
399 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800400 break;
401 default:
402 LOG(FATAL) << "Unreachable.";
403 UNREACHABLE();
404 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700405 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700406 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800407 DCHECK(IsImageBinSlotAssigned(object));
408}
409
Vladimir Marko20f85592015-03-19 10:07:02 +0000410void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000411 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000412 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
413 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800414 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
415 auto it = dex_file_oat_filename_map_.find(dex_file);
416 DCHECK(it != dex_file_oat_filename_map_.end()) << dex_file->GetLocation();
417 ImageInfo& image_info = GetImageInfo(it->second);
418 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
419 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
420 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
421 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000422
Vladimir Marko20f85592015-03-19 10:07:02 +0000423 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700424 Thread* const self = Thread::Current();
425 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800426 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700427 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800428 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800429 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700430 continue;
431 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000432 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700433 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000434 DCHECK(layout.Valid());
Jeff Haodcdc85b2015-12-04 14:06:18 -0800435 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
436 ImageInfo& image_info = GetImageInfo(oat_filename);
437 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100438 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800439 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
440 start + layout.TypesOffset(),
441 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100442 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800443 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
444 start + layout.MethodsOffset(),
445 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100446 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800447 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
448 start + layout.FieldsOffset(),
449 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100450 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800451 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000452 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000453}
454
Jeff Haodcdc85b2015-12-04 14:06:18 -0800455void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100456 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800457 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800458 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
459 native_object_relocations_.emplace(array,
460 NativeObjectRelocation { oat_filename, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100461 }
462}
463
Mathieu Chartiere401d142015-04-22 13:56:20 -0700464void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
465 DCHECK(arr != nullptr);
466 if (kIsDebugBuild) {
467 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800468 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700469 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800470 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800471 CHECK(klass == nullptr || KeepClass(klass))
472 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700473 }
474 }
475 }
476 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
477 // ArtMethods.
478 pointer_arrays_.emplace(arr, kBinArtMethodClean);
479}
480
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800481void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
482 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800483 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800484
485 // The magic happens here. We segregate objects into different bins based
486 // on how likely they are to get dirty at runtime.
487 //
488 // Likely-to-dirty objects get packed together into the same bin so that
489 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
490 // maximized.
491 //
492 // This means more pages will stay either clean or shared dirty (with zygote) and
493 // the app will use less of its own (private) memory.
494 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000495 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800496
497 if (kBinObjects) {
498 //
499 // Changing the bin of an object is purely a memory-use tuning.
500 // It has no change on runtime correctness.
501 //
502 // Memory analysis has determined that the following types of objects get dirtied
503 // the most:
504 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000505 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
506 // a fixed layout which helps improve generated code (using PC-relative addressing),
507 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
508 // Since these arrays are huge, most pages do not overlap other objects and it's not
509 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100510 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800511 // * Class'es which are verified [their clinit runs only at runtime]
512 // - classes in general [because their static fields get overwritten]
513 // - initialized classes with all-final statics are unlikely to be ever dirty,
514 // so bin them separately
515 // * Art Methods that are:
516 // - native [their native entry point is not looked up until runtime]
517 // - have declaring classes that aren't initialized
518 // [their interpreter/quick entry points are trampolines until the class
519 // becomes initialized]
520 //
521 // We also assume the following objects get dirtied either never or extremely rarely:
522 // * Strings (they are immutable)
523 // * Art methods that aren't native and have initialized declared classes
524 //
525 // We assume that "regular" bin objects are highly unlikely to become dirtied,
526 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
527 //
528 if (object->IsClass()) {
529 bin = kBinClassVerified;
530 mirror::Class* klass = object->AsClass();
531
Mathieu Chartiere401d142015-04-22 13:56:20 -0700532 // Add non-embedded vtable to the pointer array table if there is one.
533 auto* vtable = klass->GetVTable();
534 if (vtable != nullptr) {
535 AddMethodPointerArray(vtable);
536 }
537 auto* iftable = klass->GetIfTable();
538 if (iftable != nullptr) {
539 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
540 if (iftable->GetMethodArrayCount(i) > 0) {
541 AddMethodPointerArray(iftable->GetMethodArray(i));
542 }
543 }
544 }
545
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800546 if (klass->GetStatus() == Class::kStatusInitialized) {
547 bin = kBinClassInitialized;
548
549 // If the class's static fields are all final, put it into a separate bin
550 // since it's very likely it will stay clean.
551 uint32_t num_static_fields = klass->NumStaticFields();
552 if (num_static_fields == 0) {
553 bin = kBinClassInitializedFinalStatics;
554 } else {
555 // Maybe all the statics are final?
556 bool all_final = true;
557 for (uint32_t i = 0; i < num_static_fields; ++i) {
558 ArtField* field = klass->GetStaticField(i);
559 if (!field->IsFinal()) {
560 all_final = false;
561 break;
562 }
563 }
564
565 if (all_final) {
566 bin = kBinClassInitializedFinalStatics;
567 }
568 }
569 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800570 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
571 bin = kBinString; // Strings are almost always immutable (except for object header).
572 } // else bin = kBinRegular
573 }
574
Jeff Haodcdc85b2015-12-04 14:06:18 -0800575 const char* oat_filename = GetOatFilename(object);
576 ImageInfo& image_info = GetImageInfo(oat_filename);
577
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800578 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800579 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
580 // Move the current bin size up to accommodate the object we just assigned a bin slot.
581 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800582
583 BinSlot new_bin_slot(bin, current_offset);
584 SetImageBinSlot(object, new_bin_slot);
585
Jeff Haodcdc85b2015-12-04 14:06:18 -0800586 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800587
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800588 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800589 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800590}
591
Mathieu Chartiere401d142015-04-22 13:56:20 -0700592bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
593 if (m->IsNative()) {
594 return true;
595 }
596 mirror::Class* declaring_class = m->GetDeclaringClass();
597 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
598 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
599}
600
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800601bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
602 DCHECK(object != nullptr);
603
604 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
605 // If it's in some other state, then we haven't yet assigned an image bin slot.
606 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
607 return false;
608 } else if (kIsDebugBuild) {
609 LockWord lock_word = object->GetLockWord(false);
610 size_t offset = lock_word.ForwardingAddress();
611 BinSlot bin_slot(offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800612 const char* oat_filename = GetOatFilename(object);
613 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
614 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800615 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800616 }
617 return true;
618}
619
620ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
621 DCHECK(object != nullptr);
622 DCHECK(IsImageBinSlotAssigned(object));
623
624 LockWord lock_word = object->GetLockWord(false);
625 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
626 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
627
628 BinSlot bin_slot(static_cast<uint32_t>(offset));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800629 const char* oat_filename = GetOatFilename(object);
630 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
631 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800632
633 return bin_slot;
634}
635
Brian Carlstrom7940e442013-07-12 13:46:57 -0700636bool ImageWriter::AllocMemory() {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800637 for (const char* oat_filename : oat_filenames_) {
638 ImageInfo& image_info = GetImageInfo(oat_filename);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800639 ImageSection unused_sections[ImageHeader::kSectionCount];
640 const size_t length = RoundUp(
641 image_info.CreateImageSections(target_ptr_size_, unused_sections),
642 kPageSize);
643
Jeff Haodcdc85b2015-12-04 14:06:18 -0800644 std::string error_msg;
645 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
646 nullptr,
647 length,
648 PROT_READ | PROT_WRITE,
649 false,
650 false,
651 &error_msg));
652 if (UNLIKELY(image_info.image_.get() == nullptr)) {
653 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
654 return false;
655 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700656
Jeff Haodcdc85b2015-12-04 14:06:18 -0800657 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
658 CHECK_LE(image_info.image_end_, length);
659 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
660 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
661 if (image_info.image_bitmap_.get() == nullptr) {
662 LOG(ERROR) << "Failed to allocate memory for image bitmap";
663 return false;
664 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700665 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700666 return true;
667}
668
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700669class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
670 public:
671 bool Visit(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
672 StackHandleScope<1> hs(Thread::Current());
673 mirror::Class::ComputeName(hs.NewHandle(c));
674 return true;
675 }
676};
677
Brian Carlstrom7940e442013-07-12 13:46:57 -0700678void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700679 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700680 ComputeLazyFieldsForClassesVisitor visitor;
681 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700682}
683
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800684static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
685 return klass->GetClassLoader() == nullptr;
686}
687
688bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
689 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
690}
691
692bool ImageWriter::ContainsBootClassLoaderNonImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800693 bool early_exit = false;
694 std::unordered_set<mirror::Class*> visited;
695 return ContainsBootClassLoaderNonImageClassInternal(klass, &early_exit, &visited);
696}
697
698bool ImageWriter::ContainsBootClassLoaderNonImageClassInternal(
699 mirror::Class* klass,
700 bool* early_exit,
701 std::unordered_set<mirror::Class*>* visited) {
702 DCHECK(early_exit != nullptr);
703 DCHECK(visited != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700704 if (klass == nullptr) {
705 return false;
706 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800707 auto found = prune_class_memo_.find(klass);
708 if (found != prune_class_memo_.end()) {
709 // Already computed, return the found value.
710 return found->second;
711 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800712 // Circular dependencies, return false but do not store the result in the memoization table.
713 if (visited->find(klass) != visited->end()) {
714 *early_exit = true;
715 return false;
716 }
717 visited->emplace(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800718 bool result = IsBootClassLoaderNonImageClass(klass);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800719 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800720 if (!result) {
721 // Check interfaces since these wont be visited through VisitReferences.)
722 mirror::IfTable* if_table = klass->GetIfTable();
723 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800724 result = result || ContainsBootClassLoaderNonImageClassInternal(
725 if_table->GetInterface(i),
726 &my_early_exit,
727 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800728 }
729 }
730 // Check static fields and their classes.
731 size_t num_static_fields = klass->NumReferenceStaticFields();
732 if (num_static_fields != 0 && klass->IsResolved()) {
733 // Presumably GC can happen when we are cross compiling, it should not cause performance
734 // problems to do pointer size logic.
735 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
736 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
737 for (size_t i = 0u; i < num_static_fields; ++i) {
738 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
739 if (ref != nullptr) {
740 if (ref->IsClass()) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800741 result = result ||
742 ContainsBootClassLoaderNonImageClassInternal(
743 ref->AsClass(),
744 &my_early_exit,
745 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800746 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800747 result = result ||
748 ContainsBootClassLoaderNonImageClassInternal(
749 ref->GetClass(),
750 &my_early_exit,
751 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800752 }
753 field_offset = MemberOffset(field_offset.Uint32Value() +
754 sizeof(mirror::HeapReference<mirror::Object>));
755 }
756 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800757 result = result ||
758 ContainsBootClassLoaderNonImageClassInternal(
759 klass->GetSuperClass(),
760 &my_early_exit,
761 visited);
762 // Erase the element we stored earlier since we are exiting the function.
763 auto it = visited->find(klass);
764 DCHECK(it != visited->end());
765 visited->erase(it);
766 // Only store result if it is true or none of the calls early exited due to circular
767 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
768 // a child call and we can remember the result.
769 if (result == true || !my_early_exit || visited->empty()) {
770 prune_class_memo_[klass] = result;
771 }
772 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800773 return result;
774}
775
776bool ImageWriter::KeepClass(Class* klass) {
777 if (klass == nullptr) {
778 return false;
779 }
780 if (compile_app_image_) {
781 // For app images, we need to prune boot loader classes that are not in the boot image since
782 // these may have already been loaded when the app image is loaded.
783 return !ContainsBootClassLoaderNonImageClass(klass);
784 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700785 std::string temp;
786 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700787}
788
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700789class NonImageClassesVisitor : public ClassVisitor {
790 public:
791 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
792
793 bool Visit(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800794 if (!image_writer_->KeepClass(klass)) {
795 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700796 }
797 return true;
798 }
799
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800800 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700801 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700802};
803
804void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700805 Runtime* runtime = Runtime::Current();
806 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700807 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700808
809 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700810 NonImageClassesVisitor visitor(this);
811 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700812
813 // Remove the undesired classes from the class roots.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800814 for (mirror::Class* klass : visitor.classes_to_prune_) {
815 std::string temp;
816 const char* name = klass->GetDescriptor(&temp);
817 VLOG(compiler) << "Pruning class " << name;
818 if (!compile_app_image_) {
819 DCHECK(IsBootClassLoaderClass(klass));
820 }
821 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800822 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700823 }
824
825 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100826 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700827
828 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
829 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
830 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800831 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
832 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700833 if (dex_cache == nullptr) {
834 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700835 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700836 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
837 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800838 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700839 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700840 }
841 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100842 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
843 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
844 ArtMethod* method =
845 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700846 if (method != nullptr) {
847 auto* declaring_class = method->GetDeclaringClass();
848 // Miranda methods may be held live by a class which was not an image class but have a
849 // declaring class which is an image class. Set it to the resolution method to be safe and
850 // prevent dangling pointers.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800851 if (method->IsMiranda() || !KeepClass(declaring_class)) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100852 mirror::DexCache::SetElementPtrSize(resolved_methods,
853 i,
854 resolution_method,
855 target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700856 } else {
857 // Check that the class is still in the classes table.
858 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
859 << PrettyClass(declaring_class) << " not in class linker table";
860 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700861 }
862 }
863 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700864 ArtField* field = dex_cache->GetResolvedField(i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800865 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700866 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700867 }
868 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700869 // Clean the dex field. It might have been populated during the initialization phase, but
870 // contains data only valid during a real run.
871 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700872 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700873
874 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
875 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800876
877 // Clear to save RAM.
878 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700879}
880
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800881void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700882 if (compiler_driver_.GetImageClasses() != nullptr) {
883 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700884 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700885 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700886}
887
888void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
889 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800890 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700891 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800892 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700893 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700894 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800895 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
896 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700897 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700898 }
899}
900
901void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700902 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700903 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700904 for (const std::string& image_class : *image_classes) {
905 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700906 }
907}
908
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800909void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700910 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700911 // if it is a string, we want to intern it if its not interned.
912 if (obj->GetClass()->IsStringClass()) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800913 const char* oat_filename = GetOatFilename(obj);
914 ImageInfo& image_info = GetImageInfo(oat_filename);
915
Brian Carlstrom7940e442013-07-12 13:46:57 -0700916 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800917 if (IsImageBinSlotAssigned(obj)) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800918 DCHECK_EQ(obj, image_info.intern_table_->InternStrongImageString(obj->AsString()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700919 return;
920 }
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700921 // InternImageString allows us to intern while holding the heap bitmap lock. This is safe since
922 // we are guaranteed to not have GC during image writing.
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800923 mirror::String* const interned = image_info.intern_table_->InternStrongImageString(
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700924 obj->AsString());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700925 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800926 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700927 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800928 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700929 }
930 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800931 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700932 return;
933 }
934 // else (obj == interned), nothing to do but fall through to the normal case
935 }
936
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800937 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700938}
939
Jeff Haodcdc85b2015-12-04 14:06:18 -0800940ObjectArray<Object>* ImageWriter::CreateImageRoots(const char* oat_filename) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700941 Runtime* runtime = Runtime::Current();
942 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700943 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700944 StackHandleScope<3> hs(self);
945 Handle<Class> object_array_class(hs.NewHandle(
946 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700947
Jeff Haodcdc85b2015-12-04 14:06:18 -0800948 std::unordered_set<const DexFile*> image_dex_files;
949 for (auto& pair : dex_file_oat_filename_map_) {
950 const DexFile* image_dex_file = pair.first;
951 const char* image_oat_filename = pair.second;
952 if (strcmp(oat_filename, image_oat_filename) == 0) {
953 image_dex_files.insert(image_dex_file);
954 }
955 }
956
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700957 // build an Object[] of all the DexCaches used in the source_space_.
958 // Since we can't hold the dex lock when allocating the dex_caches
959 // ObjectArray, we lock the dex lock twice, first to get the number
960 // of dex caches first and then lock it again to copy the dex
961 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800962 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700963 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700964 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800965 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800966 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
967 mirror::DexCache* dex_cache =
968 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800969 const DexFile* dex_file = dex_cache->GetDexFile();
970 if (!IsInBootImage(dex_cache)) {
971 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
972 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800973 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700974 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700975 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800976 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700977 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
978 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700979 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800980 size_t non_image_dex_caches = 0;
981 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800982 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
983 mirror::DexCache* dex_cache =
984 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800985 const DexFile* dex_file = dex_cache->GetDexFile();
986 if (!IsInBootImage(dex_cache)) {
987 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
988 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800989 }
990 CHECK_EQ(dex_cache_count, non_image_dex_caches)
991 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700992 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800993 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
994 mirror::DexCache* dex_cache =
995 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800996 const DexFile* dex_file = dex_cache->GetDexFile();
997 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800998 dex_caches->Set<false>(i, dex_cache);
999 ++i;
1000 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001001 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001002 }
1003
1004 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001005 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001006 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001007 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001008 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001009 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001010 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001011 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001012 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001013}
1014
Mathieu Chartier590fee92013-09-13 13:46:47 -07001015// Walk instance fields of the given Class. Separate function to allow recursion on the super
1016// class.
1017void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1018 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001019 StackHandleScope<1> hs(Thread::Current());
1020 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1021 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001022 if (super != nullptr) {
1023 WalkInstanceFields(obj, super);
1024 }
1025 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001026 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +00001027 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001028 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001029 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001030 if (value != nullptr) {
1031 WalkFieldsInOrder(value);
1032 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001033 field_offset = MemberOffset(field_offset.Uint32Value() +
1034 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001035 }
1036}
1037
1038// For an unvisited object, visit it then all its children found via fields.
1039void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001040 if (IsInBootImage(obj)) {
1041 // Object is in the image, don't need to fix it up.
1042 return;
1043 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001044 // Use our own visitor routine (instead of GC visitor) to get better locality between
1045 // an object and its fields
1046 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001047 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001048 StackHandleScope<2> hs(Thread::Current());
1049 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1050 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001051 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001052 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001053 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001054 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001055 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001056 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001057 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001058 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001059 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001060 if (value != nullptr) {
1061 WalkFieldsInOrder(value);
1062 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001063 field_offset = MemberOffset(field_offset.Uint32Value() +
1064 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001065 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001066 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001067 auto* as_klass = h_obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001068 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001069 LengthPrefixedArray<ArtField>* fields[] = {
1070 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1071 };
Jeff Haodcdc85b2015-12-04 14:06:18 -08001072 const char* oat_file = GetOatFilenameForDexCache(dex_cache);
1073 ImageInfo& image_info = GetImageInfo(oat_file);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001074 {
1075 // Note: This table is only accessed from the image writer, so the lock is technically
1076 // unnecessary.
1077 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1078 // Insert in the class table for this iamge.
1079 image_info.class_table_->Insert(as_klass);
1080 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001081 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1082 // Total array length including header.
1083 if (cur_fields != nullptr) {
1084 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1085 // Forward the entire array at once.
1086 auto it = native_object_relocations_.find(cur_fields);
1087 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1088 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001089 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001090 DCHECK(!IsInBootImage(cur_fields));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001091 native_object_relocations_.emplace(cur_fields,
1092 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtFieldArray });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001093 offset += header_size;
1094 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001095 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001096 // Need to forward arrays separate of fields.
1097 ArtField* field = &cur_fields->At(i);
1098 auto it2 = native_object_relocations_.find(field);
1099 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1100 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001101 DCHECK(!IsInBootImage(field));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001102 native_object_relocations_.emplace(field,
1103 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001104 offset += sizeof(ArtField);
1105 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001106 }
1107 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001108 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001109 size_t num_methods = as_klass->NumMethods();
1110 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001111 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001112 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1113 if (WillMethodBeDirty(&m)) {
1114 any_dirty = true;
1115 break;
1116 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001117 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001118 NativeObjectRelocationType type = any_dirty
1119 ? kNativeObjectRelocationTypeArtMethodDirty
1120 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001121 Bin bin_type = BinTypeForNativeRelocationType(type);
1122 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001123 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1124 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001125 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1126 method_size,
1127 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001128 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001129 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001130 CHECK(it == native_object_relocations_.end())
1131 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001132 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001133 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001134 native_object_relocations_.emplace(array,
1135 NativeObjectRelocation {
1136 oat_file,
1137 offset,
1138 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1139 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001140 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001141 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001142 AssignMethodOffset(&m, type, oat_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001143 }
Alex Lighte64300b2015-12-15 15:02:47 -08001144 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001145 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001146 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001147 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001148 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001149 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001150 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001151 mirror::Object* value = obj_array->Get(i);
1152 if (value != nullptr) {
1153 WalkFieldsInOrder(value);
1154 }
1155 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001156 } else if (h_obj->IsClassLoader()) {
1157 // Register the class loader if it has a class table.
1158 // The fake boot class loader should not get registered and we should end up with only one
1159 // class loader.
1160 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1161 if (class_loader->GetClassTable() != nullptr) {
1162 class_loaders_.insert(class_loader);
1163 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001164 }
1165 }
1166}
1167
Jeff Haodcdc85b2015-12-04 14:06:18 -08001168void ImageWriter::AssignMethodOffset(ArtMethod* method,
1169 NativeObjectRelocationType type,
1170 const char* oat_filename) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001171 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001172 auto it = native_object_relocations_.find(method);
1173 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001174 << PrettyMethod(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001175 ImageInfo& image_info = GetImageInfo(oat_filename);
1176 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
1177 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_filename, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001178 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001179}
1180
Mathieu Chartier590fee92013-09-13 13:46:47 -07001181void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1182 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1183 DCHECK(writer != nullptr);
1184 writer->WalkFieldsInOrder(obj);
1185}
1186
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001187void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1188 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1189 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001190 if (!writer->IsInBootImage(obj)) {
1191 writer->UnbinObjectsIntoOffset(obj);
1192 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001193}
1194
1195void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001196 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001197 CHECK(obj != nullptr);
1198
1199 // We know the bin slot, and the total bin sizes for all objects by now,
1200 // so calculate the object's final image offset.
1201
1202 DCHECK(IsImageBinSlotAssigned(obj));
1203 BinSlot bin_slot = GetImageBinSlot(obj);
1204 // Change the lockword from a bin slot into an offset
1205 AssignImageOffset(obj, bin_slot);
1206}
1207
Vladimir Markof4da6752014-08-01 19:04:18 +01001208void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001209 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001210 StackHandleScopeCollection handles(self);
1211 std::vector<Handle<ObjectArray<Object>>> image_roots;
1212 for (const char* oat_filename : oat_filenames_) {
1213 std::string image_filename = oat_filename;
1214 image_roots.push_back(handles.NewHandle(CreateImageRoots(image_filename.c_str())));
1215 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001216
Mathieu Chartiere401d142015-04-22 13:56:20 -07001217 auto* runtime = Runtime::Current();
1218 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001219
Mathieu Chartier31e89252013-08-28 11:29:12 -07001220 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001221 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001222 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001223
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001224 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1225 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001226 // Write the image runtime methods.
1227 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1228 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1229 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1230 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1231 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1232 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1233 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1234 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001235
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001236 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001237 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1238 auto it = native_object_relocations_.find(&image_method_array_);
1239 CHECK(it == native_object_relocations_.end());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001240 ImageInfo& default_image_info = GetImageInfo(default_oat_filename_);
1241 size_t& offset =
1242 default_image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001243 if (!compile_app_image_) {
1244 native_object_relocations_.emplace(&image_method_array_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001245 NativeObjectRelocation { default_oat_filename_, offset, image_method_type });
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001246 }
Vladimir Marko14632852015-08-17 12:07:23 +01001247 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001248 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001249 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001250 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001251 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001252 for (auto* m : image_methods_) {
1253 CHECK(m != nullptr);
1254 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001255 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1256 if (!IsInBootImage(m)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001257 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean, default_oat_filename_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001258 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001259 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001260 // Calculate size of the dex cache arrays slot and prepare offsets.
1261 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001262
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001263 // Calculate the sizes of the intern tables and class tables.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001264 for (const char* oat_filename : oat_filenames_) {
1265 ImageInfo& image_info = GetImageInfo(oat_filename);
1266 // Calculate how big the intern table will be after being serialized.
1267 InternTable* const intern_table = image_info.intern_table_.get();
1268 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1269 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001270 // Calculate the size of the class table.
1271 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1272 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001273 }
1274
Vladimir Markocf36d492015-08-12 19:27:26 +01001275 // Calculate bin slot offsets.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001276 for (const char* oat_filename : oat_filenames_) {
1277 ImageInfo& image_info = GetImageInfo(oat_filename);
1278 size_t bin_offset = image_objects_offset_begin_;
1279 for (size_t i = 0; i != kBinSize; ++i) {
1280 image_info.bin_slot_offsets_[i] = bin_offset;
1281 bin_offset += image_info.bin_slot_sizes_[i];
1282 if (i == kBinArtField) {
1283 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1284 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1285 DCHECK_ALIGNED(bin_offset, 4u);
1286 DCHECK(method_alignment == 4u || method_alignment == 8u);
1287 bin_offset = RoundUp(bin_offset, method_alignment);
1288 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001289 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001290 // NOTE: There may be additional padding between the bin slots and the intern table.
1291 DCHECK_EQ(image_info.image_end_,
1292 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001293 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001294
Jeff Haodcdc85b2015-12-04 14:06:18 -08001295 // Calculate image offsets.
1296 size_t image_offset = 0;
1297 for (const char* oat_filename : oat_filenames_) {
1298 ImageInfo& image_info = GetImageInfo(oat_filename);
1299 image_info.image_begin_ = global_image_begin_ + image_offset;
1300 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001301 ImageSection unused_sections[ImageHeader::kSectionCount];
1302 image_info.image_size_ = RoundUp(
1303 image_info.CreateImageSections(target_ptr_size_, unused_sections),
1304 kPageSize);
1305 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001306 image_offset += image_info.image_size_;
1307 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001308
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001309 // Transform each object's bin slot into an offset which will be used to do the final copy.
1310 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001311
Jeff Haodcdc85b2015-12-04 14:06:18 -08001312 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001313
Jeff Haodcdc85b2015-12-04 14:06:18 -08001314 size_t i = 0;
1315 for (const char* oat_filename : oat_filenames_) {
1316 ImageInfo& image_info = GetImageInfo(oat_filename);
1317 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1318 i++;
1319 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001320
Mathieu Chartiere401d142015-04-22 13:56:20 -07001321 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001322 for (auto& pair : native_object_relocations_) {
1323 NativeObjectRelocation& relocation = pair.second;
1324 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001325 ImageInfo& image_info = GetImageInfo(relocation.oat_filename);
1326 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001327 }
1328
Jeff Haodcdc85b2015-12-04 14:06:18 -08001329 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001330}
1331
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001332size_t ImageWriter::ImageInfo::CreateImageSections(size_t target_ptr_size,
1333 ImageSection* out_sections) const {
1334 DCHECK(out_sections != nullptr);
1335 // Objects section
1336 auto* objects_section = &out_sections[ImageHeader::kSectionObjects];
1337 *objects_section = ImageSection(0u, image_end_);
1338 size_t cur_pos = objects_section->End();
1339 // Add field section.
1340 auto* field_section = &out_sections[ImageHeader::kSectionArtFields];
1341 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
1342 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
1343 cur_pos = field_section->End();
1344 // Round up to the alignment the required by the method section.
1345 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size));
1346 // Add method section.
1347 auto* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1348 *methods_section = ImageSection(cur_pos,
1349 bin_slot_sizes_[kBinArtMethodClean] +
1350 bin_slot_sizes_[kBinArtMethodDirty]);
1351 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
1352 cur_pos = methods_section->End();
1353 // Add dex cache arrays section.
1354 auto* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1355 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1356 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1357 cur_pos = dex_cache_arrays_section->End();
1358 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1359 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1360 // Calculate the size of the interned strings.
1361 auto* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
1362 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1363 cur_pos = interned_strings_section->End();
1364 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1365 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1366 // Calculate the size of the class table section.
1367 auto* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001368 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001369 cur_pos = class_table_section->End();
1370 // Image end goes right before the start of the image bitmap.
1371 return cur_pos;
1372}
1373
Vladimir Markof4da6752014-08-01 19:04:18 +01001374void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
1375 CHECK_NE(0U, oat_loaded_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001376 const char* oat_filename = oat_file_->GetLocation().c_str();
1377 ImageInfo& image_info = GetImageInfo(oat_filename);
1378 const uint8_t* oat_file_begin = GetOatFileBegin(oat_filename);
Ian Rogers13735952014-10-08 12:43:28 -07001379 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001380 image_info.oat_data_begin_ = const_cast<uint8_t*>(oat_file_begin) + oat_data_offset;
1381 const uint8_t* oat_data_end = image_info.oat_data_begin_ + oat_file_->Size();
1382 image_info.oat_size_ = oat_file_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001383
1384 // Create the image sections.
1385 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001386 const size_t image_end = image_info.CreateImageSections(target_ptr_size_, sections);
1387
Mathieu Chartiere401d142015-04-22 13:56:20 -07001388 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001389 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001390 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001391 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001392 if (VLOG_IS_ON(compiler)) {
1393 LOG(INFO) << "Creating header for " << oat_filename;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001394 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001395 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001396 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1397 ++idx;
1398 }
1399 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001400 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1401 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1402 << " Image offset=" << image_info.image_offset_ << std::dec;
1403 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1404 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1405 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1406 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001407 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001408
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001409 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1410 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001411 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1412 image_end,
1413 sections,
1414 image_info.image_roots_address_,
1415 oat_file_->GetOatHeader().GetChecksum(),
1416 PointerToLowMemUInt32(oat_file_begin),
1417 PointerToLowMemUInt32(image_info.oat_data_begin_),
1418 PointerToLowMemUInt32(oat_data_end),
1419 PointerToLowMemUInt32(oat_file_end),
1420 target_ptr_size_,
1421 compile_pic_,
1422 image_storage_mode_,
1423 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001424}
1425
1426ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001427 auto it = native_object_relocations_.find(method);
1428 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001429 const char* oat_filename = GetOatFilename(method->GetDexCache());
1430 ImageInfo& image_info = GetImageInfo(oat_filename);
1431 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1432 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001433}
1434
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001435class FixupRootVisitor : public RootVisitor {
1436 public:
1437 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1438 }
1439
1440 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001441 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001442 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001443 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001444 }
1445 }
1446
1447 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1448 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001449 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001450 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001451 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001452 }
1453 }
1454
1455 private:
1456 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001457};
1458
Mathieu Chartierc7853442015-03-27 14:35:38 -07001459void ImageWriter::CopyAndFixupNativeData() {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001460 const char* oat_filename = oat_file_->GetLocation().c_str();
1461 ImageInfo& image_info = GetImageInfo(oat_filename);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001462 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001463 for (auto& pair : native_object_relocations_) {
1464 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001465 // Only work with fields and methods that are in the current oat file.
1466 if (strcmp(relocation.oat_filename, oat_filename) != 0) {
1467 continue;
1468 }
1469 auto* dest = image_info.image_->Begin() + relocation.offset;
1470 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001471 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001472 switch (relocation.type) {
1473 case kNativeObjectRelocationTypeArtField: {
1474 memcpy(dest, pair.first, sizeof(ArtField));
1475 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1476 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1477 break;
1478 }
1479 case kNativeObjectRelocationTypeArtMethodClean:
1480 case kNativeObjectRelocationTypeArtMethodDirty: {
1481 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001482 reinterpret_cast<ArtMethod*>(dest),
1483 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001484 break;
1485 }
1486 // For arrays, copy just the header since the elements will get copied by their corresponding
1487 // relocations.
1488 case kNativeObjectRelocationTypeArtFieldArray: {
1489 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1490 break;
1491 }
1492 case kNativeObjectRelocationTypeArtMethodArrayClean:
1493 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001494 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1495 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001496 ArtMethod::Size(target_ptr_size_),
1497 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001498 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001499 case kNativeObjectRelocationTypeDexCacheArray:
1500 // Nothing to copy here, everything is done in FixupDexCache().
1501 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001502 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001503 }
1504 }
1505 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001506 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001507 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001508 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001509 ArtMethod* method = image_methods_[i];
1510 CHECK(method != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001511 // Only place runtime methods in the image of the default oat file.
1512 if (method->IsRuntimeMethod() && strcmp(default_oat_filename_, oat_filename) != 0) {
1513 continue;
1514 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001515 if (!IsInBootImage(method)) {
1516 auto it = native_object_relocations_.find(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001517 CHECK(it != native_object_relocations_.end()) << "No forwarding for " << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001518 NativeObjectRelocation& relocation = it->second;
1519 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1520 << methods_section;
1521 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001522 method = reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001523 }
1524 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001525 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001526 FixupRootVisitor root_visitor(this);
1527
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001528 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001529 if (image_info.intern_table_bytes_ > 0) {
1530 const ImageSection& intern_table_section = image_header->GetImageSection(
1531 ImageHeader::kSectionInternedStrings);
1532 InternTable* const intern_table = image_info.intern_table_.get();
1533 uint8_t* const intern_table_memory_ptr =
1534 image_info.image_->Begin() + intern_table_section.Offset();
1535 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1536 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1537 // Fixup the pointers in the newly written intern table to contain image addresses.
1538 InternTable temp_intern_table;
1539 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1540 // the VisitRoots() will update the memory directly rather than the copies.
1541 // This also relies on visit roots not doing any verification which could fail after we update
1542 // the roots to be the image addresses.
1543 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1544 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1545 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1546 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001547 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1548 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001549 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001550 const ImageSection& class_table_section = image_header->GetImageSection(
1551 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001552 uint8_t* const class_table_memory_ptr =
1553 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001554 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001555
1556 ClassTable* table = image_info.class_table_.get();
1557 CHECK(table != nullptr);
1558 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1559 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1560 // Fixup the pointers in the newly written class table to contain image addresses. See
1561 // above comment for intern tables.
1562 ClassTable temp_class_table;
1563 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1564 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1565 table->NumZygoteClasses());
1566 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1567 RootInfo(kRootUnknown));
1568 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001569 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001570}
1571
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001572void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001573 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001574 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1575 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001576 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001577 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001578 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1579 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001580 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001581 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001582}
1583
Mathieu Chartier590fee92013-09-13 13:46:47 -07001584void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001585 DCHECK(obj != nullptr);
1586 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001587 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1588}
1589
Mathieu Chartiere401d142015-04-22 13:56:20 -07001590void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1591 mirror::Class* klass, Bin array_type) {
1592 CHECK(klass->IsArrayClass());
1593 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1594 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001595 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001596 dst->SetClass(GetImageAddress(arr->GetClass()));
1597 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001598 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001599 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1600 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001601 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001602 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001603 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001604 auto* method = reinterpret_cast<ArtMethod*>(elem);
1605 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1606 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1607 << PrettyClass(method->GetDeclaringClass());
1608 } else {
1609 CHECK_EQ(array_type, kBinArtField);
1610 auto* field = reinterpret_cast<ArtField*>(elem);
1611 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1612 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1613 << PrettyClass(field->GetDeclaringClass());
1614 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001615 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001616 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001617 ImageInfo& image_info = GetImageInfo(it->second.oat_filename);
1618 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001619 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001620 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001621 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001622 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001623}
1624
1625void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001626 if (IsInBootImage(obj)) {
1627 return;
1628 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001629 size_t offset = GetImageOffset(obj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001630 const char* oat_filename = GetOatFilename(obj);
1631 ImageInfo& image_info = GetImageInfo(oat_filename);
1632 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1633 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001634 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001635
Jeff Haodcdc85b2015-12-04 14:06:18 -08001636 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001637
1638 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001639 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001640 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001641
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001642 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1643 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001644 const auto it = saved_hashcode_map_.find(obj);
1645 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1646 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001647 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001648}
1649
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001650// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001651class FixupVisitor {
1652 public:
1653 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1654 }
1655
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001656 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1657 // with other logic.
1658 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1659 const {}
1660 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1661
1662
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001663 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001664 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001665 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001666 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1667 // image.
1668 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001669 offset,
1670 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001671 }
1672
1673 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001674 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001675 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001676 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001677 mirror::Reference::ReferentOffset(),
1678 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001679 }
1680
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001681 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001682 ImageWriter* const image_writer_;
1683 mirror::Object* const copy_;
1684};
1685
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001686class FixupClassVisitor FINAL : public FixupVisitor {
1687 public:
1688 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1689 }
1690
Mathieu Chartierc7853442015-03-27 14:35:38 -07001691 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001692 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001693 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001694 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001695 }
1696
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001697 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1698 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001699 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001700 LOG(FATAL) << "Reference not expected here.";
1701 }
1702};
1703
Vladimir Marko05792b92015-08-03 11:56:49 +01001704uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1705 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001706 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001707 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001708 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1709 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001710 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001711 return relocation.offset;
1712}
1713
1714template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001715T* ImageWriter::NativeLocationInImage(T* obj, const char* oat_filename) {
1716 if (obj == nullptr || IsInBootImage(obj)) {
1717 return obj;
1718 } else {
1719 ImageInfo& image_info = GetImageInfo(oat_filename);
1720 return reinterpret_cast<T*>(image_info.image_begin_ + NativeOffsetInImage(obj));
1721 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001722}
1723
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001724template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001725T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1726 if (obj == nullptr || IsInBootImage(obj)) {
1727 return obj;
1728 } else {
1729 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
1730 ImageInfo& image_info = GetImageInfo(oat_filename);
1731 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1732 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001733}
1734
1735class NativeLocationVisitor {
1736 public:
Jeff Haodcdc85b2015-12-04 14:06:18 -08001737 explicit NativeLocationVisitor(ImageWriter* image_writer, const char* oat_filename)
1738 : image_writer_(image_writer), oat_filename_(oat_filename) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001739
1740 template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001741 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1742 return image_writer_->NativeLocationInImage(ptr, oat_filename_);
1743 }
1744
1745 ArtMethod* operator()(ArtMethod* method) const SHARED_REQUIRES(Locks::mutator_lock_) {
1746 const char* oat_filename = method->IsRuntimeMethod() ? image_writer_->GetDefaultOatFilename() :
1747 image_writer_->GetOatFilenameForDexCache(method->GetDexCache());
1748 return image_writer_->NativeLocationInImage(method, oat_filename);
1749 }
1750
1751 ArtField* operator()(ArtField* field) const SHARED_REQUIRES(Locks::mutator_lock_) {
1752 const char* oat_filename = image_writer_->GetOatFilenameForDexCache(field->GetDexCache());
1753 return image_writer_->NativeLocationInImage(field, oat_filename);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001754 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001755
1756 private:
1757 ImageWriter* const image_writer_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001758 const char* oat_filename_;
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001759};
1760
1761void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001762 const char* oat_filename = GetOatFilename(orig);
1763 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this, oat_filename));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001764 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001765 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001766}
1767
Ian Rogersef7d42f2014-01-06 12:55:46 -08001768void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001769 DCHECK(orig != nullptr);
1770 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001771 if (kUseBakerOrBrooksReadBarrier) {
1772 orig->AssertReadBarrierPointer();
1773 if (kUseBrooksReadBarrier) {
1774 // Note the address 'copy' isn't the same as the image address of 'orig'.
1775 copy->SetReadBarrierPointer(GetImageAddress(orig));
1776 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1777 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001778 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001779 auto* klass = orig->GetClass();
1780 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001781 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001782 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1783 if (it != pointer_arrays_.end()) {
1784 // Should only need to fixup every pointer array exactly once.
1785 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1786 pointer_arrays_.erase(it);
1787 return;
1788 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001789 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001790 if (orig->IsClass()) {
1791 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001792 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001793 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1794 // Need to go update the ArtMethod.
1795 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1796 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1797 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001798 auto it = native_object_relocations_.find(src_method);
1799 CHECK(it != native_object_relocations_.end())
1800 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001801 dest->SetArtMethod(
Jeff Haodcdc85b2015-12-04 14:06:18 -08001802 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001803 } else if (!klass->IsArrayClass()) {
1804 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1805 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1806 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001807 } else if (klass->IsClassLoaderClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001808 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1809 // ClassLoader.
1810 down_cast<mirror::ClassLoader*>(copy)->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001811 // Also set allocator to null to be safe. The allocator is created when we create the class
1812 // table. We also never expect to unload things in the image since they are held live as
1813 // roots.
1814 down_cast<mirror::ClassLoader*>(copy)->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001815 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001816 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001817 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001818 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001819 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001820}
1821
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001822
1823class ImageAddressVisitor {
1824 public:
1825 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1826
1827 template <typename T>
1828 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1829 return image_writer_->GetImageAddress(ptr);
1830 }
1831
1832 private:
1833 ImageWriter* const image_writer_;
1834};
1835
1836
Vladimir Marko05792b92015-08-03 11:56:49 +01001837void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1838 mirror::DexCache* copy_dex_cache) {
1839 // Though the DexCache array fields are usually treated as native pointers, we set the full
1840 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1841 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1842 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Jeff Haodcdc85b2015-12-04 14:06:18 -08001843 const char* oat_filename = GetOatFilenameForDexCache(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001844 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1845 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001846 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001847 NativeLocationInImage(orig_strings, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001848 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001849 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
1850 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001851 }
1852 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1853 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001854 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001855 NativeLocationInImage(orig_types, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001856 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001857 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
1858 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001859 }
1860 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1861 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001862 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001863 NativeLocationInImage(orig_methods, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001864 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001865 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001866 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1867 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001868 const char* method_oat_filename;
1869 if (orig == nullptr || orig->IsRuntimeMethod()) {
1870 method_oat_filename = default_oat_filename_;
1871 } else {
1872 method_oat_filename = GetOatFilenameForDexCache(orig->GetDexCache());
1873 }
1874 ArtMethod* copy = NativeLocationInImage(orig, method_oat_filename);
Vladimir Marko05792b92015-08-03 11:56:49 +01001875 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1876 }
1877 }
1878 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1879 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001880 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001881 NativeLocationInImage(orig_fields, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001882 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001883 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001884 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1885 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001886 const char* field_oat_filename =
1887 orig == nullptr ? default_oat_filename_ : GetOatFilenameForDexCache(orig->GetDexCache());
1888 ArtField* copy = NativeLocationInImage(orig, field_oat_filename);
Vladimir Marko05792b92015-08-03 11:56:49 +01001889 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1890 }
1891 }
1892}
1893
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001894const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1895 DCHECK_LT(type, kOatAddressCount);
1896 // If we are compiling an app image, we need to use the stubs of the boot image.
1897 if (compile_app_image_) {
1898 // Use the current image pointers.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001899 std::vector<gc::space::ImageSpace*> image_spaces =
1900 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1901 DCHECK(!image_spaces.empty());
1902 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001903 CHECK(oat_file != nullptr);
1904 const OatHeader& header = oat_file->GetOatHeader();
1905 switch (type) {
1906 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1907 case kOatAddressQuickGenericJNITrampoline:
1908 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1909 case kOatAddressInterpreterToInterpreterBridge:
1910 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1911 case kOatAddressInterpreterToCompiledCodeBridge:
1912 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1913 case kOatAddressJNIDlsymLookup:
1914 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1915 case kOatAddressQuickIMTConflictTrampoline:
1916 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1917 case kOatAddressQuickResolutionTrampoline:
1918 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1919 case kOatAddressQuickToInterpreterBridge:
1920 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1921 default:
1922 UNREACHABLE();
1923 }
1924 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001925 const ImageInfo& primary_image_info = GetImageInfo(0);
1926 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001927}
1928
Jeff Haodcdc85b2015-12-04 14:06:18 -08001929const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
1930 const ImageInfo& image_info,
1931 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001932 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
1933 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
1934 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07001935 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001936 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001937
1938 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1939 // trampoline.
1940
1941 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001942 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1943 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001944 const uint8_t* quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001945 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001946 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
1947 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001948 // We have code for a non-static or initialized method, just use the code.
1949 } else if (quick_code == nullptr && method->IsNative() &&
1950 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1951 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001952 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001953 } else if (quick_code == nullptr && !method->IsNative()) {
1954 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001955 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001956 *quick_is_interpreted = true;
1957 } else {
1958 CHECK(!method->GetDeclaringClass()->IsInitialized());
1959 // We have code for a static method, but need to go through the resolution stub for class
1960 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001961 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
1962 }
1963 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001964 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001965 }
1966 return quick_code;
1967}
1968
Jeff Haodcdc85b2015-12-04 14:06:18 -08001969void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
1970 ArtMethod* copy,
1971 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01001972 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001973
1974 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01001975
Jeff Haodcdc85b2015-12-04 14:06:18 -08001976 const char* oat_filename;
Mathieu Chartiere467cea2016-01-07 18:36:19 -08001977 if (orig->IsRuntimeMethod() || compile_app_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001978 oat_filename = default_oat_filename_;
1979 } else {
1980 auto it = dex_file_oat_filename_map_.find(orig->GetDexFile());
1981 DCHECK(it != dex_file_oat_filename_map_.end()) << orig->GetDexFile()->GetLocation();
1982 oat_filename = it->second;
1983 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001984 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001985 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods, oat_filename),
1986 target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01001987 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001988 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types, oat_filename),
1989 target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001990
Ian Rogers848871b2013-08-05 10:56:33 -07001991 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1992 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07001993
Ian Rogers848871b2013-08-05 10:56:33 -07001994 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001995 Runtime* runtime = Runtime::Current();
1996 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001997 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001998 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001999 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
2000 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002001 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002002 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002003 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
2004 bool found_one = false;
2005 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2006 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2007 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2008 found_one = true;
2009 break;
2010 }
2011 }
2012 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2013 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002014 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002015 // We assume all methods have code. If they don't currently then we set them to the use the
2016 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2017 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002018 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002019 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002020 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002021 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002022 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002023 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002024 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002025
Sebastien Hertze1d07812014-05-21 15:44:09 +02002026 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002027 if (orig->IsNative()) {
2028 // The native method's pointer is set to a stub to lookup via dlsym.
2029 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002030 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002031 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002032 }
2033 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002034 }
2035}
2036
Alex Lighta59dd802014-07-02 16:28:08 -07002037static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07002038 uint64_t data_sec_offset;
2039 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
2040 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07002041 return nullptr;
2042 }
Tong Shen62d1ca32014-09-03 17:24:56 -07002043 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08002044}
2045
Vladimir Markof4da6752014-08-01 19:04:18 +01002046void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07002047 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -08002048 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file,
2049 PROT_READ | PROT_WRITE,
2050 MAP_SHARED,
2051 &error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07002052 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002053 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07002054 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002055 }
Alex Lighta59dd802014-07-02 16:28:08 -07002056 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
2057 CHECK(oat_header != nullptr);
2058 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002059
Jeff Haodcdc85b2015-12-04 14:06:18 -08002060 ImageInfo& image_info = GetImageInfo(oat_file_->GetLocation().c_str());
2061 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07002062 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002063}
2064
Jeff Haodcdc85b2015-12-04 14:06:18 -08002065size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002066 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002067 return std::accumulate(&image_info.bin_slot_sizes_[0],
2068 &image_info.bin_slot_sizes_[up_to],
2069 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002070}
2071
2072ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2073 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002074 static_assert(kBinBits == 3, "wrong number of bin bits");
2075 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002076 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2077
2078 DCHECK_LT(GetBin(), kBinSize);
2079 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2080}
2081
2082ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2083 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2084 DCHECK_EQ(index, GetIndex());
2085}
2086
2087ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2088 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2089}
2090
2091uint32_t ImageWriter::BinSlot::GetIndex() const {
2092 return lockword_ & ~kBinMask;
2093}
2094
Jeff Haodcdc85b2015-12-04 14:06:18 -08002095uint8_t* ImageWriter::GetOatFileBegin(const char* oat_filename) const {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002096 uintptr_t last_image_end = 0;
2097 for (const char* oat_fn : oat_filenames_) {
2098 const ImageInfo& image_info = GetConstImageInfo(oat_fn);
2099 DCHECK(image_info.image_begin_ != nullptr);
2100 uintptr_t this_end = reinterpret_cast<uintptr_t>(image_info.image_begin_) +
2101 image_info.image_size_;
2102 last_image_end = std::max(this_end, last_image_end);
2103 }
2104 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
2105 return reinterpret_cast<uint8_t*>(last_image_end) + image_info.oat_offset_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002106}
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
Jeff Haodcdc85b2015-12-04 14:06:18 -08002125const char* ImageWriter::GetOatFilename(mirror::Object* obj) const {
2126 if (compile_app_image_) {
2127 return default_oat_filename_;
2128 } else {
2129 return GetOatFilenameForDexCache(obj->IsDexCache() ? obj->AsDexCache() :
2130 obj->IsClass() ? obj->AsClass()->GetDexCache() : obj->GetClass()->GetDexCache());
2131 }
2132}
2133
2134const char* ImageWriter::GetOatFilenameForDexCache(mirror::DexCache* dex_cache) const {
2135 if (compile_app_image_ || dex_cache == nullptr) {
2136 return default_oat_filename_;
2137 } else {
2138 auto it = dex_file_oat_filename_map_.find(dex_cache->GetDexFile());
2139 DCHECK(it != dex_file_oat_filename_map_.end()) << dex_cache->GetDexFile()->GetLocation();
2140 return it->second;
2141 }
2142}
2143
2144ImageWriter::ImageInfo& ImageWriter::GetImageInfo(const char* oat_filename) {
2145 auto it = image_info_map_.find(oat_filename);
2146 DCHECK(it != image_info_map_.end());
2147 return it->second;
2148}
2149
2150const ImageWriter::ImageInfo& ImageWriter::GetConstImageInfo(const char* oat_filename) const {
2151 auto it = image_info_map_.find(oat_filename);
2152 DCHECK(it != image_info_map_.end());
2153 return it->second;
2154}
2155
2156const ImageWriter::ImageInfo& ImageWriter::GetImageInfo(size_t index) const {
2157 DCHECK_LT(index, oat_filenames_.size());
2158 return GetConstImageInfo(oat_filenames_[index]);
2159}
2160
2161void ImageWriter::UpdateOatFile(const char* oat_filename) {
2162 std::unique_ptr<File> oat_file(OS::OpenFileForReading(oat_filename));
2163 DCHECK(oat_file != nullptr);
2164 size_t oat_loaded_size = 0;
2165 size_t oat_data_offset = 0;
2166 ElfWriter::GetOatElfInformation(oat_file.get(), &oat_loaded_size, &oat_data_offset);
2167
2168 ImageInfo& cur_image_info = GetImageInfo(oat_filename);
2169
2170 // Update the oat_offset of the next image info.
2171 auto it = std::find(oat_filenames_.begin(), oat_filenames_.end(), oat_filename);
2172 DCHECK(it != oat_filenames_.end());
2173
2174 it++;
2175 if (it != oat_filenames_.end()) {
2176 // There is a following one.
2177 ImageInfo& next_image_info = GetImageInfo(*it);
2178 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2179 }
2180}
2181
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002182ImageWriter::ImageWriter(
2183 const CompilerDriver& compiler_driver,
2184 uintptr_t image_begin,
2185 bool compile_pic,
2186 bool compile_app_image,
2187 ImageHeader::StorageMode image_storage_mode,
2188 const std::vector<const char*> oat_filenames,
2189 const std::unordered_map<const DexFile*, const char*>& dex_file_oat_filename_map)
2190 : compiler_driver_(compiler_driver),
2191 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2192 image_objects_offset_begin_(0),
2193 oat_file_(nullptr),
2194 compile_pic_(compile_pic),
2195 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002196 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
2197 image_method_array_(ImageHeader::kImageMethodsCount),
2198 dirty_methods_(0u),
2199 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002200 image_storage_mode_(image_storage_mode),
2201 dex_file_oat_filename_map_(dex_file_oat_filename_map),
2202 oat_filenames_(oat_filenames),
2203 default_oat_filename_(oat_filenames[0]) {
2204 CHECK_NE(image_begin, 0U);
2205 for (const char* oat_filename : oat_filenames) {
2206 image_info_map_.emplace(oat_filename, ImageInfo());
2207 }
2208 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
2209}
2210
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002211ImageWriter::ImageInfo::ImageInfo()
2212 : intern_table_(new InternTable),
2213 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002214
Brian Carlstrom7940e442013-07-12 13:46:57 -07002215} // namespace art