blob: 0c853238055372f7759d9b66df75a72596c78708 [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;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700337 for (jobject weak_root : class_linker->GetDexCaches()) {
338 mirror::DexCache* dex_cache =
339 down_cast<mirror::DexCache*>(self->DecodeJObject(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++) {
375 auto* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
376 if (method != nullptr && !method->IsRuntimeMethod()) {
377 auto* 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()])
517 << "bin slot offset should not exceed the size of that bin";
518 }
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;
Vladimir Marko5c42c292015-02-25 12:02:49 +0000540 image_.reset(MemMap::MapAnonymous("image writer image", nullptr, length, PROT_READ | PROT_WRITE,
541 false, false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700542 if (UNLIKELY(image_.get() == nullptr)) {
543 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700544 return false;
545 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700546
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700547 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
548 CHECK_LE(image_end_, length);
549 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
550 "image bitmap", image_->Begin(), RoundUp(image_end_, kPageSize)));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700551 if (image_bitmap_.get() == nullptr) {
552 LOG(ERROR) << "Failed to allocate memory for image bitmap";
553 return false;
554 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700555 return true;
556}
557
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700558class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
559 public:
560 bool Visit(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
561 StackHandleScope<1> hs(Thread::Current());
562 mirror::Class::ComputeName(hs.NewHandle(c));
563 return true;
564 }
565};
566
Brian Carlstrom7940e442013-07-12 13:46:57 -0700567void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700568 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700569 ComputeLazyFieldsForClassesVisitor visitor;
570 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700571}
572
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800573static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
574 return klass->GetClassLoader() == nullptr;
575}
576
577bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
578 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
579}
580
581bool ImageWriter::ContainsBootClassLoaderNonImageClass(mirror::Class* klass) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700582 if (klass == nullptr) {
583 return false;
584 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800585 auto found = prune_class_memo_.find(klass);
586 if (found != prune_class_memo_.end()) {
587 // Already computed, return the found value.
588 return found->second;
589 }
590 // Place holder value to prevent infinite recursion.
591 prune_class_memo_.emplace(klass, false);
592 bool result = IsBootClassLoaderNonImageClass(klass);
593 if (!result) {
594 // Check interfaces since these wont be visited through VisitReferences.)
595 mirror::IfTable* if_table = klass->GetIfTable();
596 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
597 result = result || ContainsBootClassLoaderNonImageClass(if_table->GetInterface(i));
598 }
599 }
600 // Check static fields and their classes.
601 size_t num_static_fields = klass->NumReferenceStaticFields();
602 if (num_static_fields != 0 && klass->IsResolved()) {
603 // Presumably GC can happen when we are cross compiling, it should not cause performance
604 // problems to do pointer size logic.
605 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
606 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
607 for (size_t i = 0u; i < num_static_fields; ++i) {
608 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
609 if (ref != nullptr) {
610 if (ref->IsClass()) {
611 result = result || ContainsBootClassLoaderNonImageClass(ref->AsClass());
612 }
613 result = result || ContainsBootClassLoaderNonImageClass(ref->GetClass());
614 }
615 field_offset = MemberOffset(field_offset.Uint32Value() +
616 sizeof(mirror::HeapReference<mirror::Object>));
617 }
618 }
619 result = result || ContainsBootClassLoaderNonImageClass(klass->GetSuperClass());
620 prune_class_memo_[klass] = result;
621 return result;
622}
623
624bool ImageWriter::KeepClass(Class* klass) {
625 if (klass == nullptr) {
626 return false;
627 }
628 if (compile_app_image_) {
629 // For app images, we need to prune boot loader classes that are not in the boot image since
630 // these may have already been loaded when the app image is loaded.
631 return !ContainsBootClassLoaderNonImageClass(klass);
632 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700633 std::string temp;
634 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700635}
636
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700637class NonImageClassesVisitor : public ClassVisitor {
638 public:
639 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
640
641 bool Visit(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800642 if (!image_writer_->KeepClass(klass)) {
643 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700644 }
645 return true;
646 }
647
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800648 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700649 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700650};
651
652void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700653 Runtime* runtime = Runtime::Current();
654 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700655 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700656
657 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700658 NonImageClassesVisitor visitor(this);
659 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700660
661 // Remove the undesired classes from the class roots.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800662 for (mirror::Class* klass : visitor.classes_to_prune_) {
663 std::string temp;
664 const char* name = klass->GetDescriptor(&temp);
665 VLOG(compiler) << "Pruning class " << name;
666 if (!compile_app_image_) {
667 DCHECK(IsBootClassLoaderClass(klass));
668 }
669 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800670 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700671 }
672
673 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100674 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700675
676 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
677 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
678 ReaderMutexLock mu2(self, *class_linker->DexLock());
679 for (jobject weak_root : class_linker->GetDexCaches()) {
680 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
681 if (dex_cache == nullptr) {
682 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700683 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700684 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
685 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800686 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700687 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700688 }
689 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100690 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
691 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
692 ArtMethod* method =
693 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700694 if (method != nullptr) {
695 auto* declaring_class = method->GetDeclaringClass();
696 // Miranda methods may be held live by a class which was not an image class but have a
697 // declaring class which is an image class. Set it to the resolution method to be safe and
698 // prevent dangling pointers.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800699 if (method->IsMiranda() || !KeepClass(declaring_class)) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100700 mirror::DexCache::SetElementPtrSize(resolved_methods,
701 i,
702 resolution_method,
703 target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700704 } else {
705 // Check that the class is still in the classes table.
706 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
707 << PrettyClass(declaring_class) << " not in class linker table";
708 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700709 }
710 }
711 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700712 ArtField* field = dex_cache->GetResolvedField(i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800713 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700714 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700715 }
716 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700717 // Clean the dex field. It might have been populated during the initialization phase, but
718 // contains data only valid during a real run.
719 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700720 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700721
722 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
723 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800724
725 // Clear to save RAM.
726 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700727}
728
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800729void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700730 if (compiler_driver_.GetImageClasses() != nullptr) {
731 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700732 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700733 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700734}
735
736void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
737 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800738 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700739 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800740 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700741 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700742 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800743 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
744 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700745 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700746 }
747}
748
749void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700750 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700751 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700752 for (const std::string& image_class : *image_classes) {
753 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700754 }
755}
756
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800757void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700758 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700759 // if it is a string, we want to intern it if its not interned.
760 if (obj->GetClass()->IsStringClass()) {
761 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800762 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700763 DCHECK_EQ(obj, obj->AsString()->Intern());
764 return;
765 }
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700766 // InternImageString allows us to intern while holding the heap bitmap lock. This is safe since
767 // we are guaranteed to not have GC during image writing.
Mathieu Chartier90ef3db2015-08-04 15:19:41 -0700768 mirror::String* const interned = Runtime::Current()->GetInternTable()->InternStrongImageString(
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700769 obj->AsString());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700770 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800771 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700772 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800773 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700774 }
775 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800776 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700777 return;
778 }
779 // else (obj == interned), nothing to do but fall through to the normal case
780 }
781
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800782 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700783}
784
785ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
786 Runtime* runtime = Runtime::Current();
787 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700788 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700789 StackHandleScope<3> hs(self);
790 Handle<Class> object_array_class(hs.NewHandle(
791 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700792
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700793 // build an Object[] of all the DexCaches used in the source_space_.
794 // Since we can't hold the dex lock when allocating the dex_caches
795 // ObjectArray, we lock the dex lock twice, first to get the number
796 // of dex caches first and then lock it again to copy the dex
797 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800798 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700799 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700800 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800801 // Count number of dex caches not in the boot image.
802 for (jobject weak_root : class_linker->GetDexCaches()) {
803 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
804 dex_cache_count += IsInBootImage(dex_cache) ? 0u : 1u;
805 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700806 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700807 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800808 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700809 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
810 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700811 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800812 size_t non_image_dex_caches = 0;
813 // Re-count number of non image dex caches.
814 for (jobject weak_root : class_linker->GetDexCaches()) {
815 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
816 non_image_dex_caches += IsInBootImage(dex_cache) ? 0u : 1u;
817 }
818 CHECK_EQ(dex_cache_count, non_image_dex_caches)
819 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700820 size_t i = 0;
821 for (jobject weak_root : class_linker->GetDexCaches()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800822 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
823 if (!IsInBootImage(dex_cache)) {
824 dex_caches->Set<false>(i, dex_cache);
825 ++i;
826 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700827 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700828 }
829
830 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -0700831 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700832 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700833 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100834 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700835 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700836 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700837 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700838 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700839}
840
Mathieu Chartier590fee92013-09-13 13:46:47 -0700841// Walk instance fields of the given Class. Separate function to allow recursion on the super
842// class.
843void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
844 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700845 StackHandleScope<1> hs(Thread::Current());
846 Handle<mirror::Class> h_class(hs.NewHandle(klass));
847 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700848 if (super != nullptr) {
849 WalkInstanceFields(obj, super);
850 }
851 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700852 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000853 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700854 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700855 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700856 if (value != nullptr) {
857 WalkFieldsInOrder(value);
858 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000859 field_offset = MemberOffset(field_offset.Uint32Value() +
860 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700861 }
862}
863
864// For an unvisited object, visit it then all its children found via fields.
865void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800866 if (IsInBootImage(obj)) {
867 // Object is in the image, don't need to fix it up.
868 return;
869 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800870 // Use our own visitor routine (instead of GC visitor) to get better locality between
871 // an object and its fields
872 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700873 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700874 StackHandleScope<2> hs(Thread::Current());
875 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
876 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700877 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800878 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700879 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700880 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700881 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700882 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700883 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700884 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700885 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700886 if (value != nullptr) {
887 WalkFieldsInOrder(value);
888 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000889 field_offset = MemberOffset(field_offset.Uint32Value() +
890 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700891 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700892 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700893 auto* as_klass = h_obj->AsClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700894 LengthPrefixedArray<ArtField>* fields[] = {
895 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
896 };
897 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
898 // Total array length including header.
899 if (cur_fields != nullptr) {
900 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
901 // Forward the entire array at once.
902 auto it = native_object_relocations_.find(cur_fields);
903 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
904 << " already forwarded";
905 size_t& offset = bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800906 DCHECK(!IsInBootImage(cur_fields));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700907 native_object_relocations_.emplace(
908 cur_fields, NativeObjectRelocation {
909 offset, kNativeObjectRelocationTypeArtFieldArray });
910 offset += header_size;
911 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +0100912 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700913 // Need to forward arrays separate of fields.
914 ArtField* field = &cur_fields->At(i);
915 auto it2 = native_object_relocations_.find(field);
916 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
917 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800918 DCHECK(!IsInBootImage(field));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700919 native_object_relocations_.emplace(
920 field, NativeObjectRelocation {offset, kNativeObjectRelocationTypeArtField });
921 offset += sizeof(ArtField);
922 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700923 }
924 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700925 // Visit and assign offsets for methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700926 LengthPrefixedArray<ArtMethod>* method_arrays[] = {
927 as_klass->GetDirectMethodsPtr(), as_klass->GetVirtualMethodsPtr(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700928 };
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700929 for (LengthPrefixedArray<ArtMethod>* array : method_arrays) {
930 if (array == nullptr) {
931 continue;
932 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700933 bool any_dirty = false;
934 size_t count = 0;
Vladimir Marko14632852015-08-17 12:07:23 +0100935 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
936 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +0100937 auto iteration_range =
938 MakeIterationRangeFromLengthPrefixedArray(array, method_size, method_alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700939 for (auto& m : iteration_range) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700940 any_dirty = any_dirty || WillMethodBeDirty(&m);
941 ++count;
942 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700943 NativeObjectRelocationType type = any_dirty ? kNativeObjectRelocationTypeArtMethodDirty :
944 kNativeObjectRelocationTypeArtMethodClean;
945 Bin bin_type = BinTypeForNativeRelocationType(type);
946 // Forward the entire array at once, but header first.
Vladimir Markocf36d492015-08-12 19:27:26 +0100947 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
948 method_size,
949 method_alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700950 auto it = native_object_relocations_.find(array);
951 CHECK(it == native_object_relocations_.end()) << "Method array " << array
952 << " already forwarded";
953 size_t& offset = bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800954 DCHECK(!IsInBootImage(array));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700955 native_object_relocations_.emplace(array, NativeObjectRelocation { offset,
956 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty :
957 kNativeObjectRelocationTypeArtMethodArrayClean });
958 offset += header_size;
959 for (auto& m : iteration_range) {
960 AssignMethodOffset(&m, type);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700961 }
962 (any_dirty ? dirty_methods_ : clean_methods_) += count;
963 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700964 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700965 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700966 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700967 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700968 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700969 mirror::Object* value = obj_array->Get(i);
970 if (value != nullptr) {
971 WalkFieldsInOrder(value);
972 }
973 }
974 }
975 }
976}
977
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700978void ImageWriter::AssignMethodOffset(ArtMethod* method, NativeObjectRelocationType type) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800979 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700980 auto it = native_object_relocations_.find(method);
981 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -0700982 << PrettyMethod(method);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700983 size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
984 native_object_relocations_.emplace(method, NativeObjectRelocation { offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +0100985 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700986}
987
Mathieu Chartier590fee92013-09-13 13:46:47 -0700988void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
989 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
990 DCHECK(writer != nullptr);
991 writer->WalkFieldsInOrder(obj);
992}
993
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800994void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
995 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
996 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800997 if (!writer->IsInBootImage(obj)) {
998 writer->UnbinObjectsIntoOffset(obj);
999 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001000}
1001
1002void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001003 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001004 CHECK(obj != nullptr);
1005
1006 // We know the bin slot, and the total bin sizes for all objects by now,
1007 // so calculate the object's final image offset.
1008
1009 DCHECK(IsImageBinSlotAssigned(obj));
1010 BinSlot bin_slot = GetImageBinSlot(obj);
1011 // Change the lockword from a bin slot into an offset
1012 AssignImageOffset(obj, bin_slot);
1013}
1014
Vladimir Markof4da6752014-08-01 19:04:18 +01001015void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001016 Thread* const self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001017 StackHandleScope<1> hs(self);
1018 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001019
Mathieu Chartiere401d142015-04-22 13:56:20 -07001020 auto* runtime = Runtime::Current();
1021 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001022 DCHECK_EQ(0U, image_end_);
1023
Mathieu Chartier31e89252013-08-28 11:29:12 -07001024 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001025 // know where image_roots is going to end up
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001026 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001027
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001028 image_objects_offset_begin_ = image_end_;
1029 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1030 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001031 // Write the image runtime methods.
1032 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1033 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1034 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1035 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1036 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1037 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1038 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1039 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001040
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001041 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001042 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1043 auto it = native_object_relocations_.find(&image_method_array_);
1044 CHECK(it == native_object_relocations_.end());
1045 size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001046 if (!compile_app_image_) {
1047 native_object_relocations_.emplace(&image_method_array_,
1048 NativeObjectRelocation { offset, image_method_type });
1049 }
Vladimir Marko14632852015-08-17 12:07:23 +01001050 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001051 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001052 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001053 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001054 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001055 for (auto* m : image_methods_) {
1056 CHECK(m != nullptr);
1057 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001058 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1059 if (!IsInBootImage(m)) {
1060 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean);
1061 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001062 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001063 // Calculate size of the dex cache arrays slot and prepare offsets.
1064 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001065
Vladimir Markocf36d492015-08-12 19:27:26 +01001066 // Calculate bin slot offsets.
1067 size_t bin_offset = image_objects_offset_begin_;
Vladimir Marko20f85592015-03-19 10:07:02 +00001068 for (size_t i = 0; i != kBinSize; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01001069 bin_slot_offsets_[i] = bin_offset;
1070 bin_offset += bin_slot_sizes_[i];
1071 if (i == kBinArtField) {
1072 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1073 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1074 DCHECK_ALIGNED(bin_offset, 4u);
1075 DCHECK(method_alignment == 4u || method_alignment == 8u);
1076 bin_offset = RoundUp(bin_offset, method_alignment);
1077 }
Vladimir Marko20f85592015-03-19 10:07:02 +00001078 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001079 // NOTE: There may be additional padding between the bin slots and the intern table.
1080
Mathieu Chartierc7853442015-03-27 14:35:38 -07001081 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
1082
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001083 // Transform each object's bin slot into an offset which will be used to do the final copy.
1084 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001085
Mathieu Chartierc7853442015-03-27 14:35:38 -07001086 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001087
Vladimir Markof4da6752014-08-01 19:04:18 +01001088 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
1089
Mathieu Chartiere401d142015-04-22 13:56:20 -07001090 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001091 for (auto& pair : native_object_relocations_) {
1092 NativeObjectRelocation& relocation = pair.second;
1093 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Markocf36d492015-08-12 19:27:26 +01001094 relocation.offset += bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001095 }
1096
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001097 // Calculate how big the intern table will be after being serialized.
1098 auto* const intern_table = Runtime::Current()->GetInternTable();
1099 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1100 intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1101
Mathieu Chartiere401d142015-04-22 13:56:20 -07001102 // Note that image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001103}
1104
1105void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
1106 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -07001107 const uint8_t* oat_file_begin = GetOatFileBegin();
1108 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001109 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -07001110 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001111
1112 // Create the image sections.
1113 ImageSection sections[ImageHeader::kSectionCount];
1114 // Objects section
1115 auto* objects_section = &sections[ImageHeader::kSectionObjects];
1116 *objects_section = ImageSection(0u, image_end_);
1117 size_t cur_pos = objects_section->End();
1118 // Add field section.
1119 auto* field_section = &sections[ImageHeader::kSectionArtFields];
1120 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
Vladimir Markocf36d492015-08-12 19:27:26 +01001121 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001122 cur_pos = field_section->End();
Vladimir Markocf36d492015-08-12 19:27:26 +01001123 // Round up to the alignment the required by the method section.
Vladimir Marko14632852015-08-17 12:07:23 +01001124 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001125 // Add method section.
1126 auto* methods_section = &sections[ImageHeader::kSectionArtMethods];
1127 *methods_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtMethodClean] +
1128 bin_slot_sizes_[kBinArtMethodDirty]);
Vladimir Markocf36d492015-08-12 19:27:26 +01001129 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001130 cur_pos = methods_section->End();
Vladimir Marko05792b92015-08-03 11:56:49 +01001131 // Add dex cache arrays section.
1132 auto* dex_cache_arrays_section = &sections[ImageHeader::kSectionDexCacheArrays];
1133 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1134 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1135 cur_pos = dex_cache_arrays_section->End();
Nicolas Geoffray7bf2b4f2015-07-08 10:11:59 +00001136 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1137 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001138 // Calculate the size of the interned strings.
1139 auto* interned_strings_section = &sections[ImageHeader::kSectionInternedStrings];
1140 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1141 cur_pos = interned_strings_section->End();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001142 // Finally bitmap section.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001143 const size_t bitmap_bytes = image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001144 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
1145 *bitmap_section = ImageSection(RoundUp(cur_pos, kPageSize), RoundUp(bitmap_bytes, kPageSize));
1146 cur_pos = bitmap_section->End();
1147 if (kIsDebugBuild) {
1148 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001149 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001150 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1151 ++idx;
1152 }
1153 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
1154 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001155 const size_t image_end = static_cast<uint32_t>(interned_strings_section->End());
1156 CHECK_EQ(AlignUp(image_begin_ + image_end, kPageSize), oat_file_begin) <<
1157 "Oat file should be right after the image.";
Mathieu Chartiere401d142015-04-22 13:56:20 -07001158 // Create the header.
1159 new (image_->Begin()) ImageHeader(
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001160 PointerToLowMemUInt32(image_begin_), image_end,
1161 sections, image_roots_address_, oat_file_->GetOatHeader().GetChecksum(),
Mathieu Chartiere401d142015-04-22 13:56:20 -07001162 PointerToLowMemUInt32(oat_file_begin), PointerToLowMemUInt32(oat_data_begin_),
1163 PointerToLowMemUInt32(oat_data_end), PointerToLowMemUInt32(oat_file_end), target_ptr_size_,
1164 compile_pic_);
1165}
1166
1167ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001168 auto it = native_object_relocations_.find(method);
1169 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001170 CHECK_GE(it->second.offset, image_end_) << "ArtMethods should be after Objects";
1171 return reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001172}
1173
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001174class FixupRootVisitor : public RootVisitor {
1175 public:
1176 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1177 }
1178
1179 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001180 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001181 for (size_t i = 0; i < count; ++i) {
1182 *roots[i] = ImageAddress(*roots[i]);
1183 }
1184 }
1185
1186 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1187 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001188 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001189 for (size_t i = 0; i < count; ++i) {
1190 roots[i]->Assign(ImageAddress(roots[i]->AsMirrorPtr()));
1191 }
1192 }
1193
1194 private:
1195 ImageWriter* const image_writer_;
1196
Mathieu Chartier90443472015-07-16 20:32:27 -07001197 mirror::Object* ImageAddress(mirror::Object* obj) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001198 const size_t offset = image_writer_->GetImageOffset(obj);
1199 auto* const dest = reinterpret_cast<Object*>(image_writer_->image_begin_ + offset);
1200 VLOG(compiler) << "Update root from " << obj << " to " << dest;
1201 return dest;
1202 }
1203};
1204
Mathieu Chartierc7853442015-03-27 14:35:38 -07001205void ImageWriter::CopyAndFixupNativeData() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001206 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001207 for (auto& pair : native_object_relocations_) {
1208 NativeObjectRelocation& relocation = pair.second;
1209 auto* dest = image_->Begin() + relocation.offset;
1210 DCHECK_GE(dest, image_->Begin() + image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001211 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001212 switch (relocation.type) {
1213 case kNativeObjectRelocationTypeArtField: {
1214 memcpy(dest, pair.first, sizeof(ArtField));
1215 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1216 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1217 break;
1218 }
1219 case kNativeObjectRelocationTypeArtMethodClean:
1220 case kNativeObjectRelocationTypeArtMethodDirty: {
1221 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
1222 reinterpret_cast<ArtMethod*>(dest));
1223 break;
1224 }
1225 // For arrays, copy just the header since the elements will get copied by their corresponding
1226 // relocations.
1227 case kNativeObjectRelocationTypeArtFieldArray: {
1228 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1229 break;
1230 }
1231 case kNativeObjectRelocationTypeArtMethodArrayClean:
1232 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001233 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1234 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001235 ArtMethod::Size(target_ptr_size_),
1236 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001237 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001238 case kNativeObjectRelocationTypeDexCacheArray:
1239 // Nothing to copy here, everything is done in FixupDexCache().
1240 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001241 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001242 }
1243 }
1244 // Fixup the image method roots.
1245 auto* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001246 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001247 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001248 ArtMethod* method = image_methods_[i];
1249 CHECK(method != nullptr);
1250 if (!IsInBootImage(method)) {
1251 auto it = native_object_relocations_.find(method);
1252 CHECK(it != native_object_relocations_.end()) << "No fowarding for " << PrettyMethod(method);
1253 NativeObjectRelocation& relocation = it->second;
1254 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1255 << methods_section;
1256 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
1257 method = reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
1258 }
1259 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001260 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001261 // Write the intern table into the image.
1262 const ImageSection& intern_table_section = image_header->GetImageSection(
1263 ImageHeader::kSectionInternedStrings);
1264 InternTable* const intern_table = Runtime::Current()->GetInternTable();
1265 uint8_t* const memory_ptr = image_->Begin() + intern_table_section.Offset();
1266 const size_t intern_table_bytes = intern_table->WriteToMemory(memory_ptr);
1267 // Fixup the pointers in the newly written intern table to contain image addresses.
1268 InternTable temp_table;
1269 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1270 // the VisitRoots() will update the memory directly rather than the copies.
1271 // This also relies on visit roots not doing any verification which could fail after we update
1272 // the roots to be the image addresses.
1273 temp_table.ReadFromMemory(memory_ptr);
1274 CHECK_EQ(temp_table.Size(), intern_table->Size());
1275 FixupRootVisitor visitor(this);
1276 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
1277 CHECK_EQ(intern_table_bytes, intern_table_bytes_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001278}
1279
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001280void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001281 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001282 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1283 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001284 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001285 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001286 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1287 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001288 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001289 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001290}
1291
Mathieu Chartier590fee92013-09-13 13:46:47 -07001292void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001293 DCHECK(obj != nullptr);
1294 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001295 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1296}
1297
Mathieu Chartiere401d142015-04-22 13:56:20 -07001298void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1299 mirror::Class* klass, Bin array_type) {
1300 CHECK(klass->IsArrayClass());
1301 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1302 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001303 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001304 dst->SetClass(GetImageAddress(arr->GetClass()));
1305 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001306 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001307 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1308 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001309 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001310 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001311 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001312 auto* method = reinterpret_cast<ArtMethod*>(elem);
1313 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1314 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1315 << PrettyClass(method->GetDeclaringClass());
1316 } else {
1317 CHECK_EQ(array_type, kBinArtField);
1318 auto* field = reinterpret_cast<ArtField*>(elem);
1319 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1320 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1321 << PrettyClass(field->GetDeclaringClass());
1322 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001323 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001324 } else {
1325 elem = image_begin_ + it->second.offset;
1326 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001327 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001328 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001329 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001330}
1331
1332void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001333 if (IsInBootImage(obj)) {
1334 return;
1335 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001336 size_t offset = GetImageOffset(obj);
1337 auto* dst = reinterpret_cast<Object*>(image_->Begin() + offset);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001338 DCHECK_LT(offset, image_end_);
1339 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001340
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001341 image_bitmap_->Set(dst); // Mark the obj as live.
1342
1343 const size_t n = obj->SizeOf();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001344 DCHECK_LE(offset + n, image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001345 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001346
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001347 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1348 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001349 const auto it = saved_hashcode_map_.find(obj);
1350 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1351 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001352 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001353}
1354
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001355// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001356class FixupVisitor {
1357 public:
1358 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1359 }
1360
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001361 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1362 // with other logic.
1363 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1364 const {}
1365 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1366
1367
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001368 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001369 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001370 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001371 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1372 // image.
1373 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001374 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001375 }
1376
1377 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001378 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001379 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001380 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001381 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001382 }
1383
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001384 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001385 ImageWriter* const image_writer_;
1386 mirror::Object* const copy_;
1387};
1388
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001389class FixupClassVisitor FINAL : public FixupVisitor {
1390 public:
1391 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1392 }
1393
Mathieu Chartierc7853442015-03-27 14:35:38 -07001394 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001395 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001396 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001397 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001398 }
1399
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001400 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1401 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001402 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001403 LOG(FATAL) << "Reference not expected here.";
1404 }
1405};
1406
Vladimir Marko05792b92015-08-03 11:56:49 +01001407uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1408 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001409 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001410 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001411 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1412 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001413 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001414 return relocation.offset;
1415}
1416
1417template <typename T>
1418T* ImageWriter::NativeLocationInImage(T* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001419 return (obj == nullptr || IsInBootImage(obj))
1420 ? obj
1421 : reinterpret_cast<T*>(image_begin_ + NativeOffsetInImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001422}
1423
Mathieu Chartierc7853442015-03-27 14:35:38 -07001424void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001425 // Update the field arrays.
Vladimir Marko05792b92015-08-03 11:56:49 +01001426 copy->SetSFieldsPtrUnchecked(NativeLocationInImage(orig->GetSFieldsPtr()));
1427 copy->SetIFieldsPtrUnchecked(NativeLocationInImage(orig->GetIFieldsPtr()));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001428 // Update direct and virtual method arrays.
Vladimir Marko05792b92015-08-03 11:56:49 +01001429 copy->SetDirectMethodsPtrUnchecked(NativeLocationInImage(orig->GetDirectMethodsPtr()));
1430 copy->SetVirtualMethodsPtr(NativeLocationInImage(orig->GetVirtualMethodsPtr()));
1431 // Update dex cache strings.
1432 copy->SetDexCacheStrings(NativeLocationInImage(orig->GetDexCacheStrings()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001433 // Fix up embedded tables.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001434 if (!orig->IsTemp()) {
1435 // TODO: Why do we have temp classes in some cases?
1436 if (orig->ShouldHaveEmbeddedImtAndVTable()) {
1437 for (int32_t i = 0; i < orig->GetEmbeddedVTableLength(); ++i) {
1438 ArtMethod* orig_method = orig->GetEmbeddedVTableEntry(i, target_ptr_size_);
1439 copy->SetEmbeddedVTableEntryUnchecked(
1440 i,
1441 NativeLocationInImage(orig_method),
1442 target_ptr_size_);
1443 }
1444 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
1445 copy->SetEmbeddedImTableEntry(
1446 i,
1447 NativeLocationInImage(orig->GetEmbeddedImTableEntry(i, target_ptr_size_)),
1448 target_ptr_size_);
1449 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001450 }
1451 }
1452 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001453 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001454}
1455
Ian Rogersef7d42f2014-01-06 12:55:46 -08001456void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001457 DCHECK(orig != nullptr);
1458 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001459 if (kUseBakerOrBrooksReadBarrier) {
1460 orig->AssertReadBarrierPointer();
1461 if (kUseBrooksReadBarrier) {
1462 // Note the address 'copy' isn't the same as the image address of 'orig'.
1463 copy->SetReadBarrierPointer(GetImageAddress(orig));
1464 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1465 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001466 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001467 auto* klass = orig->GetClass();
1468 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001469 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001470 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1471 if (it != pointer_arrays_.end()) {
1472 // Should only need to fixup every pointer array exactly once.
1473 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1474 pointer_arrays_.erase(it);
1475 return;
1476 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001477 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001478 if (orig->IsClass()) {
1479 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001480 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001481 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1482 // Need to go update the ArtMethod.
1483 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1484 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1485 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001486 auto it = native_object_relocations_.find(src_method);
1487 CHECK(it != native_object_relocations_.end())
1488 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001489 dest->SetArtMethod(
1490 reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001491 } else if (!klass->IsArrayClass()) {
1492 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1493 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1494 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
1495 } else if (klass->IsSubClass(down_cast<mirror::Class*>(
1496 class_linker->GetClassRoot(ClassLinker::kJavaLangClassLoader)))) {
1497 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1498 // ClassLoader.
1499 down_cast<mirror::ClassLoader*>(copy)->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001500 // Also set allocator to null to be safe. The allocator is created when we create the class
1501 // table. We also never expect to unload things in the image since they are held live as
1502 // roots.
1503 down_cast<mirror::ClassLoader*>(copy)->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001504 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001505 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001506 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001507 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001508 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001509}
1510
Vladimir Marko05792b92015-08-03 11:56:49 +01001511void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1512 mirror::DexCache* copy_dex_cache) {
1513 // Though the DexCache array fields are usually treated as native pointers, we set the full
1514 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1515 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1516 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1517 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1518 if (orig_strings != nullptr) {
1519 uintptr_t copy_strings_offset = NativeOffsetInImage(orig_strings);
1520 copy_dex_cache->SetField64<false>(
1521 mirror::DexCache::StringsOffset(),
1522 static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + copy_strings_offset)));
1523 GcRoot<mirror::String>* copy_strings =
1524 reinterpret_cast<GcRoot<mirror::String>*>(image_->Begin() + copy_strings_offset);
1525 for (size_t i = 0, num = orig_dex_cache->NumStrings(); i != num; ++i) {
1526 copy_strings[i] = GcRoot<mirror::String>(GetImageAddress(orig_strings[i].Read()));
1527 }
1528 }
1529 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1530 if (orig_types != nullptr) {
1531 uintptr_t copy_types_offset = NativeOffsetInImage(orig_types);
1532 copy_dex_cache->SetField64<false>(
1533 mirror::DexCache::ResolvedTypesOffset(),
1534 static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + copy_types_offset)));
1535 GcRoot<mirror::Class>* copy_types =
1536 reinterpret_cast<GcRoot<mirror::Class>*>(image_->Begin() + copy_types_offset);
1537 for (size_t i = 0, num = orig_dex_cache->NumResolvedTypes(); i != num; ++i) {
1538 copy_types[i] = GcRoot<mirror::Class>(GetImageAddress(orig_types[i].Read()));
1539 }
1540 }
1541 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1542 if (orig_methods != nullptr) {
1543 uintptr_t copy_methods_offset = NativeOffsetInImage(orig_methods);
1544 copy_dex_cache->SetField64<false>(
1545 mirror::DexCache::ResolvedMethodsOffset(),
1546 static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + copy_methods_offset)));
1547 ArtMethod** copy_methods =
1548 reinterpret_cast<ArtMethod**>(image_->Begin() + copy_methods_offset);
1549 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1550 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001551 ArtMethod* copy = IsInBootImage(orig) ? orig : NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001552 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1553 }
1554 }
1555 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1556 if (orig_fields != nullptr) {
1557 uintptr_t copy_fields_offset = NativeOffsetInImage(orig_fields);
1558 copy_dex_cache->SetField64<false>(
1559 mirror::DexCache::ResolvedFieldsOffset(),
1560 static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + copy_fields_offset)));
1561 ArtField** copy_fields = reinterpret_cast<ArtField**>(image_->Begin() + copy_fields_offset);
1562 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1563 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001564 ArtField* copy = IsInBootImage(orig) ? orig : NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001565 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1566 }
1567 }
1568}
1569
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001570const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1571 DCHECK_LT(type, kOatAddressCount);
1572 // If we are compiling an app image, we need to use the stubs of the boot image.
1573 if (compile_app_image_) {
1574 // Use the current image pointers.
1575 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1576 DCHECK(image_space != nullptr);
1577 const OatFile* oat_file = image_space->GetOatFile();
1578 CHECK(oat_file != nullptr);
1579 const OatHeader& header = oat_file->GetOatHeader();
1580 switch (type) {
1581 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1582 case kOatAddressQuickGenericJNITrampoline:
1583 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1584 case kOatAddressInterpreterToInterpreterBridge:
1585 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1586 case kOatAddressInterpreterToCompiledCodeBridge:
1587 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1588 case kOatAddressJNIDlsymLookup:
1589 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1590 case kOatAddressQuickIMTConflictTrampoline:
1591 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1592 case kOatAddressQuickResolutionTrampoline:
1593 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1594 case kOatAddressQuickToInterpreterBridge:
1595 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1596 default:
1597 UNREACHABLE();
1598 }
1599 }
1600 return GetOatAddressForOffset(oat_address_offsets_[type]);
1601}
1602
Mathieu Chartiere401d142015-04-22 13:56:20 -07001603const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method, bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001604 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
1605 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
1606 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
1607 DCHECK(!method->IsAbstract()) << PrettyMethod(method);
1608 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001609
1610 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1611 // trampoline.
1612
1613 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001614 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1615 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001616 const uint8_t* quick_code = GetOatAddressForOffset(quick_oat_code_offset);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001617 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001618 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
1619 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001620 // We have code for a non-static or initialized method, just use the code.
1621 } else if (quick_code == nullptr && method->IsNative() &&
1622 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1623 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001624 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001625 } else if (quick_code == nullptr && !method->IsNative()) {
1626 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001627 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001628 *quick_is_interpreted = true;
1629 } else {
1630 CHECK(!method->GetDeclaringClass()->IsInitialized());
1631 // We have code for a static method, but need to go through the resolution stub for class
1632 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001633 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
1634 }
1635 if (!IsInBootOatFile(quick_code)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001636 DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001637 }
1638 return quick_code;
1639}
1640
Mathieu Chartiere401d142015-04-22 13:56:20 -07001641const uint8_t* ImageWriter::GetQuickEntryPoint(ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001642 // Calculate the quick entry point following the same logic as FixupMethod() below.
1643 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001644 Runtime* runtime = Runtime::Current();
1645 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001646 return GetOatAddress(kOatAddressQuickResolutionTrampoline);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001647 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
1648 method == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001649 return GetOatAddress(kOatAddressQuickIMTConflictTrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001650 } else {
1651 // We assume all methods have code. If they don't currently then we set them to the use the
1652 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1653 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1654 if (UNLIKELY(method->IsAbstract())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001655 return GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001656 } else {
1657 bool quick_is_interpreted;
1658 return GetQuickCode(method, &quick_is_interpreted);
1659 }
1660 }
1661}
1662
Mathieu Chartiere401d142015-04-22 13:56:20 -07001663void ImageWriter::CopyAndFixupMethod(ArtMethod* orig, ArtMethod* copy) {
Vladimir Marko14632852015-08-17 12:07:23 +01001664 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001665
1666 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01001667
1668 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
1669 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
1670 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
1671 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001672
Ian Rogers848871b2013-08-05 10:56:33 -07001673 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1674 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07001675
Ian Rogers848871b2013-08-05 10:56:33 -07001676 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001677 Runtime* runtime = Runtime::Current();
1678 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001679 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001680 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001681 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1682 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001683 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001684 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001685 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
1686 bool found_one = false;
1687 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
1688 auto idx = static_cast<Runtime::CalleeSaveType>(i);
1689 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
1690 found_one = true;
1691 break;
1692 }
1693 }
1694 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
1695 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001696 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001697 // We assume all methods have code. If they don't currently then we set them to the use the
1698 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1699 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1700 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001701 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001702 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001703 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001704 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -07001705 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001706 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001707
Sebastien Hertze1d07812014-05-21 15:44:09 +02001708 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001709 if (orig->IsNative()) {
1710 // The native method's pointer is set to a stub to lookup via dlsym.
1711 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001712 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001713 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001714 }
1715 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001716 }
1717}
1718
Alex Lighta59dd802014-07-02 16:28:08 -07001719static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001720 uint64_t data_sec_offset;
1721 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1722 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001723 return nullptr;
1724 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001725 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001726}
1727
Vladimir Markof4da6752014-08-01 19:04:18 +01001728void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001729 std::string error_msg;
1730 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
1731 MAP_SHARED, &error_msg));
1732 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001733 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001734 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001735 }
Alex Lighta59dd802014-07-02 16:28:08 -07001736 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1737 CHECK(oat_header != nullptr);
1738 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001739
Brian Carlstrom7940e442013-07-12 13:46:57 -07001740 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001741 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001742}
1743
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001744size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1745 DCHECK_LE(up_to, kBinSize);
1746 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1747}
1748
1749ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1750 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07001751 static_assert(kBinBits == 3, "wrong number of bin bits");
1752 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001753 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1754
1755 DCHECK_LT(GetBin(), kBinSize);
1756 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1757}
1758
1759ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1760 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1761 DCHECK_EQ(index, GetIndex());
1762}
1763
1764ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1765 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1766}
1767
1768uint32_t ImageWriter::BinSlot::GetIndex() const {
1769 return lockword_ & ~kBinMask;
1770}
1771
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001772uint8_t* ImageWriter::GetOatFileBegin() const {
1773 DCHECK_GT(intern_table_bytes_, 0u);
Vladimir Marko05792b92015-08-03 11:56:49 +01001774 size_t native_sections_size =
1775 bin_slot_sizes_[kBinArtField] + bin_slot_sizes_[kBinArtMethodDirty] +
1776 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinDexCacheArray] +
1777 intern_table_bytes_;
1778 return image_begin_ + RoundUp(image_end_ + native_sections_size, kPageSize);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001779}
1780
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001781ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
1782 switch (type) {
1783 case kNativeObjectRelocationTypeArtField:
1784 case kNativeObjectRelocationTypeArtFieldArray:
1785 return kBinArtField;
1786 case kNativeObjectRelocationTypeArtMethodClean:
1787 case kNativeObjectRelocationTypeArtMethodArrayClean:
1788 return kBinArtMethodClean;
1789 case kNativeObjectRelocationTypeArtMethodDirty:
1790 case kNativeObjectRelocationTypeArtMethodArrayDirty:
1791 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01001792 case kNativeObjectRelocationTypeDexCacheArray:
1793 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001794 }
1795 UNREACHABLE();
1796}
1797
Brian Carlstrom7940e442013-07-12 13:46:57 -07001798} // namespace art