blob: 3d9e7e7cda5b6d3d8d43832015e35dda13c2a3af [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() {
333 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700334 Thread* const self = Thread::Current();
335 ReaderMutexLock mu(self, *class_linker->DexLock());
Vladimir Marko20f85592015-03-19 10:07:02 +0000336 uint32_t size = 0u;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800337 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700338 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800339 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800340 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700341 continue;
342 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000343 const DexFile* dex_file = dex_cache->GetDexFile();
344 dex_cache_array_starts_.Put(dex_file, size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700345 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000346 DCHECK(layout.Valid());
Vladimir Marko05792b92015-08-03 11:56:49 +0100347 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
348 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(), size + layout.TypesOffset());
349 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
350 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(), size + layout.MethodsOffset());
351 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
352 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(), size + layout.FieldsOffset());
353 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
354 AddDexCacheArrayRelocation(dex_cache->GetStrings(), size + layout.StringsOffset());
Vladimir Marko20f85592015-03-19 10:07:02 +0000355 size += layout.Size();
356 }
357 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
358 // when AssignImageBinSlot() assigns their indexes out or order.
359 bin_slot_sizes_[kBinDexCacheArray] = size;
360}
361
Vladimir Marko05792b92015-08-03 11:56:49 +0100362void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset) {
363 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800364 DCHECK(!IsInBootImage(array));
Vladimir Marko05792b92015-08-03 11:56:49 +0100365 native_object_relocations_.emplace(
366 array,
367 NativeObjectRelocation { offset, kNativeObjectRelocationTypeDexCacheArray });
368 }
369}
370
Mathieu Chartiere401d142015-04-22 13:56:20 -0700371void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
372 DCHECK(arr != nullptr);
373 if (kIsDebugBuild) {
374 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800375 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700376 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800377 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800378 CHECK(klass == nullptr || KeepClass(klass))
379 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700380 }
381 }
382 }
383 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
384 // ArtMethods.
385 pointer_arrays_.emplace(arr, kBinArtMethodClean);
386}
387
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800388void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
389 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800390 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800391
392 // The magic happens here. We segregate objects into different bins based
393 // on how likely they are to get dirty at runtime.
394 //
395 // Likely-to-dirty objects get packed together into the same bin so that
396 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
397 // maximized.
398 //
399 // This means more pages will stay either clean or shared dirty (with zygote) and
400 // the app will use less of its own (private) memory.
401 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000402 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800403
404 if (kBinObjects) {
405 //
406 // Changing the bin of an object is purely a memory-use tuning.
407 // It has no change on runtime correctness.
408 //
409 // Memory analysis has determined that the following types of objects get dirtied
410 // the most:
411 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000412 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
413 // a fixed layout which helps improve generated code (using PC-relative addressing),
414 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
415 // Since these arrays are huge, most pages do not overlap other objects and it's not
416 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100417 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800418 // * Class'es which are verified [their clinit runs only at runtime]
419 // - classes in general [because their static fields get overwritten]
420 // - initialized classes with all-final statics are unlikely to be ever dirty,
421 // so bin them separately
422 // * Art Methods that are:
423 // - native [their native entry point is not looked up until runtime]
424 // - have declaring classes that aren't initialized
425 // [their interpreter/quick entry points are trampolines until the class
426 // becomes initialized]
427 //
428 // We also assume the following objects get dirtied either never or extremely rarely:
429 // * Strings (they are immutable)
430 // * Art methods that aren't native and have initialized declared classes
431 //
432 // We assume that "regular" bin objects are highly unlikely to become dirtied,
433 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
434 //
435 if (object->IsClass()) {
436 bin = kBinClassVerified;
437 mirror::Class* klass = object->AsClass();
438
Mathieu Chartiere401d142015-04-22 13:56:20 -0700439 // Add non-embedded vtable to the pointer array table if there is one.
440 auto* vtable = klass->GetVTable();
441 if (vtable != nullptr) {
442 AddMethodPointerArray(vtable);
443 }
444 auto* iftable = klass->GetIfTable();
445 if (iftable != nullptr) {
446 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
447 if (iftable->GetMethodArrayCount(i) > 0) {
448 AddMethodPointerArray(iftable->GetMethodArray(i));
449 }
450 }
451 }
452
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800453 if (klass->GetStatus() == Class::kStatusInitialized) {
454 bin = kBinClassInitialized;
455
456 // If the class's static fields are all final, put it into a separate bin
457 // since it's very likely it will stay clean.
458 uint32_t num_static_fields = klass->NumStaticFields();
459 if (num_static_fields == 0) {
460 bin = kBinClassInitializedFinalStatics;
461 } else {
462 // Maybe all the statics are final?
463 bool all_final = true;
464 for (uint32_t i = 0; i < num_static_fields; ++i) {
465 ArtField* field = klass->GetStaticField(i);
466 if (!field->IsFinal()) {
467 all_final = false;
468 break;
469 }
470 }
471
472 if (all_final) {
473 bin = kBinClassInitializedFinalStatics;
474 }
475 }
476 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800477 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
478 bin = kBinString; // Strings are almost always immutable (except for object header).
479 } // else bin = kBinRegular
480 }
481
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800482 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Vladimir Marko05792b92015-08-03 11:56:49 +0100483 current_offset = bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
484 // Move the current bin size up to accomodate the object we just assigned a bin slot.
485 bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800486
487 BinSlot new_bin_slot(bin, current_offset);
488 SetImageBinSlot(object, new_bin_slot);
489
490 ++bin_slot_count_[bin];
491
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800492 // Grow the image closer to the end by the object we just assigned.
493 image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800494}
495
Mathieu Chartiere401d142015-04-22 13:56:20 -0700496bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
497 if (m->IsNative()) {
498 return true;
499 }
500 mirror::Class* declaring_class = m->GetDeclaringClass();
501 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
502 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
503}
504
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800505bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
506 DCHECK(object != nullptr);
507
508 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
509 // If it's in some other state, then we haven't yet assigned an image bin slot.
510 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
511 return false;
512 } else if (kIsDebugBuild) {
513 LockWord lock_word = object->GetLockWord(false);
514 size_t offset = lock_word.ForwardingAddress();
515 BinSlot bin_slot(offset);
516 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800517 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800518 }
519 return true;
520}
521
522ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
523 DCHECK(object != nullptr);
524 DCHECK(IsImageBinSlotAssigned(object));
525
526 LockWord lock_word = object->GetLockWord(false);
527 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
528 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
529
530 BinSlot bin_slot(static_cast<uint32_t>(offset));
531 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()]);
532
533 return bin_slot;
534}
535
Brian Carlstrom7940e442013-07-12 13:46:57 -0700536bool ImageWriter::AllocMemory() {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700537 const size_t length = RoundUp(image_objects_offset_begin_ + GetBinSizeSum() + intern_table_bytes_,
538 kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700539 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800540 image_.reset(MemMap::MapAnonymous("image writer image",
541 nullptr,
542 length,
543 PROT_READ | PROT_WRITE,
544 false,
545 false,
546 &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700547 if (UNLIKELY(image_.get() == nullptr)) {
548 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700549 return false;
550 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700551
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700552 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
553 CHECK_LE(image_end_, length);
554 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800555 "image bitmap",
556 image_->Begin(),
557 RoundUp(image_end_, kPageSize)));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700558 if (image_bitmap_.get() == nullptr) {
559 LOG(ERROR) << "Failed to allocate memory for image bitmap";
560 return false;
561 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700562 return true;
563}
564
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700565class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
566 public:
567 bool Visit(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
568 StackHandleScope<1> hs(Thread::Current());
569 mirror::Class::ComputeName(hs.NewHandle(c));
570 return true;
571 }
572};
573
Brian Carlstrom7940e442013-07-12 13:46:57 -0700574void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700575 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700576 ComputeLazyFieldsForClassesVisitor visitor;
577 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700578}
579
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800580static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
581 return klass->GetClassLoader() == nullptr;
582}
583
584bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
585 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
586}
587
588bool ImageWriter::ContainsBootClassLoaderNonImageClass(mirror::Class* klass) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700589 if (klass == nullptr) {
590 return false;
591 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800592 auto found = prune_class_memo_.find(klass);
593 if (found != prune_class_memo_.end()) {
594 // Already computed, return the found value.
595 return found->second;
596 }
597 // Place holder value to prevent infinite recursion.
598 prune_class_memo_.emplace(klass, false);
599 bool result = IsBootClassLoaderNonImageClass(klass);
600 if (!result) {
601 // Check interfaces since these wont be visited through VisitReferences.)
602 mirror::IfTable* if_table = klass->GetIfTable();
603 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
604 result = result || ContainsBootClassLoaderNonImageClass(if_table->GetInterface(i));
605 }
606 }
607 // Check static fields and their classes.
608 size_t num_static_fields = klass->NumReferenceStaticFields();
609 if (num_static_fields != 0 && klass->IsResolved()) {
610 // Presumably GC can happen when we are cross compiling, it should not cause performance
611 // problems to do pointer size logic.
612 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
613 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
614 for (size_t i = 0u; i < num_static_fields; ++i) {
615 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
616 if (ref != nullptr) {
617 if (ref->IsClass()) {
618 result = result || ContainsBootClassLoaderNonImageClass(ref->AsClass());
619 }
620 result = result || ContainsBootClassLoaderNonImageClass(ref->GetClass());
621 }
622 field_offset = MemberOffset(field_offset.Uint32Value() +
623 sizeof(mirror::HeapReference<mirror::Object>));
624 }
625 }
626 result = result || ContainsBootClassLoaderNonImageClass(klass->GetSuperClass());
627 prune_class_memo_[klass] = result;
628 return result;
629}
630
631bool ImageWriter::KeepClass(Class* klass) {
632 if (klass == nullptr) {
633 return false;
634 }
635 if (compile_app_image_) {
636 // For app images, we need to prune boot loader classes that are not in the boot image since
637 // these may have already been loaded when the app image is loaded.
638 return !ContainsBootClassLoaderNonImageClass(klass);
639 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700640 std::string temp;
641 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700642}
643
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700644class NonImageClassesVisitor : public ClassVisitor {
645 public:
646 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
647
648 bool Visit(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800649 if (!image_writer_->KeepClass(klass)) {
650 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700651 }
652 return true;
653 }
654
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800655 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700656 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700657};
658
659void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700660 Runtime* runtime = Runtime::Current();
661 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700662 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700663
664 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700665 NonImageClassesVisitor visitor(this);
666 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700667
668 // Remove the undesired classes from the class roots.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800669 for (mirror::Class* klass : visitor.classes_to_prune_) {
670 std::string temp;
671 const char* name = klass->GetDescriptor(&temp);
672 VLOG(compiler) << "Pruning class " << name;
673 if (!compile_app_image_) {
674 DCHECK(IsBootClassLoaderClass(klass));
675 }
676 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800677 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700678 }
679
680 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100681 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700682
683 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
684 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
685 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800686 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
687 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700688 if (dex_cache == nullptr) {
689 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700690 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700691 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
692 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800693 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700694 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700695 }
696 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100697 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
698 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
699 ArtMethod* method =
700 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700701 if (method != nullptr) {
702 auto* declaring_class = method->GetDeclaringClass();
703 // Miranda methods may be held live by a class which was not an image class but have a
704 // declaring class which is an image class. Set it to the resolution method to be safe and
705 // prevent dangling pointers.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800706 if (method->IsMiranda() || !KeepClass(declaring_class)) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100707 mirror::DexCache::SetElementPtrSize(resolved_methods,
708 i,
709 resolution_method,
710 target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700711 } else {
712 // Check that the class is still in the classes table.
713 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
714 << PrettyClass(declaring_class) << " not in class linker table";
715 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700716 }
717 }
718 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700719 ArtField* field = dex_cache->GetResolvedField(i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800720 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700721 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700722 }
723 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700724 // Clean the dex field. It might have been populated during the initialization phase, but
725 // contains data only valid during a real run.
726 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700727 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700728
729 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
730 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800731
732 // Clear to save RAM.
733 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700734}
735
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800736void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700737 if (compiler_driver_.GetImageClasses() != nullptr) {
738 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700739 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700740 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700741}
742
743void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
744 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800745 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700746 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800747 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700748 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700749 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800750 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
751 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700752 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700753 }
754}
755
756void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700757 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700758 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700759 for (const std::string& image_class : *image_classes) {
760 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700761 }
762}
763
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800764void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700765 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700766 // if it is a string, we want to intern it if its not interned.
767 if (obj->GetClass()->IsStringClass()) {
768 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800769 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700770 DCHECK_EQ(obj, obj->AsString()->Intern());
771 return;
772 }
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700773 // InternImageString allows us to intern while holding the heap bitmap lock. This is safe since
774 // we are guaranteed to not have GC during image writing.
Mathieu Chartier90ef3db2015-08-04 15:19:41 -0700775 mirror::String* const interned = Runtime::Current()->GetInternTable()->InternStrongImageString(
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700776 obj->AsString());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700777 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800778 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700779 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800780 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700781 }
782 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800783 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700784 return;
785 }
786 // else (obj == interned), nothing to do but fall through to the normal case
787 }
788
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800789 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700790}
791
792ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
793 Runtime* runtime = Runtime::Current();
794 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700795 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700796 StackHandleScope<3> hs(self);
797 Handle<Class> object_array_class(hs.NewHandle(
798 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700799
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700800 // build an Object[] of all the DexCaches used in the source_space_.
801 // Since we can't hold the dex lock when allocating the dex_caches
802 // ObjectArray, we lock the dex lock twice, first to get the number
803 // of dex caches first and then lock it again to copy the dex
804 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800805 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700806 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700807 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800808 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800809 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
810 mirror::DexCache* dex_cache =
811 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800812 dex_cache_count += IsInBootImage(dex_cache) ? 0u : 1u;
813 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700814 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700815 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800816 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700817 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
818 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700819 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800820 size_t non_image_dex_caches = 0;
821 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800822 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
823 mirror::DexCache* dex_cache =
824 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800825 non_image_dex_caches += IsInBootImage(dex_cache) ? 0u : 1u;
826 }
827 CHECK_EQ(dex_cache_count, non_image_dex_caches)
828 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700829 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800830 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
831 mirror::DexCache* dex_cache =
832 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800833 if (!IsInBootImage(dex_cache)) {
834 dex_caches->Set<false>(i, dex_cache);
835 ++i;
836 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700837 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700838 }
839
840 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -0700841 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700842 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700843 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100844 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700845 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700846 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700847 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700848 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700849}
850
Mathieu Chartier590fee92013-09-13 13:46:47 -0700851// Walk instance fields of the given Class. Separate function to allow recursion on the super
852// class.
853void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
854 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700855 StackHandleScope<1> hs(Thread::Current());
856 Handle<mirror::Class> h_class(hs.NewHandle(klass));
857 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700858 if (super != nullptr) {
859 WalkInstanceFields(obj, super);
860 }
861 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700862 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000863 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700864 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700865 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700866 if (value != nullptr) {
867 WalkFieldsInOrder(value);
868 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000869 field_offset = MemberOffset(field_offset.Uint32Value() +
870 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700871 }
872}
873
874// For an unvisited object, visit it then all its children found via fields.
875void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800876 if (IsInBootImage(obj)) {
877 // Object is in the image, don't need to fix it up.
878 return;
879 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800880 // Use our own visitor routine (instead of GC visitor) to get better locality between
881 // an object and its fields
882 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700883 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700884 StackHandleScope<2> hs(Thread::Current());
885 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
886 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700887 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800888 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700889 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700890 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700891 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700892 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700893 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700894 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700895 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700896 if (value != nullptr) {
897 WalkFieldsInOrder(value);
898 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000899 field_offset = MemberOffset(field_offset.Uint32Value() +
900 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700901 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700902 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700903 auto* as_klass = h_obj->AsClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700904 LengthPrefixedArray<ArtField>* fields[] = {
905 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
906 };
907 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
908 // Total array length including header.
909 if (cur_fields != nullptr) {
910 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
911 // Forward the entire array at once.
912 auto it = native_object_relocations_.find(cur_fields);
913 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
914 << " already forwarded";
915 size_t& offset = bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800916 DCHECK(!IsInBootImage(cur_fields));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700917 native_object_relocations_.emplace(
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800918 cur_fields,
919 NativeObjectRelocation {offset, kNativeObjectRelocationTypeArtFieldArray });
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700920 offset += header_size;
921 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +0100922 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700923 // Need to forward arrays separate of fields.
924 ArtField* field = &cur_fields->At(i);
925 auto it2 = native_object_relocations_.find(field);
926 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
927 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800928 DCHECK(!IsInBootImage(field));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700929 native_object_relocations_.emplace(
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800930 field,
931 NativeObjectRelocation {offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700932 offset += sizeof(ArtField);
933 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700934 }
935 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700936 // Visit and assign offsets for methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700937 LengthPrefixedArray<ArtMethod>* method_arrays[] = {
938 as_klass->GetDirectMethodsPtr(), as_klass->GetVirtualMethodsPtr(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700939 };
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700940 for (LengthPrefixedArray<ArtMethod>* array : method_arrays) {
941 if (array == nullptr) {
942 continue;
943 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700944 bool any_dirty = false;
945 size_t count = 0;
Vladimir Marko14632852015-08-17 12:07:23 +0100946 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
947 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +0100948 auto iteration_range =
949 MakeIterationRangeFromLengthPrefixedArray(array, method_size, method_alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700950 for (auto& m : iteration_range) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700951 any_dirty = any_dirty || WillMethodBeDirty(&m);
952 ++count;
953 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800954 NativeObjectRelocationType type = any_dirty
955 ? kNativeObjectRelocationTypeArtMethodDirty
956 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700957 Bin bin_type = BinTypeForNativeRelocationType(type);
958 // Forward the entire array at once, but header first.
Vladimir Markocf36d492015-08-12 19:27:26 +0100959 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
960 method_size,
961 method_alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700962 auto it = native_object_relocations_.find(array);
963 CHECK(it == native_object_relocations_.end()) << "Method array " << array
964 << " already forwarded";
965 size_t& offset = bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800966 DCHECK(!IsInBootImage(array));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700967 native_object_relocations_.emplace(array, NativeObjectRelocation { offset,
968 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty :
969 kNativeObjectRelocationTypeArtMethodArrayClean });
970 offset += header_size;
971 for (auto& m : iteration_range) {
972 AssignMethodOffset(&m, type);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700973 }
974 (any_dirty ? dirty_methods_ : clean_methods_) += count;
975 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700976 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700977 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700978 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700979 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700980 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700981 mirror::Object* value = obj_array->Get(i);
982 if (value != nullptr) {
983 WalkFieldsInOrder(value);
984 }
985 }
986 }
987 }
988}
989
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700990void ImageWriter::AssignMethodOffset(ArtMethod* method, NativeObjectRelocationType type) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800991 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700992 auto it = native_object_relocations_.find(method);
993 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -0700994 << PrettyMethod(method);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700995 size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
996 native_object_relocations_.emplace(method, NativeObjectRelocation { offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +0100997 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700998}
999
Mathieu Chartier590fee92013-09-13 13:46:47 -07001000void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1001 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1002 DCHECK(writer != nullptr);
1003 writer->WalkFieldsInOrder(obj);
1004}
1005
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001006void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1007 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1008 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001009 if (!writer->IsInBootImage(obj)) {
1010 writer->UnbinObjectsIntoOffset(obj);
1011 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001012}
1013
1014void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001015 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001016 CHECK(obj != nullptr);
1017
1018 // We know the bin slot, and the total bin sizes for all objects by now,
1019 // so calculate the object's final image offset.
1020
1021 DCHECK(IsImageBinSlotAssigned(obj));
1022 BinSlot bin_slot = GetImageBinSlot(obj);
1023 // Change the lockword from a bin slot into an offset
1024 AssignImageOffset(obj, bin_slot);
1025}
1026
Vladimir Markof4da6752014-08-01 19:04:18 +01001027void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001028 Thread* const self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001029 StackHandleScope<1> hs(self);
1030 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001031
Mathieu Chartiere401d142015-04-22 13:56:20 -07001032 auto* runtime = Runtime::Current();
1033 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001034 DCHECK_EQ(0U, image_end_);
1035
Mathieu Chartier31e89252013-08-28 11:29:12 -07001036 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001037 // know where image_roots is going to end up
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001038 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001039
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001040 image_objects_offset_begin_ = image_end_;
1041 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1042 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001043 // Write the image runtime methods.
1044 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1045 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1046 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1047 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1048 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1049 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1050 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1051 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001052
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001053 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001054 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1055 auto it = native_object_relocations_.find(&image_method_array_);
1056 CHECK(it == native_object_relocations_.end());
1057 size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001058 if (!compile_app_image_) {
1059 native_object_relocations_.emplace(&image_method_array_,
1060 NativeObjectRelocation { offset, image_method_type });
1061 }
Vladimir Marko14632852015-08-17 12:07:23 +01001062 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001063 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001064 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001065 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001066 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001067 for (auto* m : image_methods_) {
1068 CHECK(m != nullptr);
1069 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001070 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1071 if (!IsInBootImage(m)) {
1072 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean);
1073 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001074 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001075 // Calculate size of the dex cache arrays slot and prepare offsets.
1076 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001077
Vladimir Markocf36d492015-08-12 19:27:26 +01001078 // Calculate bin slot offsets.
1079 size_t bin_offset = image_objects_offset_begin_;
Vladimir Marko20f85592015-03-19 10:07:02 +00001080 for (size_t i = 0; i != kBinSize; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01001081 bin_slot_offsets_[i] = bin_offset;
1082 bin_offset += bin_slot_sizes_[i];
1083 if (i == kBinArtField) {
1084 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1085 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1086 DCHECK_ALIGNED(bin_offset, 4u);
1087 DCHECK(method_alignment == 4u || method_alignment == 8u);
1088 bin_offset = RoundUp(bin_offset, method_alignment);
1089 }
Vladimir Marko20f85592015-03-19 10:07:02 +00001090 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001091 // NOTE: There may be additional padding between the bin slots and the intern table.
1092
Mathieu Chartierc7853442015-03-27 14:35:38 -07001093 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
1094
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001095 // Transform each object's bin slot into an offset which will be used to do the final copy.
1096 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001097
Mathieu Chartierc7853442015-03-27 14:35:38 -07001098 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001099
Vladimir Markof4da6752014-08-01 19:04:18 +01001100 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
1101
Mathieu Chartiere401d142015-04-22 13:56:20 -07001102 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001103 for (auto& pair : native_object_relocations_) {
1104 NativeObjectRelocation& relocation = pair.second;
1105 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Markocf36d492015-08-12 19:27:26 +01001106 relocation.offset += bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001107 }
1108
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001109 // Calculate how big the intern table will be after being serialized.
1110 auto* const intern_table = Runtime::Current()->GetInternTable();
1111 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1112 intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1113
Mathieu Chartiere401d142015-04-22 13:56:20 -07001114 // Note that image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001115}
1116
1117void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
1118 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -07001119 const uint8_t* oat_file_begin = GetOatFileBegin();
1120 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001121 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -07001122 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001123
1124 // Create the image sections.
1125 ImageSection sections[ImageHeader::kSectionCount];
1126 // Objects section
1127 auto* objects_section = &sections[ImageHeader::kSectionObjects];
1128 *objects_section = ImageSection(0u, image_end_);
1129 size_t cur_pos = objects_section->End();
1130 // Add field section.
1131 auto* field_section = &sections[ImageHeader::kSectionArtFields];
1132 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
Vladimir Markocf36d492015-08-12 19:27:26 +01001133 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001134 cur_pos = field_section->End();
Vladimir Markocf36d492015-08-12 19:27:26 +01001135 // Round up to the alignment the required by the method section.
Vladimir Marko14632852015-08-17 12:07:23 +01001136 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001137 // Add method section.
1138 auto* methods_section = &sections[ImageHeader::kSectionArtMethods];
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001139 *methods_section = ImageSection(cur_pos,
1140 bin_slot_sizes_[kBinArtMethodClean] +
1141 bin_slot_sizes_[kBinArtMethodDirty]);
Vladimir Markocf36d492015-08-12 19:27:26 +01001142 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001143 cur_pos = methods_section->End();
Vladimir Marko05792b92015-08-03 11:56:49 +01001144 // Add dex cache arrays section.
1145 auto* dex_cache_arrays_section = &sections[ImageHeader::kSectionDexCacheArrays];
1146 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1147 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1148 cur_pos = dex_cache_arrays_section->End();
Nicolas Geoffray7bf2b4f2015-07-08 10:11:59 +00001149 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1150 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001151 // Calculate the size of the interned strings.
1152 auto* interned_strings_section = &sections[ImageHeader::kSectionInternedStrings];
1153 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1154 cur_pos = interned_strings_section->End();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001155 // Finally bitmap section.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001156 const size_t bitmap_bytes = image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001157 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
1158 *bitmap_section = ImageSection(RoundUp(cur_pos, kPageSize), RoundUp(bitmap_bytes, kPageSize));
1159 cur_pos = bitmap_section->End();
1160 if (kIsDebugBuild) {
1161 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001162 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001163 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1164 ++idx;
1165 }
1166 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
1167 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001168 const size_t image_end = static_cast<uint32_t>(interned_strings_section->End());
1169 CHECK_EQ(AlignUp(image_begin_ + image_end, kPageSize), oat_file_begin) <<
1170 "Oat file should be right after the image.";
Mathieu Chartiere401d142015-04-22 13:56:20 -07001171 // Create the header.
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001172 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
1173 image_end,
1174 sections,
1175 image_roots_address_,
1176 oat_file_->GetOatHeader().GetChecksum(),
1177 PointerToLowMemUInt32(oat_file_begin),
1178 PointerToLowMemUInt32(oat_data_begin_),
1179 PointerToLowMemUInt32(oat_data_end),
1180 PointerToLowMemUInt32(oat_file_end),
1181 target_ptr_size_,
1182 compile_pic_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001183}
1184
1185ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001186 auto it = native_object_relocations_.find(method);
1187 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001188 CHECK_GE(it->second.offset, image_end_) << "ArtMethods should be after Objects";
1189 return reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001190}
1191
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001192class FixupRootVisitor : public RootVisitor {
1193 public:
1194 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1195 }
1196
1197 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001198 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001199 for (size_t i = 0; i < count; ++i) {
1200 *roots[i] = ImageAddress(*roots[i]);
1201 }
1202 }
1203
1204 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1205 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001206 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001207 for (size_t i = 0; i < count; ++i) {
1208 roots[i]->Assign(ImageAddress(roots[i]->AsMirrorPtr()));
1209 }
1210 }
1211
1212 private:
1213 ImageWriter* const image_writer_;
1214
Mathieu Chartier90443472015-07-16 20:32:27 -07001215 mirror::Object* ImageAddress(mirror::Object* obj) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001216 const size_t offset = image_writer_->GetImageOffset(obj);
1217 auto* const dest = reinterpret_cast<Object*>(image_writer_->image_begin_ + offset);
1218 VLOG(compiler) << "Update root from " << obj << " to " << dest;
1219 return dest;
1220 }
1221};
1222
Mathieu Chartierc7853442015-03-27 14:35:38 -07001223void ImageWriter::CopyAndFixupNativeData() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001224 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001225 for (auto& pair : native_object_relocations_) {
1226 NativeObjectRelocation& relocation = pair.second;
1227 auto* dest = image_->Begin() + relocation.offset;
1228 DCHECK_GE(dest, image_->Begin() + image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001229 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001230 switch (relocation.type) {
1231 case kNativeObjectRelocationTypeArtField: {
1232 memcpy(dest, pair.first, sizeof(ArtField));
1233 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1234 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1235 break;
1236 }
1237 case kNativeObjectRelocationTypeArtMethodClean:
1238 case kNativeObjectRelocationTypeArtMethodDirty: {
1239 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
1240 reinterpret_cast<ArtMethod*>(dest));
1241 break;
1242 }
1243 // For arrays, copy just the header since the elements will get copied by their corresponding
1244 // relocations.
1245 case kNativeObjectRelocationTypeArtFieldArray: {
1246 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1247 break;
1248 }
1249 case kNativeObjectRelocationTypeArtMethodArrayClean:
1250 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001251 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1252 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001253 ArtMethod::Size(target_ptr_size_),
1254 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001255 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001256 case kNativeObjectRelocationTypeDexCacheArray:
1257 // Nothing to copy here, everything is done in FixupDexCache().
1258 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001259 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001260 }
1261 }
1262 // Fixup the image method roots.
1263 auto* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001264 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001265 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001266 ArtMethod* method = image_methods_[i];
1267 CHECK(method != nullptr);
1268 if (!IsInBootImage(method)) {
1269 auto it = native_object_relocations_.find(method);
1270 CHECK(it != native_object_relocations_.end()) << "No fowarding for " << PrettyMethod(method);
1271 NativeObjectRelocation& relocation = it->second;
1272 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1273 << methods_section;
1274 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
1275 method = reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
1276 }
1277 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001278 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001279 // Write the intern table into the image.
1280 const ImageSection& intern_table_section = image_header->GetImageSection(
1281 ImageHeader::kSectionInternedStrings);
1282 InternTable* const intern_table = Runtime::Current()->GetInternTable();
1283 uint8_t* const memory_ptr = image_->Begin() + intern_table_section.Offset();
1284 const size_t intern_table_bytes = intern_table->WriteToMemory(memory_ptr);
1285 // Fixup the pointers in the newly written intern table to contain image addresses.
1286 InternTable temp_table;
1287 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1288 // the VisitRoots() will update the memory directly rather than the copies.
1289 // This also relies on visit roots not doing any verification which could fail after we update
1290 // the roots to be the image addresses.
1291 temp_table.ReadFromMemory(memory_ptr);
1292 CHECK_EQ(temp_table.Size(), intern_table->Size());
1293 FixupRootVisitor visitor(this);
1294 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
1295 CHECK_EQ(intern_table_bytes, intern_table_bytes_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001296}
1297
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001298void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001299 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001300 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1301 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001302 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001303 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001304 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1305 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001306 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001307 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001308}
1309
Mathieu Chartier590fee92013-09-13 13:46:47 -07001310void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001311 DCHECK(obj != nullptr);
1312 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001313 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1314}
1315
Mathieu Chartiere401d142015-04-22 13:56:20 -07001316void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1317 mirror::Class* klass, Bin array_type) {
1318 CHECK(klass->IsArrayClass());
1319 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1320 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001321 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001322 dst->SetClass(GetImageAddress(arr->GetClass()));
1323 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001324 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001325 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1326 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001327 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001328 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001329 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001330 auto* method = reinterpret_cast<ArtMethod*>(elem);
1331 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1332 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1333 << PrettyClass(method->GetDeclaringClass());
1334 } else {
1335 CHECK_EQ(array_type, kBinArtField);
1336 auto* field = reinterpret_cast<ArtField*>(elem);
1337 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1338 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1339 << PrettyClass(field->GetDeclaringClass());
1340 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001341 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001342 } else {
1343 elem = image_begin_ + it->second.offset;
1344 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001345 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001346 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001347 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001348}
1349
1350void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001351 if (IsInBootImage(obj)) {
1352 return;
1353 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001354 size_t offset = GetImageOffset(obj);
1355 auto* dst = reinterpret_cast<Object*>(image_->Begin() + offset);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001356 DCHECK_LT(offset, image_end_);
1357 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001358
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001359 image_bitmap_->Set(dst); // Mark the obj as live.
1360
1361 const size_t n = obj->SizeOf();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001362 DCHECK_LE(offset + n, image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001363 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001364
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001365 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1366 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001367 const auto it = saved_hashcode_map_.find(obj);
1368 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1369 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001370 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001371}
1372
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001373// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001374class FixupVisitor {
1375 public:
1376 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1377 }
1378
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001379 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1380 // with other logic.
1381 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1382 const {}
1383 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1384
1385
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001386 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001387 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001388 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001389 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1390 // image.
1391 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001392 offset,
1393 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001394 }
1395
1396 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001397 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001398 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001399 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001400 mirror::Reference::ReferentOffset(),
1401 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001402 }
1403
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001404 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001405 ImageWriter* const image_writer_;
1406 mirror::Object* const copy_;
1407};
1408
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001409class FixupClassVisitor FINAL : public FixupVisitor {
1410 public:
1411 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1412 }
1413
Mathieu Chartierc7853442015-03-27 14:35:38 -07001414 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001415 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001416 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001417 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001418 }
1419
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001420 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1421 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001422 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001423 LOG(FATAL) << "Reference not expected here.";
1424 }
1425};
1426
Vladimir Marko05792b92015-08-03 11:56:49 +01001427uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1428 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001429 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001430 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001431 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1432 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001433 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001434 return relocation.offset;
1435}
1436
1437template <typename T>
1438T* ImageWriter::NativeLocationInImage(T* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001439 return (obj == nullptr || IsInBootImage(obj))
1440 ? obj
1441 : reinterpret_cast<T*>(image_begin_ + NativeOffsetInImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001442}
1443
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001444template <typename T>
1445T* ImageWriter::NativeCopyLocation(T* obj) {
1446 return (obj == nullptr || IsInBootImage(obj))
1447 ? obj
1448 : reinterpret_cast<T*>(image_->Begin() + NativeOffsetInImage(obj));
1449}
1450
1451class NativeLocationVisitor {
1452 public:
1453 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1454
1455 template <typename T>
1456 T* operator()(T* ptr) const {
1457 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001458 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001459
1460 private:
1461 ImageWriter* const image_writer_;
1462};
1463
1464void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
1465 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001466 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001467 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001468}
1469
Ian Rogersef7d42f2014-01-06 12:55:46 -08001470void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001471 DCHECK(orig != nullptr);
1472 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001473 if (kUseBakerOrBrooksReadBarrier) {
1474 orig->AssertReadBarrierPointer();
1475 if (kUseBrooksReadBarrier) {
1476 // Note the address 'copy' isn't the same as the image address of 'orig'.
1477 copy->SetReadBarrierPointer(GetImageAddress(orig));
1478 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1479 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001480 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001481 auto* klass = orig->GetClass();
1482 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001483 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001484 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1485 if (it != pointer_arrays_.end()) {
1486 // Should only need to fixup every pointer array exactly once.
1487 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1488 pointer_arrays_.erase(it);
1489 return;
1490 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001491 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001492 if (orig->IsClass()) {
1493 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001494 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001495 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1496 // Need to go update the ArtMethod.
1497 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1498 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1499 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001500 auto it = native_object_relocations_.find(src_method);
1501 CHECK(it != native_object_relocations_.end())
1502 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001503 dest->SetArtMethod(
1504 reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001505 } else if (!klass->IsArrayClass()) {
1506 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1507 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1508 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
1509 } else if (klass->IsSubClass(down_cast<mirror::Class*>(
1510 class_linker->GetClassRoot(ClassLinker::kJavaLangClassLoader)))) {
1511 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1512 // ClassLoader.
1513 down_cast<mirror::ClassLoader*>(copy)->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001514 // Also set allocator to null to be safe. The allocator is created when we create the class
1515 // table. We also never expect to unload things in the image since they are held live as
1516 // roots.
1517 down_cast<mirror::ClassLoader*>(copy)->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001518 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001519 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001520 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001521 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001522 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001523}
1524
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001525
1526class ImageAddressVisitor {
1527 public:
1528 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1529
1530 template <typename T>
1531 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1532 return image_writer_->GetImageAddress(ptr);
1533 }
1534
1535 private:
1536 ImageWriter* const image_writer_;
1537};
1538
1539
Vladimir Marko05792b92015-08-03 11:56:49 +01001540void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1541 mirror::DexCache* copy_dex_cache) {
1542 // Though the DexCache array fields are usually treated as native pointers, we set the full
1543 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1544 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1545 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1546 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1547 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001548 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
1549 NativeLocationInImage(orig_strings),
1550 /*pointer size*/8u);
1551 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings), ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001552 }
1553 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1554 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001555 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
1556 NativeLocationInImage(orig_types),
1557 /*pointer size*/8u);
1558 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types), ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001559 }
1560 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1561 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001562 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
1563 NativeLocationInImage(orig_methods),
1564 /*pointer size*/8u);
1565 ArtMethod** copy_methods = NativeCopyLocation(orig_methods);
Vladimir Marko05792b92015-08-03 11:56:49 +01001566 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1567 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001568 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001569 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1570 }
1571 }
1572 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1573 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001574 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
1575 NativeLocationInImage(orig_fields),
1576 /*pointer size*/8u);
1577 ArtField** copy_fields = NativeCopyLocation(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +01001578 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1579 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001580 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001581 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1582 }
1583 }
1584}
1585
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001586const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1587 DCHECK_LT(type, kOatAddressCount);
1588 // If we are compiling an app image, we need to use the stubs of the boot image.
1589 if (compile_app_image_) {
1590 // Use the current image pointers.
Mathieu Chartier073b16c2015-11-10 14:13:23 -08001591 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetBootImageSpace();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001592 DCHECK(image_space != nullptr);
1593 const OatFile* oat_file = image_space->GetOatFile();
1594 CHECK(oat_file != nullptr);
1595 const OatHeader& header = oat_file->GetOatHeader();
1596 switch (type) {
1597 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1598 case kOatAddressQuickGenericJNITrampoline:
1599 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1600 case kOatAddressInterpreterToInterpreterBridge:
1601 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1602 case kOatAddressInterpreterToCompiledCodeBridge:
1603 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1604 case kOatAddressJNIDlsymLookup:
1605 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1606 case kOatAddressQuickIMTConflictTrampoline:
1607 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1608 case kOatAddressQuickResolutionTrampoline:
1609 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1610 case kOatAddressQuickToInterpreterBridge:
1611 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1612 default:
1613 UNREACHABLE();
1614 }
1615 }
1616 return GetOatAddressForOffset(oat_address_offsets_[type]);
1617}
1618
Mathieu Chartiere401d142015-04-22 13:56:20 -07001619const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method, bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001620 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
1621 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
1622 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07001623 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001624 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001625
1626 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1627 // trampoline.
1628
1629 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001630 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1631 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001632 const uint8_t* quick_code = GetOatAddressForOffset(quick_oat_code_offset);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001633 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001634 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
1635 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001636 // We have code for a non-static or initialized method, just use the code.
1637 } else if (quick_code == nullptr && method->IsNative() &&
1638 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1639 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001640 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001641 } else if (quick_code == nullptr && !method->IsNative()) {
1642 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001643 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001644 *quick_is_interpreted = true;
1645 } else {
1646 CHECK(!method->GetDeclaringClass()->IsInitialized());
1647 // We have code for a static method, but need to go through the resolution stub for class
1648 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001649 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
1650 }
1651 if (!IsInBootOatFile(quick_code)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001652 DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001653 }
1654 return quick_code;
1655}
1656
Mathieu Chartiere401d142015-04-22 13:56:20 -07001657const uint8_t* ImageWriter::GetQuickEntryPoint(ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001658 // Calculate the quick entry point following the same logic as FixupMethod() below.
1659 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001660 Runtime* runtime = Runtime::Current();
1661 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001662 return GetOatAddress(kOatAddressQuickResolutionTrampoline);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001663 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
1664 method == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001665 return GetOatAddress(kOatAddressQuickIMTConflictTrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001666 } else {
1667 // We assume all methods have code. If they don't currently then we set them to the use the
1668 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1669 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07001670 if (UNLIKELY(!method->IsInvokable())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001671 return GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001672 } else {
1673 bool quick_is_interpreted;
1674 return GetQuickCode(method, &quick_is_interpreted);
1675 }
1676 }
1677}
1678
Mathieu Chartiere401d142015-04-22 13:56:20 -07001679void ImageWriter::CopyAndFixupMethod(ArtMethod* orig, ArtMethod* copy) {
Vladimir Marko14632852015-08-17 12:07:23 +01001680 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001681
1682 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01001683
1684 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
1685 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
1686 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
1687 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001688
Ian Rogers848871b2013-08-05 10:56:33 -07001689 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1690 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07001691
Ian Rogers848871b2013-08-05 10:56:33 -07001692 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001693 Runtime* runtime = Runtime::Current();
1694 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001695 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001696 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001697 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1698 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001699 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001700 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001701 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
1702 bool found_one = false;
1703 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
1704 auto idx = static_cast<Runtime::CalleeSaveType>(i);
1705 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
1706 found_one = true;
1707 break;
1708 }
1709 }
1710 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
1711 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001712 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001713 // We assume all methods have code. If they don't currently then we set them to the use the
1714 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1715 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07001716 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001717 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001718 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001719 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001720 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -07001721 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001722 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001723
Sebastien Hertze1d07812014-05-21 15:44:09 +02001724 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001725 if (orig->IsNative()) {
1726 // The native method's pointer is set to a stub to lookup via dlsym.
1727 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001728 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001729 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001730 }
1731 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001732 }
1733}
1734
Alex Lighta59dd802014-07-02 16:28:08 -07001735static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001736 uint64_t data_sec_offset;
1737 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1738 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001739 return nullptr;
1740 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001741 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001742}
1743
Vladimir Markof4da6752014-08-01 19:04:18 +01001744void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001745 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001746 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file,
1747 PROT_READ | PROT_WRITE,
1748 MAP_SHARED,
1749 &error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001750 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001751 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001752 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001753 }
Alex Lighta59dd802014-07-02 16:28:08 -07001754 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1755 CHECK(oat_header != nullptr);
1756 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001757
Brian Carlstrom7940e442013-07-12 13:46:57 -07001758 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001759 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001760}
1761
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001762size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1763 DCHECK_LE(up_to, kBinSize);
1764 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1765}
1766
1767ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1768 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07001769 static_assert(kBinBits == 3, "wrong number of bin bits");
1770 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001771 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1772
1773 DCHECK_LT(GetBin(), kBinSize);
1774 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1775}
1776
1777ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1778 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1779 DCHECK_EQ(index, GetIndex());
1780}
1781
1782ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1783 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1784}
1785
1786uint32_t ImageWriter::BinSlot::GetIndex() const {
1787 return lockword_ & ~kBinMask;
1788}
1789
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001790uint8_t* ImageWriter::GetOatFileBegin() const {
1791 DCHECK_GT(intern_table_bytes_, 0u);
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001792 size_t native_sections_size = bin_slot_sizes_[kBinArtField] +
1793 bin_slot_sizes_[kBinArtMethodDirty] +
1794 bin_slot_sizes_[kBinArtMethodClean] +
1795 bin_slot_sizes_[kBinDexCacheArray] +
1796 intern_table_bytes_;
Vladimir Marko05792b92015-08-03 11:56:49 +01001797 return image_begin_ + RoundUp(image_end_ + native_sections_size, kPageSize);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001798}
1799
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001800ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
1801 switch (type) {
1802 case kNativeObjectRelocationTypeArtField:
1803 case kNativeObjectRelocationTypeArtFieldArray:
1804 return kBinArtField;
1805 case kNativeObjectRelocationTypeArtMethodClean:
1806 case kNativeObjectRelocationTypeArtMethodArrayClean:
1807 return kBinArtMethodClean;
1808 case kNativeObjectRelocationTypeArtMethodDirty:
1809 case kNativeObjectRelocationTypeArtMethodArrayDirty:
1810 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01001811 case kNativeObjectRelocationTypeDexCacheArray:
1812 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001813 }
1814 UNREACHABLE();
1815}
1816
Brian Carlstrom7940e442013-07-12 13:46:57 -07001817} // namespace art