blob: 341742e4dc60bced793f5654c2f01ea80bc50a7e [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "image_writer.h"
18
19#include <sys/stat.h>
20
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Vladimir Marko20f85592015-03-19 10:07:02 +000022#include <numeric>
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080023#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070024#include <vector>
25
Mathieu Chartierc7853442015-03-27 14:35:38 -070026#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070027#include "art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070028#include "base/logging.h"
29#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010030#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070031#include "compiled_method.h"
32#include "dex_file-inl.h"
33#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070034#include "elf_file.h"
35#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070036#include "elf_writer.h"
37#include "gc/accounting/card_table-inl.h"
38#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070039#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070040#include "gc/heap.h"
41#include "gc/space/large_object_space.h"
42#include "gc/space/space-inl.h"
43#include "globals.h"
44#include "image.h"
45#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070046#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070047#include "lock_word.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070048#include "mirror/abstract_method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "mirror/array-inl.h"
50#include "mirror/class-inl.h"
51#include "mirror/class_loader.h"
52#include "mirror/dex_cache-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070053#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "mirror/object-inl.h"
55#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070056#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070057#include "oat.h"
58#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070059#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "runtime.h"
61#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070062#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000063#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070065using ::art::mirror::Class;
66using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070067using ::art::mirror::Object;
68using ::art::mirror::ObjectArray;
69using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070070
71namespace art {
72
Igor Murashkinf5b4c502014-11-14 15:01:59 -080073// Separate objects into multiple bins to optimize dirty memory use.
74static constexpr bool kBinObjects = true;
75
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080076// Return true if an object is already in an image space.
77bool ImageWriter::IsInBootImage(const void* obj) const {
78 if (!compile_app_image_) {
79 DCHECK(boot_image_space_ == nullptr);
80 return false;
81 }
82 const uint8_t* image_begin = boot_image_space_->Begin();
83 // Real image end including ArtMethods and ArtField sections.
84 const uint8_t* image_end = image_begin + boot_image_space_->GetImageHeader().GetImageSize();
85 return image_begin <= obj && obj < image_end;
86}
87
88bool ImageWriter::IsInBootOatFile(const void* ptr) const {
89 if (!compile_app_image_) {
90 DCHECK(boot_image_space_ == nullptr);
91 return false;
92 }
93 const ImageHeader& image_header = boot_image_space_->GetImageHeader();
94 return image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd();
95}
96
Andreas Gampedd9d0552015-03-09 12:57:41 -070097static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -070098 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -070099 Class* klass = obj->GetClass();
100 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
101}
102
103static void CheckNoDexObjects() {
104 ScopedObjectAccess soa(Thread::Current());
105 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
106}
107
Vladimir Markof4da6752014-08-01 19:04:18 +0100108bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800109 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800110 gc::Heap* const heap = Runtime::Current()->GetHeap();
111 // Cache boot image space.
112 for (gc::space::ContinuousSpace* space : heap->GetContinuousSpaces()) {
113 if (space->IsImageSpace()) {
114 CHECK(compile_app_image_);
115 CHECK(boot_image_space_ == nullptr) << "Multiple image spaces";
116 boot_image_space_ = space->AsImageSpace();
117 }
118 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100119 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700120 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100121 PruneNonImageClasses(); // Remove junk
122 ComputeLazyFieldsForImageClasses(); // Add useful information
Vladimir Markof4da6752014-08-01 19:04:18 +0100123 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100124 heap->CollectGarbage(false); // Remove garbage.
125
Andreas Gampedd9d0552015-03-09 12:57:41 -0700126 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
127 // dex files.
128 //
129 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
130 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
131 // true.
132 if (kIsDebugBuild) {
133 CheckNoDexObjects();
134 }
135
Vladimir Markof4da6752014-08-01 19:04:18 +0100136 if (kIsDebugBuild) {
137 ScopedObjectAccess soa(Thread::Current());
138 CheckNonImageClassesRemoved();
139 }
140
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700141 {
142 ScopedObjectAccess soa(Thread::Current());
143 CalculateNewObjectOffsets();
144 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100145
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700146 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
147 // bin size sums being calculated.
148 if (!AllocMemory()) {
149 return false;
150 }
151
Vladimir Markof4da6752014-08-01 19:04:18 +0100152 return true;
153}
154
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700155bool ImageWriter::Write(int image_fd,
156 const std::string& image_filename,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700157 const std::string& oat_filename,
158 const std::string& oat_location) {
159 CHECK(!image_filename.empty());
160
Ian Rogers700a4022014-05-19 16:49:03 -0700161 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700162 if (oat_file.get() == nullptr) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800163 PLOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700164 return false;
165 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700166 std::string error_msg;
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700167 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, nullptr, &error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700168 if (oat_file_ == nullptr) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800169 PLOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700170 << ": " << error_msg;
Andreas Gampe0b7fcf92015-03-13 16:54:54 -0700171 oat_file->Erase();
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700172 return false;
173 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700174 Runtime::Current()->GetOatFileManager().RegisterOatFile(
175 std::unique_ptr<const OatFile>(oat_file_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700176
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800177 const OatHeader& oat_header = oat_file_->GetOatHeader();
178 oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
179 oat_header.GetInterpreterToInterpreterBridgeOffset();
180 oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
181 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
182 oat_address_offsets_[kOatAddressJNIDlsymLookup] =
183 oat_header.GetJniDlsymLookupOffset();
184 oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
185 oat_header.GetQuickGenericJniTrampolineOffset();
186 oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
187 oat_header.GetQuickImtConflictTrampolineOffset();
188 oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
189 oat_header.GetQuickResolutionTrampolineOffset();
190 oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
191 oat_header.GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700192
Brian Carlstrom7940e442013-07-12 13:46:57 -0700193 size_t oat_loaded_size = 0;
194 size_t oat_data_offset = 0;
Vladimir Marko3fc99032015-05-13 19:06:30 +0100195 ElfWriter::GetOatElfInformation(oat_file.get(), &oat_loaded_size, &oat_data_offset);
Alex Light53cb16b2014-06-12 11:26:29 -0700196
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700197 {
198 ScopedObjectAccess soa(Thread::Current());
199 CreateHeader(oat_loaded_size, oat_data_offset);
200 CopyAndFixupNativeData();
201 // TODO: heap validation can't handle these fix up passes.
202 Runtime::Current()->GetHeap()->DisableObjectValidation();
203 CopyAndFixupObjects();
204 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700205
Vladimir Markof4da6752014-08-01 19:04:18 +0100206 SetOatChecksumFromElfFile(oat_file.get());
207
Andreas Gampe4303ba92014-11-06 01:00:46 -0800208 if (oat_file->FlushCloseOrErase() != 0) {
209 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename << " for " << oat_location;
210 return false;
211 }
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700212 std::unique_ptr<File> image_file;
213 if (image_fd != kInvalidImageFd) {
214 image_file.reset(new File(image_fd, image_filename, unix_file::kCheckSafeUsage));
215 } else {
216 image_file.reset(OS::CreateEmptyFile(image_filename.c_str()));
217 }
218 if (image_file == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700219 LOG(ERROR) << "Failed to open image file " << image_filename;
220 return false;
221 }
222 if (fchmod(image_file->Fd(), 0644) != 0) {
223 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800224 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700225 return EXIT_FAILURE;
226 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700227
Mathieu Chartiere401d142015-04-22 13:56:20 -0700228 // Write out the image + fields + methods.
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700229 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700230 const auto write_count = image_header->GetImageSize();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700231 if (!image_file->WriteFully(image_->Begin(), write_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700232 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800233 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700234 return false;
235 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700236
237 // Write out the image bitmap at the page aligned start of the image end.
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700238 const ImageSection& bitmap_section = image_header->GetImageSection(
239 ImageHeader::kSectionImageBitmap);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700240 CHECK_ALIGNED(bitmap_section.Offset(), kPageSize);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700241 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700242 bitmap_section.Size(), bitmap_section.Offset())) {
Mathieu Chartier31e89252013-08-28 11:29:12 -0700243 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800244 image_file->Erase();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700245 return false;
246 }
247
Mathieu Chartiere401d142015-04-22 13:56:20 -0700248 CHECK_EQ(bitmap_section.End(), static_cast<size_t>(image_file->GetLength()));
Andreas Gampe4303ba92014-11-06 01:00:46 -0800249 if (image_file->FlushCloseOrErase() != 0) {
250 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
251 return false;
252 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700253 return true;
254}
255
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700256void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700257 DCHECK(object != nullptr);
258 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800259
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800260 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700261 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700262 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700263 DCHECK(IsImageOffsetAssigned(object));
264}
265
Mathieu Chartiere401d142015-04-22 13:56:20 -0700266void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
267 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
268 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
269 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
270}
271
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800272void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700273 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800274 DCHECK_NE(image_objects_offset_begin_, 0u);
275
Vladimir Markocf36d492015-08-12 19:27:26 +0100276 size_t bin_slot_offset = bin_slot_offsets_[bin_slot.GetBin()];
277 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800278 DCHECK_ALIGNED(new_offset, kObjectAlignment);
279
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700280 SetImageOffset(object, new_offset);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800281 DCHECK_LT(new_offset, image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700282}
283
Ian Rogersef7d42f2014-01-06 12:55:46 -0800284bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800285 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700286 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700287 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700288}
289
Ian Rogersef7d42f2014-01-06 12:55:46 -0800290size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700291 DCHECK(object != nullptr);
292 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700293 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700294 size_t offset = lock_word.ForwardingAddress();
295 DCHECK_LT(offset, image_end_);
296 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700297}
298
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800299void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
300 DCHECK(object != nullptr);
301 DCHECK(!IsImageOffsetAssigned(object));
302 DCHECK(!IsImageBinSlotAssigned(object));
303
304 // Before we stomp over the lock word, save the hash code for later.
305 Monitor::Deflate(Thread::Current(), object);;
306 LockWord lw(object->GetLockWord(false));
307 switch (lw.GetState()) {
308 case LockWord::kFatLocked: {
309 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
310 break;
311 }
312 case LockWord::kThinLocked: {
313 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
314 break;
315 }
316 case LockWord::kUnlocked:
317 // No hash, don't need to save it.
318 break;
319 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700320 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
321 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800322 break;
323 default:
324 LOG(FATAL) << "Unreachable.";
325 UNREACHABLE();
326 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700327 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700328 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800329 DCHECK(IsImageBinSlotAssigned(object));
330}
331
Vladimir Marko20f85592015-03-19 10:07:02 +0000332void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000333 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
334 uint32_t size = 0u;
335 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
336 dex_cache_array_starts_.Put(dex_file, size);
337 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
338 size += layout.Size();
339 }
340 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
341 // when AssignImageBinSlot() assigns their indexes out or order.
342 bin_slot_sizes_[kBinDexCacheArray] = size;
343
Vladimir Marko20f85592015-03-19 10:07:02 +0000344 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700345 Thread* const self = Thread::Current();
346 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800347 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700348 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800349 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800350 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700351 continue;
352 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000353 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700354 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000355 DCHECK(layout.Valid());
Vladimir Markof60c7e22015-11-23 18:05:08 +0000356 uint32_t start = dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100357 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Vladimir Markof60c7e22015-11-23 18:05:08 +0000358 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(), start + layout.TypesOffset());
Vladimir Marko05792b92015-08-03 11:56:49 +0100359 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Vladimir Markof60c7e22015-11-23 18:05:08 +0000360 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(), start + layout.MethodsOffset());
Vladimir Marko05792b92015-08-03 11:56:49 +0100361 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Vladimir Markof60c7e22015-11-23 18:05:08 +0000362 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(), start + layout.FieldsOffset());
Vladimir Marko05792b92015-08-03 11:56:49 +0100363 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Vladimir Markof60c7e22015-11-23 18:05:08 +0000364 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset());
Vladimir Marko20f85592015-03-19 10:07:02 +0000365 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000366}
367
Vladimir Marko05792b92015-08-03 11:56:49 +0100368void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset) {
369 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800370 DCHECK(!IsInBootImage(array));
Vladimir Marko05792b92015-08-03 11:56:49 +0100371 native_object_relocations_.emplace(
372 array,
373 NativeObjectRelocation { offset, kNativeObjectRelocationTypeDexCacheArray });
374 }
375}
376
Mathieu Chartiere401d142015-04-22 13:56:20 -0700377void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
378 DCHECK(arr != nullptr);
379 if (kIsDebugBuild) {
380 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800381 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700382 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800383 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800384 CHECK(klass == nullptr || KeepClass(klass))
385 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700386 }
387 }
388 }
389 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
390 // ArtMethods.
391 pointer_arrays_.emplace(arr, kBinArtMethodClean);
392}
393
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800394void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
395 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800396 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800397
398 // The magic happens here. We segregate objects into different bins based
399 // on how likely they are to get dirty at runtime.
400 //
401 // Likely-to-dirty objects get packed together into the same bin so that
402 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
403 // maximized.
404 //
405 // This means more pages will stay either clean or shared dirty (with zygote) and
406 // the app will use less of its own (private) memory.
407 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000408 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800409
410 if (kBinObjects) {
411 //
412 // Changing the bin of an object is purely a memory-use tuning.
413 // It has no change on runtime correctness.
414 //
415 // Memory analysis has determined that the following types of objects get dirtied
416 // the most:
417 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000418 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
419 // a fixed layout which helps improve generated code (using PC-relative addressing),
420 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
421 // Since these arrays are huge, most pages do not overlap other objects and it's not
422 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100423 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800424 // * Class'es which are verified [their clinit runs only at runtime]
425 // - classes in general [because their static fields get overwritten]
426 // - initialized classes with all-final statics are unlikely to be ever dirty,
427 // so bin them separately
428 // * Art Methods that are:
429 // - native [their native entry point is not looked up until runtime]
430 // - have declaring classes that aren't initialized
431 // [their interpreter/quick entry points are trampolines until the class
432 // becomes initialized]
433 //
434 // We also assume the following objects get dirtied either never or extremely rarely:
435 // * Strings (they are immutable)
436 // * Art methods that aren't native and have initialized declared classes
437 //
438 // We assume that "regular" bin objects are highly unlikely to become dirtied,
439 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
440 //
441 if (object->IsClass()) {
442 bin = kBinClassVerified;
443 mirror::Class* klass = object->AsClass();
444
Mathieu Chartiere401d142015-04-22 13:56:20 -0700445 // Add non-embedded vtable to the pointer array table if there is one.
446 auto* vtable = klass->GetVTable();
447 if (vtable != nullptr) {
448 AddMethodPointerArray(vtable);
449 }
450 auto* iftable = klass->GetIfTable();
451 if (iftable != nullptr) {
452 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
453 if (iftable->GetMethodArrayCount(i) > 0) {
454 AddMethodPointerArray(iftable->GetMethodArray(i));
455 }
456 }
457 }
458
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800459 if (klass->GetStatus() == Class::kStatusInitialized) {
460 bin = kBinClassInitialized;
461
462 // If the class's static fields are all final, put it into a separate bin
463 // since it's very likely it will stay clean.
464 uint32_t num_static_fields = klass->NumStaticFields();
465 if (num_static_fields == 0) {
466 bin = kBinClassInitializedFinalStatics;
467 } else {
468 // Maybe all the statics are final?
469 bool all_final = true;
470 for (uint32_t i = 0; i < num_static_fields; ++i) {
471 ArtField* field = klass->GetStaticField(i);
472 if (!field->IsFinal()) {
473 all_final = false;
474 break;
475 }
476 }
477
478 if (all_final) {
479 bin = kBinClassInitializedFinalStatics;
480 }
481 }
482 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800483 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
484 bin = kBinString; // Strings are almost always immutable (except for object header).
485 } // else bin = kBinRegular
486 }
487
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800488 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Vladimir Marko05792b92015-08-03 11:56:49 +0100489 current_offset = bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
490 // Move the current bin size up to accomodate the object we just assigned a bin slot.
491 bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800492
493 BinSlot new_bin_slot(bin, current_offset);
494 SetImageBinSlot(object, new_bin_slot);
495
496 ++bin_slot_count_[bin];
497
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800498 // Grow the image closer to the end by the object we just assigned.
499 image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800500}
501
Mathieu Chartiere401d142015-04-22 13:56:20 -0700502bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
503 if (m->IsNative()) {
504 return true;
505 }
506 mirror::Class* declaring_class = m->GetDeclaringClass();
507 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
508 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
509}
510
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800511bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
512 DCHECK(object != nullptr);
513
514 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
515 // If it's in some other state, then we haven't yet assigned an image bin slot.
516 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
517 return false;
518 } else if (kIsDebugBuild) {
519 LockWord lock_word = object->GetLockWord(false);
520 size_t offset = lock_word.ForwardingAddress();
521 BinSlot bin_slot(offset);
522 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800523 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800524 }
525 return true;
526}
527
528ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
529 DCHECK(object != nullptr);
530 DCHECK(IsImageBinSlotAssigned(object));
531
532 LockWord lock_word = object->GetLockWord(false);
533 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
534 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
535
536 BinSlot bin_slot(static_cast<uint32_t>(offset));
537 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()]);
538
539 return bin_slot;
540}
541
Brian Carlstrom7940e442013-07-12 13:46:57 -0700542bool ImageWriter::AllocMemory() {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700543 const size_t length = RoundUp(image_objects_offset_begin_ + GetBinSizeSum() + intern_table_bytes_,
544 kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700545 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800546 image_.reset(MemMap::MapAnonymous("image writer image",
547 nullptr,
548 length,
549 PROT_READ | PROT_WRITE,
550 false,
551 false,
552 &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700553 if (UNLIKELY(image_.get() == nullptr)) {
554 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700555 return false;
556 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700557
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700558 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
559 CHECK_LE(image_end_, length);
560 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800561 "image bitmap",
562 image_->Begin(),
563 RoundUp(image_end_, kPageSize)));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700564 if (image_bitmap_.get() == nullptr) {
565 LOG(ERROR) << "Failed to allocate memory for image bitmap";
566 return false;
567 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700568 return true;
569}
570
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700571class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
572 public:
573 bool Visit(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
574 StackHandleScope<1> hs(Thread::Current());
575 mirror::Class::ComputeName(hs.NewHandle(c));
576 return true;
577 }
578};
579
Brian Carlstrom7940e442013-07-12 13:46:57 -0700580void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700581 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700582 ComputeLazyFieldsForClassesVisitor visitor;
583 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700584}
585
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800586static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
587 return klass->GetClassLoader() == nullptr;
588}
589
590bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
591 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
592}
593
594bool ImageWriter::ContainsBootClassLoaderNonImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800595 bool early_exit = false;
596 std::unordered_set<mirror::Class*> visited;
597 return ContainsBootClassLoaderNonImageClassInternal(klass, &early_exit, &visited);
598}
599
600bool ImageWriter::ContainsBootClassLoaderNonImageClassInternal(
601 mirror::Class* klass,
602 bool* early_exit,
603 std::unordered_set<mirror::Class*>* visited) {
604 DCHECK(early_exit != nullptr);
605 DCHECK(visited != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700606 if (klass == nullptr) {
607 return false;
608 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800609 auto found = prune_class_memo_.find(klass);
610 if (found != prune_class_memo_.end()) {
611 // Already computed, return the found value.
612 return found->second;
613 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800614 // Circular dependencies, return false but do not store the result in the memoization table.
615 if (visited->find(klass) != visited->end()) {
616 *early_exit = true;
617 return false;
618 }
619 visited->emplace(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800620 bool result = IsBootClassLoaderNonImageClass(klass);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800621 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800622 if (!result) {
623 // Check interfaces since these wont be visited through VisitReferences.)
624 mirror::IfTable* if_table = klass->GetIfTable();
625 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800626 result = result || ContainsBootClassLoaderNonImageClassInternal(
627 if_table->GetInterface(i),
628 &my_early_exit,
629 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800630 }
631 }
632 // Check static fields and their classes.
633 size_t num_static_fields = klass->NumReferenceStaticFields();
634 if (num_static_fields != 0 && klass->IsResolved()) {
635 // Presumably GC can happen when we are cross compiling, it should not cause performance
636 // problems to do pointer size logic.
637 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
638 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
639 for (size_t i = 0u; i < num_static_fields; ++i) {
640 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
641 if (ref != nullptr) {
642 if (ref->IsClass()) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800643 result = result ||
644 ContainsBootClassLoaderNonImageClassInternal(
645 ref->AsClass(),
646 &my_early_exit,
647 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800648 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800649 result = result ||
650 ContainsBootClassLoaderNonImageClassInternal(
651 ref->GetClass(),
652 &my_early_exit,
653 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800654 }
655 field_offset = MemberOffset(field_offset.Uint32Value() +
656 sizeof(mirror::HeapReference<mirror::Object>));
657 }
658 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800659 result = result ||
660 ContainsBootClassLoaderNonImageClassInternal(
661 klass->GetSuperClass(),
662 &my_early_exit,
663 visited);
664 // Erase the element we stored earlier since we are exiting the function.
665 auto it = visited->find(klass);
666 DCHECK(it != visited->end());
667 visited->erase(it);
668 // Only store result if it is true or none of the calls early exited due to circular
669 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
670 // a child call and we can remember the result.
671 if (result == true || !my_early_exit || visited->empty()) {
672 prune_class_memo_[klass] = result;
673 }
674 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800675 return result;
676}
677
678bool ImageWriter::KeepClass(Class* klass) {
679 if (klass == nullptr) {
680 return false;
681 }
682 if (compile_app_image_) {
683 // For app images, we need to prune boot loader classes that are not in the boot image since
684 // these may have already been loaded when the app image is loaded.
685 return !ContainsBootClassLoaderNonImageClass(klass);
686 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700687 std::string temp;
688 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700689}
690
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700691class NonImageClassesVisitor : public ClassVisitor {
692 public:
693 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
694
695 bool Visit(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800696 if (!image_writer_->KeepClass(klass)) {
697 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700698 }
699 return true;
700 }
701
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800702 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700703 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700704};
705
706void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700707 Runtime* runtime = Runtime::Current();
708 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700709 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700710
711 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700712 NonImageClassesVisitor visitor(this);
713 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700714
715 // Remove the undesired classes from the class roots.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800716 for (mirror::Class* klass : visitor.classes_to_prune_) {
717 std::string temp;
718 const char* name = klass->GetDescriptor(&temp);
719 VLOG(compiler) << "Pruning class " << name;
720 if (!compile_app_image_) {
721 DCHECK(IsBootClassLoaderClass(klass));
722 }
723 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800724 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700725 }
726
727 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100728 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700729
730 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
731 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
732 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800733 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
734 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700735 if (dex_cache == nullptr) {
736 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700737 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700738 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
739 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800740 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700741 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700742 }
743 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100744 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
745 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
746 ArtMethod* method =
747 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700748 if (method != nullptr) {
749 auto* declaring_class = method->GetDeclaringClass();
750 // Miranda methods may be held live by a class which was not an image class but have a
751 // declaring class which is an image class. Set it to the resolution method to be safe and
752 // prevent dangling pointers.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800753 if (method->IsMiranda() || !KeepClass(declaring_class)) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100754 mirror::DexCache::SetElementPtrSize(resolved_methods,
755 i,
756 resolution_method,
757 target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700758 } else {
759 // Check that the class is still in the classes table.
760 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
761 << PrettyClass(declaring_class) << " not in class linker table";
762 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700763 }
764 }
765 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700766 ArtField* field = dex_cache->GetResolvedField(i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800767 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700768 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700769 }
770 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700771 // Clean the dex field. It might have been populated during the initialization phase, but
772 // contains data only valid during a real run.
773 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700774 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700775
776 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
777 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800778
779 // Clear to save RAM.
780 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700781}
782
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800783void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700784 if (compiler_driver_.GetImageClasses() != nullptr) {
785 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700786 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700787 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700788}
789
790void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
791 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800792 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700793 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800794 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700795 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700796 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800797 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
798 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700799 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700800 }
801}
802
803void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700804 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700805 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700806 for (const std::string& image_class : *image_classes) {
807 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700808 }
809}
810
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800811void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700812 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700813 // if it is a string, we want to intern it if its not interned.
814 if (obj->GetClass()->IsStringClass()) {
815 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800816 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700817 DCHECK_EQ(obj, obj->AsString()->Intern());
818 return;
819 }
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700820 // InternImageString allows us to intern while holding the heap bitmap lock. This is safe since
821 // we are guaranteed to not have GC during image writing.
Mathieu Chartier90ef3db2015-08-04 15:19:41 -0700822 mirror::String* const interned = Runtime::Current()->GetInternTable()->InternStrongImageString(
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700823 obj->AsString());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700824 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800825 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700826 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800827 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700828 }
829 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800830 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700831 return;
832 }
833 // else (obj == interned), nothing to do but fall through to the normal case
834 }
835
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800836 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700837}
838
839ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
840 Runtime* runtime = Runtime::Current();
841 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700842 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700843 StackHandleScope<3> hs(self);
844 Handle<Class> object_array_class(hs.NewHandle(
845 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700846
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700847 // build an Object[] of all the DexCaches used in the source_space_.
848 // Since we can't hold the dex lock when allocating the dex_caches
849 // ObjectArray, we lock the dex lock twice, first to get the number
850 // of dex caches first and then lock it again to copy the dex
851 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800852 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700853 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700854 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800855 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800856 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
857 mirror::DexCache* dex_cache =
858 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800859 dex_cache_count += IsInBootImage(dex_cache) ? 0u : 1u;
860 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700861 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700862 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800863 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700864 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
865 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700866 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800867 size_t non_image_dex_caches = 0;
868 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800869 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
870 mirror::DexCache* dex_cache =
871 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800872 non_image_dex_caches += IsInBootImage(dex_cache) ? 0u : 1u;
873 }
874 CHECK_EQ(dex_cache_count, non_image_dex_caches)
875 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700876 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800877 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
878 mirror::DexCache* dex_cache =
879 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800880 if (!IsInBootImage(dex_cache)) {
881 dex_caches->Set<false>(i, dex_cache);
882 ++i;
883 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700884 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700885 }
886
887 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -0700888 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700889 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700890 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100891 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700892 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700893 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700894 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700895 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700896}
897
Mathieu Chartier590fee92013-09-13 13:46:47 -0700898// Walk instance fields of the given Class. Separate function to allow recursion on the super
899// class.
900void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
901 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700902 StackHandleScope<1> hs(Thread::Current());
903 Handle<mirror::Class> h_class(hs.NewHandle(klass));
904 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700905 if (super != nullptr) {
906 WalkInstanceFields(obj, super);
907 }
908 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700909 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000910 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700911 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700912 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700913 if (value != nullptr) {
914 WalkFieldsInOrder(value);
915 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000916 field_offset = MemberOffset(field_offset.Uint32Value() +
917 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700918 }
919}
920
921// For an unvisited object, visit it then all its children found via fields.
922void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800923 if (IsInBootImage(obj)) {
924 // Object is in the image, don't need to fix it up.
925 return;
926 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800927 // Use our own visitor routine (instead of GC visitor) to get better locality between
928 // an object and its fields
929 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700930 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700931 StackHandleScope<2> hs(Thread::Current());
932 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
933 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700934 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800935 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700936 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700937 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700938 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700939 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700940 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700941 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700942 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700943 if (value != nullptr) {
944 WalkFieldsInOrder(value);
945 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000946 field_offset = MemberOffset(field_offset.Uint32Value() +
947 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700948 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700949 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700950 auto* as_klass = h_obj->AsClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700951 LengthPrefixedArray<ArtField>* fields[] = {
952 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
953 };
954 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
955 // Total array length including header.
956 if (cur_fields != nullptr) {
957 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
958 // Forward the entire array at once.
959 auto it = native_object_relocations_.find(cur_fields);
960 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
961 << " already forwarded";
962 size_t& offset = bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800963 DCHECK(!IsInBootImage(cur_fields));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700964 native_object_relocations_.emplace(
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800965 cur_fields,
966 NativeObjectRelocation {offset, kNativeObjectRelocationTypeArtFieldArray });
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700967 offset += header_size;
968 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +0100969 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700970 // Need to forward arrays separate of fields.
971 ArtField* field = &cur_fields->At(i);
972 auto it2 = native_object_relocations_.find(field);
973 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
974 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800975 DCHECK(!IsInBootImage(field));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700976 native_object_relocations_.emplace(
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800977 field,
978 NativeObjectRelocation {offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700979 offset += sizeof(ArtField);
980 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700981 }
982 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700983 // Visit and assign offsets for methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700984 LengthPrefixedArray<ArtMethod>* method_arrays[] = {
985 as_klass->GetDirectMethodsPtr(), as_klass->GetVirtualMethodsPtr(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700986 };
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700987 for (LengthPrefixedArray<ArtMethod>* array : method_arrays) {
988 if (array == nullptr) {
989 continue;
990 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700991 bool any_dirty = false;
992 size_t count = 0;
Vladimir Marko14632852015-08-17 12:07:23 +0100993 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
994 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +0100995 auto iteration_range =
996 MakeIterationRangeFromLengthPrefixedArray(array, method_size, method_alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700997 for (auto& m : iteration_range) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700998 any_dirty = any_dirty || WillMethodBeDirty(&m);
999 ++count;
1000 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001001 NativeObjectRelocationType type = any_dirty
1002 ? kNativeObjectRelocationTypeArtMethodDirty
1003 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001004 Bin bin_type = BinTypeForNativeRelocationType(type);
1005 // Forward the entire array at once, but header first.
Vladimir Markocf36d492015-08-12 19:27:26 +01001006 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1007 method_size,
1008 method_alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001009 auto it = native_object_relocations_.find(array);
1010 CHECK(it == native_object_relocations_.end()) << "Method array " << array
1011 << " already forwarded";
1012 size_t& offset = bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001013 DCHECK(!IsInBootImage(array));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001014 native_object_relocations_.emplace(array, NativeObjectRelocation { offset,
1015 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty :
1016 kNativeObjectRelocationTypeArtMethodArrayClean });
1017 offset += header_size;
1018 for (auto& m : iteration_range) {
1019 AssignMethodOffset(&m, type);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001020 }
1021 (any_dirty ? dirty_methods_ : clean_methods_) += count;
1022 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001023 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001024 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001025 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001026 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001027 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001028 mirror::Object* value = obj_array->Get(i);
1029 if (value != nullptr) {
1030 WalkFieldsInOrder(value);
1031 }
1032 }
1033 }
1034 }
1035}
1036
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001037void ImageWriter::AssignMethodOffset(ArtMethod* method, NativeObjectRelocationType type) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001038 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001039 auto it = native_object_relocations_.find(method);
1040 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001041 << PrettyMethod(method);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001042 size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
1043 native_object_relocations_.emplace(method, NativeObjectRelocation { offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001044 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001045}
1046
Mathieu Chartier590fee92013-09-13 13:46:47 -07001047void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1048 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1049 DCHECK(writer != nullptr);
1050 writer->WalkFieldsInOrder(obj);
1051}
1052
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001053void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1054 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1055 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001056 if (!writer->IsInBootImage(obj)) {
1057 writer->UnbinObjectsIntoOffset(obj);
1058 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001059}
1060
1061void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001062 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001063 CHECK(obj != nullptr);
1064
1065 // We know the bin slot, and the total bin sizes for all objects by now,
1066 // so calculate the object's final image offset.
1067
1068 DCHECK(IsImageBinSlotAssigned(obj));
1069 BinSlot bin_slot = GetImageBinSlot(obj);
1070 // Change the lockword from a bin slot into an offset
1071 AssignImageOffset(obj, bin_slot);
1072}
1073
Vladimir Markof4da6752014-08-01 19:04:18 +01001074void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001075 Thread* const self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001076 StackHandleScope<1> hs(self);
1077 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001078
Mathieu Chartiere401d142015-04-22 13:56:20 -07001079 auto* runtime = Runtime::Current();
1080 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001081 DCHECK_EQ(0U, image_end_);
1082
Mathieu Chartier31e89252013-08-28 11:29:12 -07001083 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001084 // know where image_roots is going to end up
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001085 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001086
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001087 image_objects_offset_begin_ = image_end_;
1088 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1089 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001090 // Write the image runtime methods.
1091 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1092 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1093 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1094 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1095 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1096 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1097 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1098 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001099
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001100 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001101 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1102 auto it = native_object_relocations_.find(&image_method_array_);
1103 CHECK(it == native_object_relocations_.end());
1104 size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001105 if (!compile_app_image_) {
1106 native_object_relocations_.emplace(&image_method_array_,
1107 NativeObjectRelocation { offset, image_method_type });
1108 }
Vladimir Marko14632852015-08-17 12:07:23 +01001109 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001110 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001111 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001112 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001113 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001114 for (auto* m : image_methods_) {
1115 CHECK(m != nullptr);
1116 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001117 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1118 if (!IsInBootImage(m)) {
1119 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean);
1120 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001121 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001122 // Calculate size of the dex cache arrays slot and prepare offsets.
1123 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001124
Vladimir Markocf36d492015-08-12 19:27:26 +01001125 // Calculate bin slot offsets.
1126 size_t bin_offset = image_objects_offset_begin_;
Vladimir Marko20f85592015-03-19 10:07:02 +00001127 for (size_t i = 0; i != kBinSize; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01001128 bin_slot_offsets_[i] = bin_offset;
1129 bin_offset += bin_slot_sizes_[i];
1130 if (i == kBinArtField) {
1131 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1132 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1133 DCHECK_ALIGNED(bin_offset, 4u);
1134 DCHECK(method_alignment == 4u || method_alignment == 8u);
1135 bin_offset = RoundUp(bin_offset, method_alignment);
1136 }
Vladimir Marko20f85592015-03-19 10:07:02 +00001137 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001138 // NOTE: There may be additional padding between the bin slots and the intern table.
1139
Mathieu Chartierc7853442015-03-27 14:35:38 -07001140 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
1141
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001142 // Transform each object's bin slot into an offset which will be used to do the final copy.
1143 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001144
Mathieu Chartierc7853442015-03-27 14:35:38 -07001145 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001146
Vladimir Markof4da6752014-08-01 19:04:18 +01001147 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
1148
Mathieu Chartiere401d142015-04-22 13:56:20 -07001149 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001150 for (auto& pair : native_object_relocations_) {
1151 NativeObjectRelocation& relocation = pair.second;
1152 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Markocf36d492015-08-12 19:27:26 +01001153 relocation.offset += bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001154 }
1155
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001156 // Calculate how big the intern table will be after being serialized.
1157 auto* const intern_table = Runtime::Current()->GetInternTable();
1158 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1159 intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1160
Mathieu Chartiere401d142015-04-22 13:56:20 -07001161 // Note that image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001162}
1163
1164void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
1165 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -07001166 const uint8_t* oat_file_begin = GetOatFileBegin();
1167 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001168 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -07001169 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001170
1171 // Create the image sections.
1172 ImageSection sections[ImageHeader::kSectionCount];
1173 // Objects section
1174 auto* objects_section = &sections[ImageHeader::kSectionObjects];
1175 *objects_section = ImageSection(0u, image_end_);
1176 size_t cur_pos = objects_section->End();
1177 // Add field section.
1178 auto* field_section = &sections[ImageHeader::kSectionArtFields];
1179 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
Vladimir Markocf36d492015-08-12 19:27:26 +01001180 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001181 cur_pos = field_section->End();
Vladimir Markocf36d492015-08-12 19:27:26 +01001182 // Round up to the alignment the required by the method section.
Vladimir Marko14632852015-08-17 12:07:23 +01001183 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001184 // Add method section.
1185 auto* methods_section = &sections[ImageHeader::kSectionArtMethods];
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001186 *methods_section = ImageSection(cur_pos,
1187 bin_slot_sizes_[kBinArtMethodClean] +
1188 bin_slot_sizes_[kBinArtMethodDirty]);
Vladimir Markocf36d492015-08-12 19:27:26 +01001189 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001190 cur_pos = methods_section->End();
Vladimir Marko05792b92015-08-03 11:56:49 +01001191 // Add dex cache arrays section.
1192 auto* dex_cache_arrays_section = &sections[ImageHeader::kSectionDexCacheArrays];
1193 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1194 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1195 cur_pos = dex_cache_arrays_section->End();
Nicolas Geoffray7bf2b4f2015-07-08 10:11:59 +00001196 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1197 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001198 // Calculate the size of the interned strings.
1199 auto* interned_strings_section = &sections[ImageHeader::kSectionInternedStrings];
1200 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1201 cur_pos = interned_strings_section->End();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001202 // Finally bitmap section.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001203 const size_t bitmap_bytes = image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001204 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
1205 *bitmap_section = ImageSection(RoundUp(cur_pos, kPageSize), RoundUp(bitmap_bytes, kPageSize));
1206 cur_pos = bitmap_section->End();
1207 if (kIsDebugBuild) {
1208 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001209 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001210 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1211 ++idx;
1212 }
1213 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
1214 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001215 const size_t image_end = static_cast<uint32_t>(interned_strings_section->End());
1216 CHECK_EQ(AlignUp(image_begin_ + image_end, kPageSize), oat_file_begin) <<
1217 "Oat file should be right after the image.";
Mathieu Chartiere401d142015-04-22 13:56:20 -07001218 // Create the header.
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001219 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
1220 image_end,
1221 sections,
1222 image_roots_address_,
1223 oat_file_->GetOatHeader().GetChecksum(),
1224 PointerToLowMemUInt32(oat_file_begin),
1225 PointerToLowMemUInt32(oat_data_begin_),
1226 PointerToLowMemUInt32(oat_data_end),
1227 PointerToLowMemUInt32(oat_file_end),
1228 target_ptr_size_,
1229 compile_pic_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001230}
1231
1232ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001233 auto it = native_object_relocations_.find(method);
1234 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001235 CHECK_GE(it->second.offset, image_end_) << "ArtMethods should be after Objects";
1236 return reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001237}
1238
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001239class FixupRootVisitor : public RootVisitor {
1240 public:
1241 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1242 }
1243
1244 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001245 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001246 for (size_t i = 0; i < count; ++i) {
1247 *roots[i] = ImageAddress(*roots[i]);
1248 }
1249 }
1250
1251 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1252 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001253 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001254 for (size_t i = 0; i < count; ++i) {
1255 roots[i]->Assign(ImageAddress(roots[i]->AsMirrorPtr()));
1256 }
1257 }
1258
1259 private:
1260 ImageWriter* const image_writer_;
1261
Mathieu Chartier90443472015-07-16 20:32:27 -07001262 mirror::Object* ImageAddress(mirror::Object* obj) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001263 const size_t offset = image_writer_->GetImageOffset(obj);
1264 auto* const dest = reinterpret_cast<Object*>(image_writer_->image_begin_ + offset);
1265 VLOG(compiler) << "Update root from " << obj << " to " << dest;
1266 return dest;
1267 }
1268};
1269
Mathieu Chartierc7853442015-03-27 14:35:38 -07001270void ImageWriter::CopyAndFixupNativeData() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001271 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001272 for (auto& pair : native_object_relocations_) {
1273 NativeObjectRelocation& relocation = pair.second;
1274 auto* dest = image_->Begin() + relocation.offset;
1275 DCHECK_GE(dest, image_->Begin() + image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001276 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001277 switch (relocation.type) {
1278 case kNativeObjectRelocationTypeArtField: {
1279 memcpy(dest, pair.first, sizeof(ArtField));
1280 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1281 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1282 break;
1283 }
1284 case kNativeObjectRelocationTypeArtMethodClean:
1285 case kNativeObjectRelocationTypeArtMethodDirty: {
1286 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
1287 reinterpret_cast<ArtMethod*>(dest));
1288 break;
1289 }
1290 // For arrays, copy just the header since the elements will get copied by their corresponding
1291 // relocations.
1292 case kNativeObjectRelocationTypeArtFieldArray: {
1293 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1294 break;
1295 }
1296 case kNativeObjectRelocationTypeArtMethodArrayClean:
1297 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001298 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1299 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001300 ArtMethod::Size(target_ptr_size_),
1301 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001302 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001303 case kNativeObjectRelocationTypeDexCacheArray:
1304 // Nothing to copy here, everything is done in FixupDexCache().
1305 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001306 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001307 }
1308 }
1309 // Fixup the image method roots.
1310 auto* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001311 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001312 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001313 ArtMethod* method = image_methods_[i];
1314 CHECK(method != nullptr);
1315 if (!IsInBootImage(method)) {
1316 auto it = native_object_relocations_.find(method);
1317 CHECK(it != native_object_relocations_.end()) << "No fowarding for " << PrettyMethod(method);
1318 NativeObjectRelocation& relocation = it->second;
1319 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1320 << methods_section;
1321 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
1322 method = reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
1323 }
1324 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001325 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001326 // Write the intern table into the image.
1327 const ImageSection& intern_table_section = image_header->GetImageSection(
1328 ImageHeader::kSectionInternedStrings);
1329 InternTable* const intern_table = Runtime::Current()->GetInternTable();
1330 uint8_t* const memory_ptr = image_->Begin() + intern_table_section.Offset();
1331 const size_t intern_table_bytes = intern_table->WriteToMemory(memory_ptr);
1332 // Fixup the pointers in the newly written intern table to contain image addresses.
1333 InternTable temp_table;
1334 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1335 // the VisitRoots() will update the memory directly rather than the copies.
1336 // This also relies on visit roots not doing any verification which could fail after we update
1337 // the roots to be the image addresses.
1338 temp_table.ReadFromMemory(memory_ptr);
1339 CHECK_EQ(temp_table.Size(), intern_table->Size());
1340 FixupRootVisitor visitor(this);
1341 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
1342 CHECK_EQ(intern_table_bytes, intern_table_bytes_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001343}
1344
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001345void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001346 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001347 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1348 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001349 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001350 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001351 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1352 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001353 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001354 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001355}
1356
Mathieu Chartier590fee92013-09-13 13:46:47 -07001357void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001358 DCHECK(obj != nullptr);
1359 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001360 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1361}
1362
Mathieu Chartiere401d142015-04-22 13:56:20 -07001363void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1364 mirror::Class* klass, Bin array_type) {
1365 CHECK(klass->IsArrayClass());
1366 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1367 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001368 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001369 dst->SetClass(GetImageAddress(arr->GetClass()));
1370 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001371 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001372 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1373 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001374 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001375 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001376 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001377 auto* method = reinterpret_cast<ArtMethod*>(elem);
1378 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1379 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1380 << PrettyClass(method->GetDeclaringClass());
1381 } else {
1382 CHECK_EQ(array_type, kBinArtField);
1383 auto* field = reinterpret_cast<ArtField*>(elem);
1384 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1385 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1386 << PrettyClass(field->GetDeclaringClass());
1387 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001388 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001389 } else {
1390 elem = image_begin_ + it->second.offset;
1391 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001392 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001393 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001394 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001395}
1396
1397void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001398 if (IsInBootImage(obj)) {
1399 return;
1400 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001401 size_t offset = GetImageOffset(obj);
1402 auto* dst = reinterpret_cast<Object*>(image_->Begin() + offset);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001403 DCHECK_LT(offset, image_end_);
1404 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001405
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001406 image_bitmap_->Set(dst); // Mark the obj as live.
1407
1408 const size_t n = obj->SizeOf();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001409 DCHECK_LE(offset + n, image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001410 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001411
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001412 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1413 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001414 const auto it = saved_hashcode_map_.find(obj);
1415 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1416 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001417 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001418}
1419
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001420// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001421class FixupVisitor {
1422 public:
1423 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1424 }
1425
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001426 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1427 // with other logic.
1428 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1429 const {}
1430 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1431
1432
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001433 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001434 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001435 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001436 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1437 // image.
1438 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001439 offset,
1440 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001441 }
1442
1443 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001444 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001445 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001446 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001447 mirror::Reference::ReferentOffset(),
1448 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001449 }
1450
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001451 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001452 ImageWriter* const image_writer_;
1453 mirror::Object* const copy_;
1454};
1455
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001456class FixupClassVisitor FINAL : public FixupVisitor {
1457 public:
1458 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1459 }
1460
Mathieu Chartierc7853442015-03-27 14:35:38 -07001461 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001462 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001463 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001464 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001465 }
1466
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001467 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1468 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001469 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001470 LOG(FATAL) << "Reference not expected here.";
1471 }
1472};
1473
Vladimir Marko05792b92015-08-03 11:56:49 +01001474uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1475 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001476 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001477 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001478 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1479 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001480 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001481 return relocation.offset;
1482}
1483
1484template <typename T>
1485T* ImageWriter::NativeLocationInImage(T* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001486 return (obj == nullptr || IsInBootImage(obj))
1487 ? obj
1488 : reinterpret_cast<T*>(image_begin_ + NativeOffsetInImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001489}
1490
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001491template <typename T>
1492T* ImageWriter::NativeCopyLocation(T* obj) {
1493 return (obj == nullptr || IsInBootImage(obj))
1494 ? obj
1495 : reinterpret_cast<T*>(image_->Begin() + NativeOffsetInImage(obj));
1496}
1497
1498class NativeLocationVisitor {
1499 public:
1500 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1501
1502 template <typename T>
1503 T* operator()(T* ptr) const {
1504 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001505 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001506
1507 private:
1508 ImageWriter* const image_writer_;
1509};
1510
1511void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
1512 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001513 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001514 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001515}
1516
Ian Rogersef7d42f2014-01-06 12:55:46 -08001517void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001518 DCHECK(orig != nullptr);
1519 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001520 if (kUseBakerOrBrooksReadBarrier) {
1521 orig->AssertReadBarrierPointer();
1522 if (kUseBrooksReadBarrier) {
1523 // Note the address 'copy' isn't the same as the image address of 'orig'.
1524 copy->SetReadBarrierPointer(GetImageAddress(orig));
1525 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1526 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001527 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001528 auto* klass = orig->GetClass();
1529 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001530 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001531 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1532 if (it != pointer_arrays_.end()) {
1533 // Should only need to fixup every pointer array exactly once.
1534 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1535 pointer_arrays_.erase(it);
1536 return;
1537 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001538 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001539 if (orig->IsClass()) {
1540 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001541 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001542 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1543 // Need to go update the ArtMethod.
1544 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1545 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1546 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001547 auto it = native_object_relocations_.find(src_method);
1548 CHECK(it != native_object_relocations_.end())
1549 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001550 dest->SetArtMethod(
1551 reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001552 } else if (!klass->IsArrayClass()) {
1553 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1554 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1555 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
1556 } else if (klass->IsSubClass(down_cast<mirror::Class*>(
1557 class_linker->GetClassRoot(ClassLinker::kJavaLangClassLoader)))) {
1558 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1559 // ClassLoader.
1560 down_cast<mirror::ClassLoader*>(copy)->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001561 // Also set allocator to null to be safe. The allocator is created when we create the class
1562 // table. We also never expect to unload things in the image since they are held live as
1563 // roots.
1564 down_cast<mirror::ClassLoader*>(copy)->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001565 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001566 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001567 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001568 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001569 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001570}
1571
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001572
1573class ImageAddressVisitor {
1574 public:
1575 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1576
1577 template <typename T>
1578 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1579 return image_writer_->GetImageAddress(ptr);
1580 }
1581
1582 private:
1583 ImageWriter* const image_writer_;
1584};
1585
1586
Vladimir Marko05792b92015-08-03 11:56:49 +01001587void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1588 mirror::DexCache* copy_dex_cache) {
1589 // Though the DexCache array fields are usually treated as native pointers, we set the full
1590 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1591 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1592 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1593 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1594 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001595 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
1596 NativeLocationInImage(orig_strings),
1597 /*pointer size*/8u);
1598 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings), ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001599 }
1600 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1601 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001602 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
1603 NativeLocationInImage(orig_types),
1604 /*pointer size*/8u);
1605 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types), ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001606 }
1607 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1608 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001609 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
1610 NativeLocationInImage(orig_methods),
1611 /*pointer size*/8u);
1612 ArtMethod** copy_methods = NativeCopyLocation(orig_methods);
Vladimir Marko05792b92015-08-03 11:56:49 +01001613 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1614 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001615 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001616 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1617 }
1618 }
1619 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1620 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001621 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
1622 NativeLocationInImage(orig_fields),
1623 /*pointer size*/8u);
1624 ArtField** copy_fields = NativeCopyLocation(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +01001625 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1626 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001627 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001628 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1629 }
1630 }
1631}
1632
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001633const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1634 DCHECK_LT(type, kOatAddressCount);
1635 // If we are compiling an app image, we need to use the stubs of the boot image.
1636 if (compile_app_image_) {
1637 // Use the current image pointers.
Mathieu Chartier073b16c2015-11-10 14:13:23 -08001638 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetBootImageSpace();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001639 DCHECK(image_space != nullptr);
1640 const OatFile* oat_file = image_space->GetOatFile();
1641 CHECK(oat_file != nullptr);
1642 const OatHeader& header = oat_file->GetOatHeader();
1643 switch (type) {
1644 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1645 case kOatAddressQuickGenericJNITrampoline:
1646 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1647 case kOatAddressInterpreterToInterpreterBridge:
1648 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1649 case kOatAddressInterpreterToCompiledCodeBridge:
1650 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1651 case kOatAddressJNIDlsymLookup:
1652 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1653 case kOatAddressQuickIMTConflictTrampoline:
1654 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1655 case kOatAddressQuickResolutionTrampoline:
1656 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1657 case kOatAddressQuickToInterpreterBridge:
1658 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1659 default:
1660 UNREACHABLE();
1661 }
1662 }
1663 return GetOatAddressForOffset(oat_address_offsets_[type]);
1664}
1665
Mathieu Chartiere401d142015-04-22 13:56:20 -07001666const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method, bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001667 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
1668 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
1669 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07001670 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001671 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001672
1673 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1674 // trampoline.
1675
1676 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001677 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1678 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001679 const uint8_t* quick_code = GetOatAddressForOffset(quick_oat_code_offset);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001680 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001681 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
1682 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001683 // We have code for a non-static or initialized method, just use the code.
1684 } else if (quick_code == nullptr && method->IsNative() &&
1685 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1686 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001687 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001688 } else if (quick_code == nullptr && !method->IsNative()) {
1689 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001690 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001691 *quick_is_interpreted = true;
1692 } else {
1693 CHECK(!method->GetDeclaringClass()->IsInitialized());
1694 // We have code for a static method, but need to go through the resolution stub for class
1695 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001696 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
1697 }
1698 if (!IsInBootOatFile(quick_code)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001699 DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001700 }
1701 return quick_code;
1702}
1703
Mathieu Chartiere401d142015-04-22 13:56:20 -07001704const uint8_t* ImageWriter::GetQuickEntryPoint(ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001705 // Calculate the quick entry point following the same logic as FixupMethod() below.
1706 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001707 Runtime* runtime = Runtime::Current();
1708 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001709 return GetOatAddress(kOatAddressQuickResolutionTrampoline);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001710 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
1711 method == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001712 return GetOatAddress(kOatAddressQuickIMTConflictTrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001713 } else {
1714 // We assume all methods have code. If they don't currently then we set them to the use the
1715 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1716 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07001717 if (UNLIKELY(!method->IsInvokable())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001718 return GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001719 } else {
1720 bool quick_is_interpreted;
1721 return GetQuickCode(method, &quick_is_interpreted);
1722 }
1723 }
1724}
1725
Mathieu Chartiere401d142015-04-22 13:56:20 -07001726void ImageWriter::CopyAndFixupMethod(ArtMethod* orig, ArtMethod* copy) {
Vladimir Marko14632852015-08-17 12:07:23 +01001727 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001728
1729 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01001730
1731 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
1732 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
1733 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
1734 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001735
Ian Rogers848871b2013-08-05 10:56:33 -07001736 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1737 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07001738
Ian Rogers848871b2013-08-05 10:56:33 -07001739 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001740 Runtime* runtime = Runtime::Current();
1741 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001742 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001743 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001744 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1745 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001746 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001747 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001748 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
1749 bool found_one = false;
1750 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
1751 auto idx = static_cast<Runtime::CalleeSaveType>(i);
1752 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
1753 found_one = true;
1754 break;
1755 }
1756 }
1757 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
1758 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001759 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001760 // We assume all methods have code. If they don't currently then we set them to the use the
1761 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1762 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07001763 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001764 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001765 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001766 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001767 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -07001768 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001769 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001770
Sebastien Hertze1d07812014-05-21 15:44:09 +02001771 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001772 if (orig->IsNative()) {
1773 // The native method's pointer is set to a stub to lookup via dlsym.
1774 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001775 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001776 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001777 }
1778 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001779 }
1780}
1781
Alex Lighta59dd802014-07-02 16:28:08 -07001782static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001783 uint64_t data_sec_offset;
1784 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1785 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001786 return nullptr;
1787 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001788 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001789}
1790
Vladimir Markof4da6752014-08-01 19:04:18 +01001791void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001792 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001793 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file,
1794 PROT_READ | PROT_WRITE,
1795 MAP_SHARED,
1796 &error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001797 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001798 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001799 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001800 }
Alex Lighta59dd802014-07-02 16:28:08 -07001801 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1802 CHECK(oat_header != nullptr);
1803 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001804
Brian Carlstrom7940e442013-07-12 13:46:57 -07001805 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001806 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001807}
1808
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001809size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1810 DCHECK_LE(up_to, kBinSize);
1811 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1812}
1813
1814ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1815 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07001816 static_assert(kBinBits == 3, "wrong number of bin bits");
1817 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001818 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1819
1820 DCHECK_LT(GetBin(), kBinSize);
1821 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1822}
1823
1824ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1825 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1826 DCHECK_EQ(index, GetIndex());
1827}
1828
1829ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1830 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1831}
1832
1833uint32_t ImageWriter::BinSlot::GetIndex() const {
1834 return lockword_ & ~kBinMask;
1835}
1836
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001837uint8_t* ImageWriter::GetOatFileBegin() const {
1838 DCHECK_GT(intern_table_bytes_, 0u);
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001839 size_t native_sections_size = bin_slot_sizes_[kBinArtField] +
1840 bin_slot_sizes_[kBinArtMethodDirty] +
1841 bin_slot_sizes_[kBinArtMethodClean] +
1842 bin_slot_sizes_[kBinDexCacheArray] +
1843 intern_table_bytes_;
Vladimir Marko05792b92015-08-03 11:56:49 +01001844 return image_begin_ + RoundUp(image_end_ + native_sections_size, kPageSize);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001845}
1846
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001847ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
1848 switch (type) {
1849 case kNativeObjectRelocationTypeArtField:
1850 case kNativeObjectRelocationTypeArtFieldArray:
1851 return kBinArtField;
1852 case kNativeObjectRelocationTypeArtMethodClean:
1853 case kNativeObjectRelocationTypeArtMethodArrayClean:
1854 return kBinArtMethodClean;
1855 case kNativeObjectRelocationTypeArtMethodDirty:
1856 case kNativeObjectRelocationTypeArtMethodArrayDirty:
1857 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01001858 case kNativeObjectRelocationTypeDexCacheArray:
1859 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001860 }
1861 UNREACHABLE();
1862}
1863
Brian Carlstrom7940e442013-07-12 13:46:57 -07001864} // namespace art