blob: 9cac8b47fbed7e3518f83d7323e416ec9ff21b15 [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>
20
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Vladimir Marko20f85592015-03-19 10:07:02 +000022#include <numeric>
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080023#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070024#include <vector>
25
Mathieu Chartierc7853442015-03-27 14:35:38 -070026#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070027#include "art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070028#include "base/logging.h"
29#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010030#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070031#include "compiled_method.h"
32#include "dex_file-inl.h"
33#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070034#include "elf_file.h"
35#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070036#include "elf_writer.h"
37#include "gc/accounting/card_table-inl.h"
38#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070039#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070040#include "gc/heap.h"
41#include "gc/space/large_object_space.h"
42#include "gc/space/space-inl.h"
43#include "globals.h"
44#include "image.h"
45#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070046#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070047#include "lock_word.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070048#include "mirror/abstract_method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "mirror/array-inl.h"
50#include "mirror/class-inl.h"
51#include "mirror/class_loader.h"
52#include "mirror/dex_cache-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070053#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "mirror/object-inl.h"
55#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070056#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070057#include "oat.h"
58#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070059#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "runtime.h"
61#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070062#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000063#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070065using ::art::mirror::Class;
66using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070067using ::art::mirror::Object;
68using ::art::mirror::ObjectArray;
69using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070070
71namespace art {
72
Igor Murashkinf5b4c502014-11-14 15:01:59 -080073// Separate objects into multiple bins to optimize dirty memory use.
74static constexpr bool kBinObjects = true;
75
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080076// Return true if an object is already in an image space.
77bool ImageWriter::IsInBootImage(const void* obj) const {
78 if (!compile_app_image_) {
79 DCHECK(boot_image_space_ == nullptr);
80 return false;
81 }
82 const uint8_t* image_begin = boot_image_space_->Begin();
83 // Real image end including ArtMethods and ArtField sections.
84 const uint8_t* image_end = image_begin + boot_image_space_->GetImageHeader().GetImageSize();
85 return image_begin <= obj && obj < image_end;
86}
87
88bool ImageWriter::IsInBootOatFile(const void* ptr) const {
89 if (!compile_app_image_) {
90 DCHECK(boot_image_space_ == nullptr);
91 return false;
92 }
93 const ImageHeader& image_header = boot_image_space_->GetImageHeader();
94 return image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd();
95}
96
Andreas Gampedd9d0552015-03-09 12:57:41 -070097static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -070098 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -070099 Class* klass = obj->GetClass();
100 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
101}
102
103static void CheckNoDexObjects() {
104 ScopedObjectAccess soa(Thread::Current());
105 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
106}
107
Vladimir Markof4da6752014-08-01 19:04:18 +0100108bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800109 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800110 gc::Heap* const heap = Runtime::Current()->GetHeap();
111 // Cache boot image space.
112 for (gc::space::ContinuousSpace* space : heap->GetContinuousSpaces()) {
113 if (space->IsImageSpace()) {
114 CHECK(compile_app_image_);
115 CHECK(boot_image_space_ == nullptr) << "Multiple image spaces";
116 boot_image_space_ = space->AsImageSpace();
117 }
118 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100119 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700120 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100121 PruneNonImageClasses(); // Remove junk
122 ComputeLazyFieldsForImageClasses(); // Add useful information
Vladimir Markof4da6752014-08-01 19:04:18 +0100123 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100124 heap->CollectGarbage(false); // Remove garbage.
125
Andreas Gampedd9d0552015-03-09 12:57:41 -0700126 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
127 // dex files.
128 //
129 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
130 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
131 // true.
132 if (kIsDebugBuild) {
133 CheckNoDexObjects();
134 }
135
Vladimir Markof4da6752014-08-01 19:04:18 +0100136 if (kIsDebugBuild) {
137 ScopedObjectAccess soa(Thread::Current());
138 CheckNonImageClassesRemoved();
139 }
140
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700141 {
142 ScopedObjectAccess soa(Thread::Current());
143 CalculateNewObjectOffsets();
144 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100145
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700146 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
147 // bin size sums being calculated.
148 if (!AllocMemory()) {
149 return false;
150 }
151
Vladimir Markof4da6752014-08-01 19:04:18 +0100152 return true;
153}
154
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700155bool ImageWriter::Write(int image_fd,
156 const std::string& image_filename,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700157 const std::string& oat_filename,
158 const std::string& oat_location) {
159 CHECK(!image_filename.empty());
160
Ian Rogers700a4022014-05-19 16:49:03 -0700161 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700162 if (oat_file.get() == nullptr) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800163 PLOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700164 return false;
165 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700166 std::string error_msg;
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700167 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, nullptr, &error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700168 if (oat_file_ == nullptr) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800169 PLOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700170 << ": " << error_msg;
Andreas Gampe0b7fcf92015-03-13 16:54:54 -0700171 oat_file->Erase();
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700172 return false;
173 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700174 Runtime::Current()->GetOatFileManager().RegisterOatFile(
175 std::unique_ptr<const OatFile>(oat_file_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700176
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800177 const OatHeader& oat_header = oat_file_->GetOatHeader();
178 oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
179 oat_header.GetInterpreterToInterpreterBridgeOffset();
180 oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
181 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
182 oat_address_offsets_[kOatAddressJNIDlsymLookup] =
183 oat_header.GetJniDlsymLookupOffset();
184 oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
185 oat_header.GetQuickGenericJniTrampolineOffset();
186 oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
187 oat_header.GetQuickImtConflictTrampolineOffset();
188 oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
189 oat_header.GetQuickResolutionTrampolineOffset();
190 oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
191 oat_header.GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700192
Brian Carlstrom7940e442013-07-12 13:46:57 -0700193 size_t oat_loaded_size = 0;
194 size_t oat_data_offset = 0;
Vladimir Marko3fc99032015-05-13 19:06:30 +0100195 ElfWriter::GetOatElfInformation(oat_file.get(), &oat_loaded_size, &oat_data_offset);
Alex Light53cb16b2014-06-12 11:26:29 -0700196
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700197 {
198 ScopedObjectAccess soa(Thread::Current());
199 CreateHeader(oat_loaded_size, oat_data_offset);
200 CopyAndFixupNativeData();
201 // TODO: heap validation can't handle these fix up passes.
202 Runtime::Current()->GetHeap()->DisableObjectValidation();
203 CopyAndFixupObjects();
204 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700205
Vladimir Markof4da6752014-08-01 19:04:18 +0100206 SetOatChecksumFromElfFile(oat_file.get());
207
Andreas Gampe4303ba92014-11-06 01:00:46 -0800208 if (oat_file->FlushCloseOrErase() != 0) {
209 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename << " for " << oat_location;
210 return false;
211 }
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700212 std::unique_ptr<File> image_file;
213 if (image_fd != kInvalidImageFd) {
214 image_file.reset(new File(image_fd, image_filename, unix_file::kCheckSafeUsage));
215 } else {
216 image_file.reset(OS::CreateEmptyFile(image_filename.c_str()));
217 }
218 if (image_file == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700219 LOG(ERROR) << "Failed to open image file " << image_filename;
220 return false;
221 }
222 if (fchmod(image_file->Fd(), 0644) != 0) {
223 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800224 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700225 return EXIT_FAILURE;
226 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700227
Mathieu Chartiere401d142015-04-22 13:56:20 -0700228 // Write out the image + fields + methods.
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700229 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700230 const auto write_count = image_header->GetImageSize();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700231 if (!image_file->WriteFully(image_->Begin(), write_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700232 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800233 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700234 return false;
235 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700236
237 // Write out the image bitmap at the page aligned start of the image end.
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700238 const ImageSection& bitmap_section = image_header->GetImageSection(
239 ImageHeader::kSectionImageBitmap);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700240 CHECK_ALIGNED(bitmap_section.Offset(), kPageSize);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700241 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700242 bitmap_section.Size(), bitmap_section.Offset())) {
Mathieu Chartier31e89252013-08-28 11:29:12 -0700243 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800244 image_file->Erase();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700245 return false;
246 }
247
Mathieu Chartiere401d142015-04-22 13:56:20 -0700248 CHECK_EQ(bitmap_section.End(), static_cast<size_t>(image_file->GetLength()));
Andreas Gampe4303ba92014-11-06 01:00:46 -0800249 if (image_file->FlushCloseOrErase() != 0) {
250 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
251 return false;
252 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700253 return true;
254}
255
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700256void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700257 DCHECK(object != nullptr);
258 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800259
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800260 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700261 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700262 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700263 DCHECK(IsImageOffsetAssigned(object));
264}
265
Mathieu Chartiere401d142015-04-22 13:56:20 -0700266void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
267 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
268 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
269 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
270}
271
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800272void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700273 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800274 DCHECK_NE(image_objects_offset_begin_, 0u);
275
Vladimir Markocf36d492015-08-12 19:27:26 +0100276 size_t bin_slot_offset = bin_slot_offsets_[bin_slot.GetBin()];
277 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800278 DCHECK_ALIGNED(new_offset, kObjectAlignment);
279
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700280 SetImageOffset(object, new_offset);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800281 DCHECK_LT(new_offset, image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700282}
283
Ian Rogersef7d42f2014-01-06 12:55:46 -0800284bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800285 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700286 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700287 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700288}
289
Ian Rogersef7d42f2014-01-06 12:55:46 -0800290size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700291 DCHECK(object != nullptr);
292 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700293 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700294 size_t offset = lock_word.ForwardingAddress();
295 DCHECK_LT(offset, image_end_);
296 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700297}
298
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800299void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
300 DCHECK(object != nullptr);
301 DCHECK(!IsImageOffsetAssigned(object));
302 DCHECK(!IsImageBinSlotAssigned(object));
303
304 // Before we stomp over the lock word, save the hash code for later.
305 Monitor::Deflate(Thread::Current(), object);;
306 LockWord lw(object->GetLockWord(false));
307 switch (lw.GetState()) {
308 case LockWord::kFatLocked: {
309 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
310 break;
311 }
312 case LockWord::kThinLocked: {
313 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
314 break;
315 }
316 case LockWord::kUnlocked:
317 // No hash, don't need to save it.
318 break;
319 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700320 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
321 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800322 break;
323 default:
324 LOG(FATAL) << "Unreachable.";
325 UNREACHABLE();
326 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700327 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700328 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800329 DCHECK(IsImageBinSlotAssigned(object));
330}
331
Vladimir Marko20f85592015-03-19 10:07:02 +0000332void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000333 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
334 uint32_t size = 0u;
335 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
336 dex_cache_array_starts_.Put(dex_file, size);
337 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
338 size += layout.Size();
339 }
340 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
341 // when AssignImageBinSlot() assigns their indexes out or order.
342 bin_slot_sizes_[kBinDexCacheArray] = size;
343
Vladimir Marko20f85592015-03-19 10:07:02 +0000344 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700345 Thread* const self = Thread::Current();
346 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800347 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700348 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800349 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800350 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700351 continue;
352 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000353 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700354 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000355 DCHECK(layout.Valid());
Vladimir Markof60c7e22015-11-23 18:05:08 +0000356 uint32_t start = dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100357 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Vladimir Markof60c7e22015-11-23 18:05:08 +0000358 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(), start + layout.TypesOffset());
Vladimir Marko05792b92015-08-03 11:56:49 +0100359 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Vladimir Markof60c7e22015-11-23 18:05:08 +0000360 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(), start + layout.MethodsOffset());
Vladimir Marko05792b92015-08-03 11:56:49 +0100361 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Vladimir Markof60c7e22015-11-23 18:05:08 +0000362 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(), start + layout.FieldsOffset());
Vladimir Marko05792b92015-08-03 11:56:49 +0100363 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Vladimir Markof60c7e22015-11-23 18:05:08 +0000364 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset());
Vladimir Marko20f85592015-03-19 10:07:02 +0000365 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000366}
367
Vladimir Marko05792b92015-08-03 11:56:49 +0100368void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset) {
369 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800370 DCHECK(!IsInBootImage(array));
Vladimir Marko05792b92015-08-03 11:56:49 +0100371 native_object_relocations_.emplace(
372 array,
373 NativeObjectRelocation { offset, kNativeObjectRelocationTypeDexCacheArray });
374 }
375}
376
Mathieu Chartiere401d142015-04-22 13:56:20 -0700377void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
378 DCHECK(arr != nullptr);
379 if (kIsDebugBuild) {
380 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800381 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700382 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800383 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800384 CHECK(klass == nullptr || KeepClass(klass))
385 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700386 }
387 }
388 }
389 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
390 // ArtMethods.
391 pointer_arrays_.emplace(arr, kBinArtMethodClean);
392}
393
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800394void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
395 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800396 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800397
398 // The magic happens here. We segregate objects into different bins based
399 // on how likely they are to get dirty at runtime.
400 //
401 // Likely-to-dirty objects get packed together into the same bin so that
402 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
403 // maximized.
404 //
405 // This means more pages will stay either clean or shared dirty (with zygote) and
406 // the app will use less of its own (private) memory.
407 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000408 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800409
410 if (kBinObjects) {
411 //
412 // Changing the bin of an object is purely a memory-use tuning.
413 // It has no change on runtime correctness.
414 //
415 // Memory analysis has determined that the following types of objects get dirtied
416 // the most:
417 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000418 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
419 // a fixed layout which helps improve generated code (using PC-relative addressing),
420 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
421 // Since these arrays are huge, most pages do not overlap other objects and it's not
422 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100423 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800424 // * Class'es which are verified [their clinit runs only at runtime]
425 // - classes in general [because their static fields get overwritten]
426 // - initialized classes with all-final statics are unlikely to be ever dirty,
427 // so bin them separately
428 // * Art Methods that are:
429 // - native [their native entry point is not looked up until runtime]
430 // - have declaring classes that aren't initialized
431 // [their interpreter/quick entry points are trampolines until the class
432 // becomes initialized]
433 //
434 // We also assume the following objects get dirtied either never or extremely rarely:
435 // * Strings (they are immutable)
436 // * Art methods that aren't native and have initialized declared classes
437 //
438 // We assume that "regular" bin objects are highly unlikely to become dirtied,
439 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
440 //
441 if (object->IsClass()) {
442 bin = kBinClassVerified;
443 mirror::Class* klass = object->AsClass();
444
Mathieu Chartiere401d142015-04-22 13:56:20 -0700445 // Add non-embedded vtable to the pointer array table if there is one.
446 auto* vtable = klass->GetVTable();
447 if (vtable != nullptr) {
448 AddMethodPointerArray(vtable);
449 }
450 auto* iftable = klass->GetIfTable();
451 if (iftable != nullptr) {
452 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
453 if (iftable->GetMethodArrayCount(i) > 0) {
454 AddMethodPointerArray(iftable->GetMethodArray(i));
455 }
456 }
457 }
458
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800459 if (klass->GetStatus() == Class::kStatusInitialized) {
460 bin = kBinClassInitialized;
461
462 // If the class's static fields are all final, put it into a separate bin
463 // since it's very likely it will stay clean.
464 uint32_t num_static_fields = klass->NumStaticFields();
465 if (num_static_fields == 0) {
466 bin = kBinClassInitializedFinalStatics;
467 } else {
468 // Maybe all the statics are final?
469 bool all_final = true;
470 for (uint32_t i = 0; i < num_static_fields; ++i) {
471 ArtField* field = klass->GetStaticField(i);
472 if (!field->IsFinal()) {
473 all_final = false;
474 break;
475 }
476 }
477
478 if (all_final) {
479 bin = kBinClassInitializedFinalStatics;
480 }
481 }
482 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800483 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
484 bin = kBinString; // Strings are almost always immutable (except for object header).
485 } // else bin = kBinRegular
486 }
487
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800488 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Vladimir Marko05792b92015-08-03 11:56:49 +0100489 current_offset = bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
490 // Move the current bin size up to accomodate the object we just assigned a bin slot.
491 bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800492
493 BinSlot new_bin_slot(bin, current_offset);
494 SetImageBinSlot(object, new_bin_slot);
495
496 ++bin_slot_count_[bin];
497
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800498 // Grow the image closer to the end by the object we just assigned.
499 image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800500}
501
Mathieu Chartiere401d142015-04-22 13:56:20 -0700502bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
503 if (m->IsNative()) {
504 return true;
505 }
506 mirror::Class* declaring_class = m->GetDeclaringClass();
507 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
508 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
509}
510
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800511bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
512 DCHECK(object != nullptr);
513
514 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
515 // If it's in some other state, then we haven't yet assigned an image bin slot.
516 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
517 return false;
518 } else if (kIsDebugBuild) {
519 LockWord lock_word = object->GetLockWord(false);
520 size_t offset = lock_word.ForwardingAddress();
521 BinSlot bin_slot(offset);
522 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800523 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800524 }
525 return true;
526}
527
528ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
529 DCHECK(object != nullptr);
530 DCHECK(IsImageBinSlotAssigned(object));
531
532 LockWord lock_word = object->GetLockWord(false);
533 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
534 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
535
536 BinSlot bin_slot(static_cast<uint32_t>(offset));
537 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()]);
538
539 return bin_slot;
540}
541
Brian Carlstrom7940e442013-07-12 13:46:57 -0700542bool ImageWriter::AllocMemory() {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700543 const size_t length = RoundUp(image_objects_offset_begin_ + GetBinSizeSum() + intern_table_bytes_,
544 kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700545 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800546 image_.reset(MemMap::MapAnonymous("image writer image",
547 nullptr,
548 length,
549 PROT_READ | PROT_WRITE,
550 false,
551 false,
552 &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700553 if (UNLIKELY(image_.get() == nullptr)) {
554 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700555 return false;
556 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700557
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700558 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
559 CHECK_LE(image_end_, length);
560 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800561 "image bitmap",
562 image_->Begin(),
563 RoundUp(image_end_, kPageSize)));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700564 if (image_bitmap_.get() == nullptr) {
565 LOG(ERROR) << "Failed to allocate memory for image bitmap";
566 return false;
567 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700568 return true;
569}
570
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700571class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
572 public:
573 bool Visit(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
574 StackHandleScope<1> hs(Thread::Current());
575 mirror::Class::ComputeName(hs.NewHandle(c));
576 return true;
577 }
578};
579
Brian Carlstrom7940e442013-07-12 13:46:57 -0700580void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700581 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700582 ComputeLazyFieldsForClassesVisitor visitor;
583 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700584}
585
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800586static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
587 return klass->GetClassLoader() == nullptr;
588}
589
590bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
591 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
592}
593
594bool ImageWriter::ContainsBootClassLoaderNonImageClass(mirror::Class* klass) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700595 if (klass == nullptr) {
596 return false;
597 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800598 auto found = prune_class_memo_.find(klass);
599 if (found != prune_class_memo_.end()) {
600 // Already computed, return the found value.
601 return found->second;
602 }
603 // Place holder value to prevent infinite recursion.
604 prune_class_memo_.emplace(klass, false);
605 bool result = IsBootClassLoaderNonImageClass(klass);
606 if (!result) {
607 // Check interfaces since these wont be visited through VisitReferences.)
608 mirror::IfTable* if_table = klass->GetIfTable();
609 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
610 result = result || ContainsBootClassLoaderNonImageClass(if_table->GetInterface(i));
611 }
612 }
613 // Check static fields and their classes.
614 size_t num_static_fields = klass->NumReferenceStaticFields();
615 if (num_static_fields != 0 && klass->IsResolved()) {
616 // Presumably GC can happen when we are cross compiling, it should not cause performance
617 // problems to do pointer size logic.
618 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
619 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
620 for (size_t i = 0u; i < num_static_fields; ++i) {
621 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
622 if (ref != nullptr) {
623 if (ref->IsClass()) {
624 result = result || ContainsBootClassLoaderNonImageClass(ref->AsClass());
625 }
626 result = result || ContainsBootClassLoaderNonImageClass(ref->GetClass());
627 }
628 field_offset = MemberOffset(field_offset.Uint32Value() +
629 sizeof(mirror::HeapReference<mirror::Object>));
630 }
631 }
632 result = result || ContainsBootClassLoaderNonImageClass(klass->GetSuperClass());
633 prune_class_memo_[klass] = result;
634 return result;
635}
636
637bool ImageWriter::KeepClass(Class* klass) {
638 if (klass == nullptr) {
639 return false;
640 }
641 if (compile_app_image_) {
642 // For app images, we need to prune boot loader classes that are not in the boot image since
643 // these may have already been loaded when the app image is loaded.
644 return !ContainsBootClassLoaderNonImageClass(klass);
645 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700646 std::string temp;
647 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700648}
649
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700650class NonImageClassesVisitor : public ClassVisitor {
651 public:
652 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
653
654 bool Visit(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800655 if (!image_writer_->KeepClass(klass)) {
656 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700657 }
658 return true;
659 }
660
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800661 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700662 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700663};
664
665void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700666 Runtime* runtime = Runtime::Current();
667 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700668 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700669
670 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700671 NonImageClassesVisitor visitor(this);
672 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700673
674 // Remove the undesired classes from the class roots.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800675 for (mirror::Class* klass : visitor.classes_to_prune_) {
676 std::string temp;
677 const char* name = klass->GetDescriptor(&temp);
678 VLOG(compiler) << "Pruning class " << name;
679 if (!compile_app_image_) {
680 DCHECK(IsBootClassLoaderClass(klass));
681 }
682 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800683 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700684 }
685
686 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100687 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700688
689 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
690 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
691 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800692 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
693 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700694 if (dex_cache == nullptr) {
695 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700696 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700697 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
698 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800699 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700700 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700701 }
702 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100703 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
704 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
705 ArtMethod* method =
706 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700707 if (method != nullptr) {
708 auto* declaring_class = method->GetDeclaringClass();
709 // Miranda methods may be held live by a class which was not an image class but have a
710 // declaring class which is an image class. Set it to the resolution method to be safe and
711 // prevent dangling pointers.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800712 if (method->IsMiranda() || !KeepClass(declaring_class)) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100713 mirror::DexCache::SetElementPtrSize(resolved_methods,
714 i,
715 resolution_method,
716 target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700717 } else {
718 // Check that the class is still in the classes table.
719 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
720 << PrettyClass(declaring_class) << " not in class linker table";
721 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700722 }
723 }
724 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700725 ArtField* field = dex_cache->GetResolvedField(i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800726 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700727 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700728 }
729 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700730 // Clean the dex field. It might have been populated during the initialization phase, but
731 // contains data only valid during a real run.
732 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700733 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700734
735 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
736 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800737
738 // Clear to save RAM.
739 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700740}
741
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800742void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700743 if (compiler_driver_.GetImageClasses() != nullptr) {
744 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700745 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700746 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700747}
748
749void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
750 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800751 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700752 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800753 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700754 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700755 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800756 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
757 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700758 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700759 }
760}
761
762void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700763 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700764 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700765 for (const std::string& image_class : *image_classes) {
766 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700767 }
768}
769
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800770void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700771 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700772 // if it is a string, we want to intern it if its not interned.
773 if (obj->GetClass()->IsStringClass()) {
774 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800775 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700776 DCHECK_EQ(obj, obj->AsString()->Intern());
777 return;
778 }
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700779 // InternImageString allows us to intern while holding the heap bitmap lock. This is safe since
780 // we are guaranteed to not have GC during image writing.
Mathieu Chartier90ef3db2015-08-04 15:19:41 -0700781 mirror::String* const interned = Runtime::Current()->GetInternTable()->InternStrongImageString(
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700782 obj->AsString());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700783 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800784 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700785 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800786 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700787 }
788 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800789 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700790 return;
791 }
792 // else (obj == interned), nothing to do but fall through to the normal case
793 }
794
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800795 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700796}
797
798ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
799 Runtime* runtime = Runtime::Current();
800 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700801 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700802 StackHandleScope<3> hs(self);
803 Handle<Class> object_array_class(hs.NewHandle(
804 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700805
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700806 // build an Object[] of all the DexCaches used in the source_space_.
807 // Since we can't hold the dex lock when allocating the dex_caches
808 // ObjectArray, we lock the dex lock twice, first to get the number
809 // of dex caches first and then lock it again to copy the dex
810 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800811 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700812 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700813 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800814 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800815 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
816 mirror::DexCache* dex_cache =
817 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800818 dex_cache_count += IsInBootImage(dex_cache) ? 0u : 1u;
819 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700820 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700821 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800822 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700823 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
824 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700825 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800826 size_t non_image_dex_caches = 0;
827 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800828 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
829 mirror::DexCache* dex_cache =
830 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800831 non_image_dex_caches += IsInBootImage(dex_cache) ? 0u : 1u;
832 }
833 CHECK_EQ(dex_cache_count, non_image_dex_caches)
834 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700835 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800836 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
837 mirror::DexCache* dex_cache =
838 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800839 if (!IsInBootImage(dex_cache)) {
840 dex_caches->Set<false>(i, dex_cache);
841 ++i;
842 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700843 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700844 }
845
846 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -0700847 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700848 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700849 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100850 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700851 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700852 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700853 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700854 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700855}
856
Mathieu Chartier590fee92013-09-13 13:46:47 -0700857// Walk instance fields of the given Class. Separate function to allow recursion on the super
858// class.
859void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
860 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700861 StackHandleScope<1> hs(Thread::Current());
862 Handle<mirror::Class> h_class(hs.NewHandle(klass));
863 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700864 if (super != nullptr) {
865 WalkInstanceFields(obj, super);
866 }
867 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700868 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000869 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700870 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700871 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700872 if (value != nullptr) {
873 WalkFieldsInOrder(value);
874 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000875 field_offset = MemberOffset(field_offset.Uint32Value() +
876 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700877 }
878}
879
880// For an unvisited object, visit it then all its children found via fields.
881void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800882 if (IsInBootImage(obj)) {
883 // Object is in the image, don't need to fix it up.
884 return;
885 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800886 // Use our own visitor routine (instead of GC visitor) to get better locality between
887 // an object and its fields
888 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700889 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700890 StackHandleScope<2> hs(Thread::Current());
891 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
892 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700893 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800894 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700895 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700896 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700897 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700898 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700899 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700900 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700901 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700902 if (value != nullptr) {
903 WalkFieldsInOrder(value);
904 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000905 field_offset = MemberOffset(field_offset.Uint32Value() +
906 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700907 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700908 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700909 auto* as_klass = h_obj->AsClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700910 LengthPrefixedArray<ArtField>* fields[] = {
911 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
912 };
913 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
914 // Total array length including header.
915 if (cur_fields != nullptr) {
916 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
917 // Forward the entire array at once.
918 auto it = native_object_relocations_.find(cur_fields);
919 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
920 << " already forwarded";
921 size_t& offset = bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800922 DCHECK(!IsInBootImage(cur_fields));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700923 native_object_relocations_.emplace(
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800924 cur_fields,
925 NativeObjectRelocation {offset, kNativeObjectRelocationTypeArtFieldArray });
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700926 offset += header_size;
927 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +0100928 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700929 // Need to forward arrays separate of fields.
930 ArtField* field = &cur_fields->At(i);
931 auto it2 = native_object_relocations_.find(field);
932 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
933 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800934 DCHECK(!IsInBootImage(field));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700935 native_object_relocations_.emplace(
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800936 field,
937 NativeObjectRelocation {offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700938 offset += sizeof(ArtField);
939 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700940 }
941 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700942 // Visit and assign offsets for methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700943 LengthPrefixedArray<ArtMethod>* method_arrays[] = {
944 as_klass->GetDirectMethodsPtr(), as_klass->GetVirtualMethodsPtr(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700945 };
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700946 for (LengthPrefixedArray<ArtMethod>* array : method_arrays) {
947 if (array == nullptr) {
948 continue;
949 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700950 bool any_dirty = false;
951 size_t count = 0;
Vladimir Marko14632852015-08-17 12:07:23 +0100952 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
953 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +0100954 auto iteration_range =
955 MakeIterationRangeFromLengthPrefixedArray(array, method_size, method_alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700956 for (auto& m : iteration_range) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700957 any_dirty = any_dirty || WillMethodBeDirty(&m);
958 ++count;
959 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800960 NativeObjectRelocationType type = any_dirty
961 ? kNativeObjectRelocationTypeArtMethodDirty
962 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700963 Bin bin_type = BinTypeForNativeRelocationType(type);
964 // Forward the entire array at once, but header first.
Vladimir Markocf36d492015-08-12 19:27:26 +0100965 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
966 method_size,
967 method_alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700968 auto it = native_object_relocations_.find(array);
969 CHECK(it == native_object_relocations_.end()) << "Method array " << array
970 << " already forwarded";
971 size_t& offset = bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800972 DCHECK(!IsInBootImage(array));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700973 native_object_relocations_.emplace(array, NativeObjectRelocation { offset,
974 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty :
975 kNativeObjectRelocationTypeArtMethodArrayClean });
976 offset += header_size;
977 for (auto& m : iteration_range) {
978 AssignMethodOffset(&m, type);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700979 }
980 (any_dirty ? dirty_methods_ : clean_methods_) += count;
981 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700982 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700983 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700984 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700985 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700986 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700987 mirror::Object* value = obj_array->Get(i);
988 if (value != nullptr) {
989 WalkFieldsInOrder(value);
990 }
991 }
992 }
993 }
994}
995
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700996void ImageWriter::AssignMethodOffset(ArtMethod* method, NativeObjectRelocationType type) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800997 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700998 auto it = native_object_relocations_.find(method);
999 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001000 << PrettyMethod(method);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001001 size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
1002 native_object_relocations_.emplace(method, NativeObjectRelocation { offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001003 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001004}
1005
Mathieu Chartier590fee92013-09-13 13:46:47 -07001006void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1007 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1008 DCHECK(writer != nullptr);
1009 writer->WalkFieldsInOrder(obj);
1010}
1011
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001012void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1013 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1014 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001015 if (!writer->IsInBootImage(obj)) {
1016 writer->UnbinObjectsIntoOffset(obj);
1017 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001018}
1019
1020void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001021 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001022 CHECK(obj != nullptr);
1023
1024 // We know the bin slot, and the total bin sizes for all objects by now,
1025 // so calculate the object's final image offset.
1026
1027 DCHECK(IsImageBinSlotAssigned(obj));
1028 BinSlot bin_slot = GetImageBinSlot(obj);
1029 // Change the lockword from a bin slot into an offset
1030 AssignImageOffset(obj, bin_slot);
1031}
1032
Vladimir Markof4da6752014-08-01 19:04:18 +01001033void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001034 Thread* const self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001035 StackHandleScope<1> hs(self);
1036 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001037
Mathieu Chartiere401d142015-04-22 13:56:20 -07001038 auto* runtime = Runtime::Current();
1039 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001040 DCHECK_EQ(0U, image_end_);
1041
Mathieu Chartier31e89252013-08-28 11:29:12 -07001042 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001043 // know where image_roots is going to end up
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001044 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001045
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001046 image_objects_offset_begin_ = image_end_;
1047 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1048 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001049 // Write the image runtime methods.
1050 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1051 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1052 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1053 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1054 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1055 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1056 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1057 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001058
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001059 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001060 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1061 auto it = native_object_relocations_.find(&image_method_array_);
1062 CHECK(it == native_object_relocations_.end());
1063 size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001064 if (!compile_app_image_) {
1065 native_object_relocations_.emplace(&image_method_array_,
1066 NativeObjectRelocation { offset, image_method_type });
1067 }
Vladimir Marko14632852015-08-17 12:07:23 +01001068 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001069 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001070 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001071 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001072 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001073 for (auto* m : image_methods_) {
1074 CHECK(m != nullptr);
1075 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001076 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1077 if (!IsInBootImage(m)) {
1078 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean);
1079 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001080 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001081 // Calculate size of the dex cache arrays slot and prepare offsets.
1082 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001083
Vladimir Markocf36d492015-08-12 19:27:26 +01001084 // Calculate bin slot offsets.
1085 size_t bin_offset = image_objects_offset_begin_;
Vladimir Marko20f85592015-03-19 10:07:02 +00001086 for (size_t i = 0; i != kBinSize; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01001087 bin_slot_offsets_[i] = bin_offset;
1088 bin_offset += bin_slot_sizes_[i];
1089 if (i == kBinArtField) {
1090 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1091 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1092 DCHECK_ALIGNED(bin_offset, 4u);
1093 DCHECK(method_alignment == 4u || method_alignment == 8u);
1094 bin_offset = RoundUp(bin_offset, method_alignment);
1095 }
Vladimir Marko20f85592015-03-19 10:07:02 +00001096 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001097 // NOTE: There may be additional padding between the bin slots and the intern table.
1098
Mathieu Chartierc7853442015-03-27 14:35:38 -07001099 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
1100
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001101 // Transform each object's bin slot into an offset which will be used to do the final copy.
1102 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001103
Mathieu Chartierc7853442015-03-27 14:35:38 -07001104 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001105
Vladimir Markof4da6752014-08-01 19:04:18 +01001106 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
1107
Mathieu Chartiere401d142015-04-22 13:56:20 -07001108 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001109 for (auto& pair : native_object_relocations_) {
1110 NativeObjectRelocation& relocation = pair.second;
1111 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Markocf36d492015-08-12 19:27:26 +01001112 relocation.offset += bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001113 }
1114
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001115 // Calculate how big the intern table will be after being serialized.
1116 auto* const intern_table = Runtime::Current()->GetInternTable();
1117 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1118 intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1119
Mathieu Chartiere401d142015-04-22 13:56:20 -07001120 // Note that image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001121}
1122
1123void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
1124 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -07001125 const uint8_t* oat_file_begin = GetOatFileBegin();
1126 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001127 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -07001128 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001129
1130 // Create the image sections.
1131 ImageSection sections[ImageHeader::kSectionCount];
1132 // Objects section
1133 auto* objects_section = &sections[ImageHeader::kSectionObjects];
1134 *objects_section = ImageSection(0u, image_end_);
1135 size_t cur_pos = objects_section->End();
1136 // Add field section.
1137 auto* field_section = &sections[ImageHeader::kSectionArtFields];
1138 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
Vladimir Markocf36d492015-08-12 19:27:26 +01001139 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001140 cur_pos = field_section->End();
Vladimir Markocf36d492015-08-12 19:27:26 +01001141 // Round up to the alignment the required by the method section.
Vladimir Marko14632852015-08-17 12:07:23 +01001142 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001143 // Add method section.
1144 auto* methods_section = &sections[ImageHeader::kSectionArtMethods];
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001145 *methods_section = ImageSection(cur_pos,
1146 bin_slot_sizes_[kBinArtMethodClean] +
1147 bin_slot_sizes_[kBinArtMethodDirty]);
Vladimir Markocf36d492015-08-12 19:27:26 +01001148 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001149 cur_pos = methods_section->End();
Vladimir Marko05792b92015-08-03 11:56:49 +01001150 // Add dex cache arrays section.
1151 auto* dex_cache_arrays_section = &sections[ImageHeader::kSectionDexCacheArrays];
1152 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1153 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1154 cur_pos = dex_cache_arrays_section->End();
Nicolas Geoffray7bf2b4f2015-07-08 10:11:59 +00001155 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1156 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001157 // Calculate the size of the interned strings.
1158 auto* interned_strings_section = &sections[ImageHeader::kSectionInternedStrings];
1159 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1160 cur_pos = interned_strings_section->End();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001161 // Finally bitmap section.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001162 const size_t bitmap_bytes = image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001163 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
1164 *bitmap_section = ImageSection(RoundUp(cur_pos, kPageSize), RoundUp(bitmap_bytes, kPageSize));
1165 cur_pos = bitmap_section->End();
1166 if (kIsDebugBuild) {
1167 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001168 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001169 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1170 ++idx;
1171 }
1172 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
1173 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001174 const size_t image_end = static_cast<uint32_t>(interned_strings_section->End());
1175 CHECK_EQ(AlignUp(image_begin_ + image_end, kPageSize), oat_file_begin) <<
1176 "Oat file should be right after the image.";
Mathieu Chartiere401d142015-04-22 13:56:20 -07001177 // Create the header.
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001178 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
1179 image_end,
1180 sections,
1181 image_roots_address_,
1182 oat_file_->GetOatHeader().GetChecksum(),
1183 PointerToLowMemUInt32(oat_file_begin),
1184 PointerToLowMemUInt32(oat_data_begin_),
1185 PointerToLowMemUInt32(oat_data_end),
1186 PointerToLowMemUInt32(oat_file_end),
1187 target_ptr_size_,
1188 compile_pic_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001189}
1190
1191ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001192 auto it = native_object_relocations_.find(method);
1193 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001194 CHECK_GE(it->second.offset, image_end_) << "ArtMethods should be after Objects";
1195 return reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001196}
1197
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001198class FixupRootVisitor : public RootVisitor {
1199 public:
1200 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1201 }
1202
1203 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001204 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001205 for (size_t i = 0; i < count; ++i) {
1206 *roots[i] = ImageAddress(*roots[i]);
1207 }
1208 }
1209
1210 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1211 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001212 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001213 for (size_t i = 0; i < count; ++i) {
1214 roots[i]->Assign(ImageAddress(roots[i]->AsMirrorPtr()));
1215 }
1216 }
1217
1218 private:
1219 ImageWriter* const image_writer_;
1220
Mathieu Chartier90443472015-07-16 20:32:27 -07001221 mirror::Object* ImageAddress(mirror::Object* obj) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001222 const size_t offset = image_writer_->GetImageOffset(obj);
1223 auto* const dest = reinterpret_cast<Object*>(image_writer_->image_begin_ + offset);
1224 VLOG(compiler) << "Update root from " << obj << " to " << dest;
1225 return dest;
1226 }
1227};
1228
Mathieu Chartierc7853442015-03-27 14:35:38 -07001229void ImageWriter::CopyAndFixupNativeData() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001230 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001231 for (auto& pair : native_object_relocations_) {
1232 NativeObjectRelocation& relocation = pair.second;
1233 auto* dest = image_->Begin() + relocation.offset;
1234 DCHECK_GE(dest, image_->Begin() + image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001235 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001236 switch (relocation.type) {
1237 case kNativeObjectRelocationTypeArtField: {
1238 memcpy(dest, pair.first, sizeof(ArtField));
1239 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1240 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1241 break;
1242 }
1243 case kNativeObjectRelocationTypeArtMethodClean:
1244 case kNativeObjectRelocationTypeArtMethodDirty: {
1245 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
1246 reinterpret_cast<ArtMethod*>(dest));
1247 break;
1248 }
1249 // For arrays, copy just the header since the elements will get copied by their corresponding
1250 // relocations.
1251 case kNativeObjectRelocationTypeArtFieldArray: {
1252 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1253 break;
1254 }
1255 case kNativeObjectRelocationTypeArtMethodArrayClean:
1256 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001257 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1258 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001259 ArtMethod::Size(target_ptr_size_),
1260 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001261 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001262 case kNativeObjectRelocationTypeDexCacheArray:
1263 // Nothing to copy here, everything is done in FixupDexCache().
1264 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001265 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001266 }
1267 }
1268 // Fixup the image method roots.
1269 auto* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001270 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001271 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001272 ArtMethod* method = image_methods_[i];
1273 CHECK(method != nullptr);
1274 if (!IsInBootImage(method)) {
1275 auto it = native_object_relocations_.find(method);
1276 CHECK(it != native_object_relocations_.end()) << "No fowarding for " << PrettyMethod(method);
1277 NativeObjectRelocation& relocation = it->second;
1278 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1279 << methods_section;
1280 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
1281 method = reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
1282 }
1283 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001284 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001285 // Write the intern table into the image.
1286 const ImageSection& intern_table_section = image_header->GetImageSection(
1287 ImageHeader::kSectionInternedStrings);
1288 InternTable* const intern_table = Runtime::Current()->GetInternTable();
1289 uint8_t* const memory_ptr = image_->Begin() + intern_table_section.Offset();
1290 const size_t intern_table_bytes = intern_table->WriteToMemory(memory_ptr);
1291 // Fixup the pointers in the newly written intern table to contain image addresses.
1292 InternTable temp_table;
1293 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1294 // the VisitRoots() will update the memory directly rather than the copies.
1295 // This also relies on visit roots not doing any verification which could fail after we update
1296 // the roots to be the image addresses.
1297 temp_table.ReadFromMemory(memory_ptr);
1298 CHECK_EQ(temp_table.Size(), intern_table->Size());
1299 FixupRootVisitor visitor(this);
1300 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
1301 CHECK_EQ(intern_table_bytes, intern_table_bytes_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001302}
1303
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001304void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001305 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001306 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1307 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001308 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001309 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001310 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1311 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001312 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001313 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001314}
1315
Mathieu Chartier590fee92013-09-13 13:46:47 -07001316void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001317 DCHECK(obj != nullptr);
1318 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001319 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1320}
1321
Mathieu Chartiere401d142015-04-22 13:56:20 -07001322void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1323 mirror::Class* klass, Bin array_type) {
1324 CHECK(klass->IsArrayClass());
1325 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1326 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001327 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001328 dst->SetClass(GetImageAddress(arr->GetClass()));
1329 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001330 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001331 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1332 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001333 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001334 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001335 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001336 auto* method = reinterpret_cast<ArtMethod*>(elem);
1337 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1338 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1339 << PrettyClass(method->GetDeclaringClass());
1340 } else {
1341 CHECK_EQ(array_type, kBinArtField);
1342 auto* field = reinterpret_cast<ArtField*>(elem);
1343 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1344 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1345 << PrettyClass(field->GetDeclaringClass());
1346 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001347 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001348 } else {
1349 elem = image_begin_ + it->second.offset;
1350 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001351 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001352 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001353 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001354}
1355
1356void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001357 if (IsInBootImage(obj)) {
1358 return;
1359 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001360 size_t offset = GetImageOffset(obj);
1361 auto* dst = reinterpret_cast<Object*>(image_->Begin() + offset);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001362 DCHECK_LT(offset, image_end_);
1363 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001364
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001365 image_bitmap_->Set(dst); // Mark the obj as live.
1366
1367 const size_t n = obj->SizeOf();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001368 DCHECK_LE(offset + n, image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001369 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001370
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001371 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1372 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001373 const auto it = saved_hashcode_map_.find(obj);
1374 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1375 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001376 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001377}
1378
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001379// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001380class FixupVisitor {
1381 public:
1382 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1383 }
1384
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001385 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1386 // with other logic.
1387 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1388 const {}
1389 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1390
1391
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001392 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001393 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001394 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001395 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1396 // image.
1397 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001398 offset,
1399 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001400 }
1401
1402 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001403 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001404 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001405 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001406 mirror::Reference::ReferentOffset(),
1407 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001408 }
1409
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001410 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001411 ImageWriter* const image_writer_;
1412 mirror::Object* const copy_;
1413};
1414
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001415class FixupClassVisitor FINAL : public FixupVisitor {
1416 public:
1417 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1418 }
1419
Mathieu Chartierc7853442015-03-27 14:35:38 -07001420 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001421 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001422 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001423 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001424 }
1425
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001426 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1427 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001428 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001429 LOG(FATAL) << "Reference not expected here.";
1430 }
1431};
1432
Vladimir Marko05792b92015-08-03 11:56:49 +01001433uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1434 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001435 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001436 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001437 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1438 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001439 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001440 return relocation.offset;
1441}
1442
1443template <typename T>
1444T* ImageWriter::NativeLocationInImage(T* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001445 return (obj == nullptr || IsInBootImage(obj))
1446 ? obj
1447 : reinterpret_cast<T*>(image_begin_ + NativeOffsetInImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001448}
1449
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001450template <typename T>
1451T* ImageWriter::NativeCopyLocation(T* obj) {
1452 return (obj == nullptr || IsInBootImage(obj))
1453 ? obj
1454 : reinterpret_cast<T*>(image_->Begin() + NativeOffsetInImage(obj));
1455}
1456
1457class NativeLocationVisitor {
1458 public:
1459 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1460
1461 template <typename T>
1462 T* operator()(T* ptr) const {
1463 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001464 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001465
1466 private:
1467 ImageWriter* const image_writer_;
1468};
1469
1470void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
1471 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001472 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001473 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001474}
1475
Ian Rogersef7d42f2014-01-06 12:55:46 -08001476void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001477 DCHECK(orig != nullptr);
1478 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001479 if (kUseBakerOrBrooksReadBarrier) {
1480 orig->AssertReadBarrierPointer();
1481 if (kUseBrooksReadBarrier) {
1482 // Note the address 'copy' isn't the same as the image address of 'orig'.
1483 copy->SetReadBarrierPointer(GetImageAddress(orig));
1484 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1485 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001486 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001487 auto* klass = orig->GetClass();
1488 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001489 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001490 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1491 if (it != pointer_arrays_.end()) {
1492 // Should only need to fixup every pointer array exactly once.
1493 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1494 pointer_arrays_.erase(it);
1495 return;
1496 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001497 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001498 if (orig->IsClass()) {
1499 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001500 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001501 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1502 // Need to go update the ArtMethod.
1503 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1504 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1505 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001506 auto it = native_object_relocations_.find(src_method);
1507 CHECK(it != native_object_relocations_.end())
1508 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001509 dest->SetArtMethod(
1510 reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001511 } else if (!klass->IsArrayClass()) {
1512 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1513 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1514 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
1515 } else if (klass->IsSubClass(down_cast<mirror::Class*>(
1516 class_linker->GetClassRoot(ClassLinker::kJavaLangClassLoader)))) {
1517 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1518 // ClassLoader.
1519 down_cast<mirror::ClassLoader*>(copy)->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001520 // Also set allocator to null to be safe. The allocator is created when we create the class
1521 // table. We also never expect to unload things in the image since they are held live as
1522 // roots.
1523 down_cast<mirror::ClassLoader*>(copy)->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001524 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001525 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001526 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001527 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001528 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001529}
1530
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001531
1532class ImageAddressVisitor {
1533 public:
1534 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1535
1536 template <typename T>
1537 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1538 return image_writer_->GetImageAddress(ptr);
1539 }
1540
1541 private:
1542 ImageWriter* const image_writer_;
1543};
1544
1545
Vladimir Marko05792b92015-08-03 11:56:49 +01001546void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1547 mirror::DexCache* copy_dex_cache) {
1548 // Though the DexCache array fields are usually treated as native pointers, we set the full
1549 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1550 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1551 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1552 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1553 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001554 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
1555 NativeLocationInImage(orig_strings),
1556 /*pointer size*/8u);
1557 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings), ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001558 }
1559 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1560 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001561 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
1562 NativeLocationInImage(orig_types),
1563 /*pointer size*/8u);
1564 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types), ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001565 }
1566 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1567 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001568 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
1569 NativeLocationInImage(orig_methods),
1570 /*pointer size*/8u);
1571 ArtMethod** copy_methods = NativeCopyLocation(orig_methods);
Vladimir Marko05792b92015-08-03 11:56:49 +01001572 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1573 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001574 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001575 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1576 }
1577 }
1578 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1579 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001580 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
1581 NativeLocationInImage(orig_fields),
1582 /*pointer size*/8u);
1583 ArtField** copy_fields = NativeCopyLocation(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +01001584 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1585 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001586 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001587 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1588 }
1589 }
1590}
1591
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001592const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1593 DCHECK_LT(type, kOatAddressCount);
1594 // If we are compiling an app image, we need to use the stubs of the boot image.
1595 if (compile_app_image_) {
1596 // Use the current image pointers.
Mathieu Chartier073b16c2015-11-10 14:13:23 -08001597 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetBootImageSpace();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001598 DCHECK(image_space != nullptr);
1599 const OatFile* oat_file = image_space->GetOatFile();
1600 CHECK(oat_file != nullptr);
1601 const OatHeader& header = oat_file->GetOatHeader();
1602 switch (type) {
1603 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1604 case kOatAddressQuickGenericJNITrampoline:
1605 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1606 case kOatAddressInterpreterToInterpreterBridge:
1607 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1608 case kOatAddressInterpreterToCompiledCodeBridge:
1609 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1610 case kOatAddressJNIDlsymLookup:
1611 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1612 case kOatAddressQuickIMTConflictTrampoline:
1613 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1614 case kOatAddressQuickResolutionTrampoline:
1615 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1616 case kOatAddressQuickToInterpreterBridge:
1617 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1618 default:
1619 UNREACHABLE();
1620 }
1621 }
1622 return GetOatAddressForOffset(oat_address_offsets_[type]);
1623}
1624
Mathieu Chartiere401d142015-04-22 13:56:20 -07001625const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method, bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001626 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
1627 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
1628 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07001629 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001630 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001631
1632 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1633 // trampoline.
1634
1635 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001636 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1637 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001638 const uint8_t* quick_code = GetOatAddressForOffset(quick_oat_code_offset);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001639 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001640 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
1641 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001642 // We have code for a non-static or initialized method, just use the code.
1643 } else if (quick_code == nullptr && method->IsNative() &&
1644 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1645 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001646 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001647 } else if (quick_code == nullptr && !method->IsNative()) {
1648 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001649 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001650 *quick_is_interpreted = true;
1651 } else {
1652 CHECK(!method->GetDeclaringClass()->IsInitialized());
1653 // We have code for a static method, but need to go through the resolution stub for class
1654 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001655 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
1656 }
1657 if (!IsInBootOatFile(quick_code)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001658 DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001659 }
1660 return quick_code;
1661}
1662
Mathieu Chartiere401d142015-04-22 13:56:20 -07001663const uint8_t* ImageWriter::GetQuickEntryPoint(ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001664 // Calculate the quick entry point following the same logic as FixupMethod() below.
1665 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001666 Runtime* runtime = Runtime::Current();
1667 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001668 return GetOatAddress(kOatAddressQuickResolutionTrampoline);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001669 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
1670 method == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001671 return GetOatAddress(kOatAddressQuickIMTConflictTrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001672 } else {
1673 // We assume all methods have code. If they don't currently then we set them to the use the
1674 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1675 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07001676 if (UNLIKELY(!method->IsInvokable())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001677 return GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001678 } else {
1679 bool quick_is_interpreted;
1680 return GetQuickCode(method, &quick_is_interpreted);
1681 }
1682 }
1683}
1684
Mathieu Chartiere401d142015-04-22 13:56:20 -07001685void ImageWriter::CopyAndFixupMethod(ArtMethod* orig, ArtMethod* copy) {
Vladimir Marko14632852015-08-17 12:07:23 +01001686 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001687
1688 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01001689
1690 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
1691 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
1692 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
1693 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001694
Ian Rogers848871b2013-08-05 10:56:33 -07001695 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1696 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07001697
Ian Rogers848871b2013-08-05 10:56:33 -07001698 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001699 Runtime* runtime = Runtime::Current();
1700 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001701 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001702 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001703 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1704 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001705 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001706 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001707 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
1708 bool found_one = false;
1709 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
1710 auto idx = static_cast<Runtime::CalleeSaveType>(i);
1711 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
1712 found_one = true;
1713 break;
1714 }
1715 }
1716 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
1717 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001718 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001719 // We assume all methods have code. If they don't currently then we set them to the use the
1720 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1721 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07001722 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001723 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001724 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001725 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001726 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -07001727 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001728 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001729
Sebastien Hertze1d07812014-05-21 15:44:09 +02001730 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001731 if (orig->IsNative()) {
1732 // The native method's pointer is set to a stub to lookup via dlsym.
1733 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001734 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001735 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001736 }
1737 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001738 }
1739}
1740
Alex Lighta59dd802014-07-02 16:28:08 -07001741static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001742 uint64_t data_sec_offset;
1743 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1744 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001745 return nullptr;
1746 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001747 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001748}
1749
Vladimir Markof4da6752014-08-01 19:04:18 +01001750void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001751 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001752 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file,
1753 PROT_READ | PROT_WRITE,
1754 MAP_SHARED,
1755 &error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001756 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001757 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001758 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001759 }
Alex Lighta59dd802014-07-02 16:28:08 -07001760 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1761 CHECK(oat_header != nullptr);
1762 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001763
Brian Carlstrom7940e442013-07-12 13:46:57 -07001764 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001765 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001766}
1767
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001768size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1769 DCHECK_LE(up_to, kBinSize);
1770 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1771}
1772
1773ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1774 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07001775 static_assert(kBinBits == 3, "wrong number of bin bits");
1776 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001777 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1778
1779 DCHECK_LT(GetBin(), kBinSize);
1780 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1781}
1782
1783ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1784 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1785 DCHECK_EQ(index, GetIndex());
1786}
1787
1788ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1789 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1790}
1791
1792uint32_t ImageWriter::BinSlot::GetIndex() const {
1793 return lockword_ & ~kBinMask;
1794}
1795
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001796uint8_t* ImageWriter::GetOatFileBegin() const {
1797 DCHECK_GT(intern_table_bytes_, 0u);
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001798 size_t native_sections_size = bin_slot_sizes_[kBinArtField] +
1799 bin_slot_sizes_[kBinArtMethodDirty] +
1800 bin_slot_sizes_[kBinArtMethodClean] +
1801 bin_slot_sizes_[kBinDexCacheArray] +
1802 intern_table_bytes_;
Vladimir Marko05792b92015-08-03 11:56:49 +01001803 return image_begin_ + RoundUp(image_end_ + native_sections_size, kPageSize);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001804}
1805
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001806ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
1807 switch (type) {
1808 case kNativeObjectRelocationTypeArtField:
1809 case kNativeObjectRelocationTypeArtFieldArray:
1810 return kBinArtField;
1811 case kNativeObjectRelocationTypeArtMethodClean:
1812 case kNativeObjectRelocationTypeArtMethodArrayClean:
1813 return kBinArtMethodClean;
1814 case kNativeObjectRelocationTypeArtMethodDirty:
1815 case kNativeObjectRelocationTypeArtMethodArrayDirty:
1816 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01001817 case kNativeObjectRelocationTypeDexCacheArray:
1818 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001819 }
1820 UNREACHABLE();
1821}
1822
Brian Carlstrom7940e442013-07-12 13:46:57 -07001823} // namespace art