blob: bf1fcdd5f54ed7763d10bb6ac73ea6c54257dee4 [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 Chartierc6f41b52015-12-04 15:38:50 -0800228 // Write out the image + fields + methods.
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000229 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
230 const auto write_count = image_header->GetImageSize();
231 if (!image_file->WriteFully(image_->Begin(), write_count)) {
Mathieu Chartier31e89252013-08-28 11:29:12 -0700232 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800233 image_file->Erase();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700234 return false;
235 }
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000236
237 // Write out the image bitmap at the page aligned start of the image end.
238 const ImageSection& bitmap_section = image_header->GetImageSection(
239 ImageHeader::kSectionImageBitmap);
240 CHECK_ALIGNED(bitmap_section.Offset(), kPageSize);
241 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
242 bitmap_section.Size(), bitmap_section.Offset())) {
243 PLOG(ERROR) << "Failed to write image file " << image_filename;
244 image_file->Erase();
245 return false;
246 }
247
248 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 Chartier208a5cb2015-12-02 15:44:07 -0800543 const size_t length = RoundUp(image_objects_offset_begin_ +
544 GetBinSizeSum() +
545 intern_table_bytes_ +
546 class_table_bytes_,
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700547 kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700548 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800549 image_.reset(MemMap::MapAnonymous("image writer image",
550 nullptr,
551 length,
552 PROT_READ | PROT_WRITE,
553 false,
554 false,
555 &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700556 if (UNLIKELY(image_.get() == nullptr)) {
557 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700558 return false;
559 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700560
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700561 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
562 CHECK_LE(image_end_, length);
563 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800564 "image bitmap",
565 image_->Begin(),
566 RoundUp(image_end_, kPageSize)));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700567 if (image_bitmap_.get() == nullptr) {
568 LOG(ERROR) << "Failed to allocate memory for image bitmap";
569 return false;
570 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700571 return true;
572}
573
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700574class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
575 public:
576 bool Visit(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
577 StackHandleScope<1> hs(Thread::Current());
578 mirror::Class::ComputeName(hs.NewHandle(c));
579 return true;
580 }
581};
582
Brian Carlstrom7940e442013-07-12 13:46:57 -0700583void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700584 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700585 ComputeLazyFieldsForClassesVisitor visitor;
586 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700587}
588
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800589static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
590 return klass->GetClassLoader() == nullptr;
591}
592
593bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
594 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
595}
596
597bool ImageWriter::ContainsBootClassLoaderNonImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800598 bool early_exit = false;
599 std::unordered_set<mirror::Class*> visited;
600 return ContainsBootClassLoaderNonImageClassInternal(klass, &early_exit, &visited);
601}
602
603bool ImageWriter::ContainsBootClassLoaderNonImageClassInternal(
604 mirror::Class* klass,
605 bool* early_exit,
606 std::unordered_set<mirror::Class*>* visited) {
607 DCHECK(early_exit != nullptr);
608 DCHECK(visited != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700609 if (klass == nullptr) {
610 return false;
611 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800612 auto found = prune_class_memo_.find(klass);
613 if (found != prune_class_memo_.end()) {
614 // Already computed, return the found value.
615 return found->second;
616 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800617 // Circular dependencies, return false but do not store the result in the memoization table.
618 if (visited->find(klass) != visited->end()) {
619 *early_exit = true;
620 return false;
621 }
622 visited->emplace(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800623 bool result = IsBootClassLoaderNonImageClass(klass);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800624 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800625 if (!result) {
626 // Check interfaces since these wont be visited through VisitReferences.)
627 mirror::IfTable* if_table = klass->GetIfTable();
628 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800629 result = result || ContainsBootClassLoaderNonImageClassInternal(
630 if_table->GetInterface(i),
631 &my_early_exit,
632 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800633 }
634 }
635 // Check static fields and their classes.
636 size_t num_static_fields = klass->NumReferenceStaticFields();
637 if (num_static_fields != 0 && klass->IsResolved()) {
638 // Presumably GC can happen when we are cross compiling, it should not cause performance
639 // problems to do pointer size logic.
640 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
641 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
642 for (size_t i = 0u; i < num_static_fields; ++i) {
643 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
644 if (ref != nullptr) {
645 if (ref->IsClass()) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800646 result = result ||
647 ContainsBootClassLoaderNonImageClassInternal(
648 ref->AsClass(),
649 &my_early_exit,
650 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800651 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800652 result = result ||
653 ContainsBootClassLoaderNonImageClassInternal(
654 ref->GetClass(),
655 &my_early_exit,
656 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800657 }
658 field_offset = MemberOffset(field_offset.Uint32Value() +
659 sizeof(mirror::HeapReference<mirror::Object>));
660 }
661 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800662 result = result ||
663 ContainsBootClassLoaderNonImageClassInternal(
664 klass->GetSuperClass(),
665 &my_early_exit,
666 visited);
667 // Erase the element we stored earlier since we are exiting the function.
668 auto it = visited->find(klass);
669 DCHECK(it != visited->end());
670 visited->erase(it);
671 // Only store result if it is true or none of the calls early exited due to circular
672 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
673 // a child call and we can remember the result.
674 if (result == true || !my_early_exit || visited->empty()) {
675 prune_class_memo_[klass] = result;
676 }
677 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800678 return result;
679}
680
681bool ImageWriter::KeepClass(Class* klass) {
682 if (klass == nullptr) {
683 return false;
684 }
685 if (compile_app_image_) {
686 // For app images, we need to prune boot loader classes that are not in the boot image since
687 // these may have already been loaded when the app image is loaded.
688 return !ContainsBootClassLoaderNonImageClass(klass);
689 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700690 std::string temp;
691 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700692}
693
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700694class NonImageClassesVisitor : public ClassVisitor {
695 public:
696 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
697
698 bool Visit(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800699 if (!image_writer_->KeepClass(klass)) {
700 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700701 }
702 return true;
703 }
704
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800705 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700706 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700707};
708
709void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700710 Runtime* runtime = Runtime::Current();
711 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700712 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700713
714 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700715 NonImageClassesVisitor visitor(this);
716 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700717
718 // Remove the undesired classes from the class roots.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800719 for (mirror::Class* klass : visitor.classes_to_prune_) {
720 std::string temp;
721 const char* name = klass->GetDescriptor(&temp);
722 VLOG(compiler) << "Pruning class " << name;
723 if (!compile_app_image_) {
724 DCHECK(IsBootClassLoaderClass(klass));
725 }
726 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800727 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700728 }
729
730 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100731 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700732
733 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
734 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
735 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800736 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
737 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700738 if (dex_cache == nullptr) {
739 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700740 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700741 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
742 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800743 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700744 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700745 }
746 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100747 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
748 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
749 ArtMethod* method =
750 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700751 if (method != nullptr) {
752 auto* declaring_class = method->GetDeclaringClass();
753 // Miranda methods may be held live by a class which was not an image class but have a
754 // declaring class which is an image class. Set it to the resolution method to be safe and
755 // prevent dangling pointers.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800756 if (method->IsMiranda() || !KeepClass(declaring_class)) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100757 mirror::DexCache::SetElementPtrSize(resolved_methods,
758 i,
759 resolution_method,
760 target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700761 } else {
762 // Check that the class is still in the classes table.
763 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
764 << PrettyClass(declaring_class) << " not in class linker table";
765 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700766 }
767 }
768 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700769 ArtField* field = dex_cache->GetResolvedField(i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800770 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700771 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700772 }
773 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700774 // Clean the dex field. It might have been populated during the initialization phase, but
775 // contains data only valid during a real run.
776 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700777 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700778
779 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
780 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800781
782 // Clear to save RAM.
783 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700784}
785
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800786void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700787 if (compiler_driver_.GetImageClasses() != nullptr) {
788 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700789 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700790 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700791}
792
793void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
794 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800795 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700796 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800797 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700798 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700799 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800800 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
801 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700802 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700803 }
804}
805
806void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700807 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700808 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700809 for (const std::string& image_class : *image_classes) {
810 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700811 }
812}
813
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800814void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700815 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700816 // if it is a string, we want to intern it if its not interned.
817 if (obj->GetClass()->IsStringClass()) {
818 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800819 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700820 DCHECK_EQ(obj, obj->AsString()->Intern());
821 return;
822 }
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700823 // InternImageString allows us to intern while holding the heap bitmap lock. This is safe since
824 // we are guaranteed to not have GC during image writing.
Mathieu Chartier90ef3db2015-08-04 15:19:41 -0700825 mirror::String* const interned = Runtime::Current()->GetInternTable()->InternStrongImageString(
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700826 obj->AsString());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700827 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800828 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700829 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800830 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700831 }
832 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800833 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700834 return;
835 }
836 // else (obj == interned), nothing to do but fall through to the normal case
837 }
838
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800839 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700840}
841
842ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
843 Runtime* runtime = Runtime::Current();
844 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700845 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700846 StackHandleScope<3> hs(self);
847 Handle<Class> object_array_class(hs.NewHandle(
848 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700849
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700850 // build an Object[] of all the DexCaches used in the source_space_.
851 // Since we can't hold the dex lock when allocating the dex_caches
852 // ObjectArray, we lock the dex lock twice, first to get the number
853 // of dex caches first and then lock it again to copy the dex
854 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800855 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700856 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700857 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800858 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800859 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
860 mirror::DexCache* dex_cache =
861 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800862 dex_cache_count += IsInBootImage(dex_cache) ? 0u : 1u;
863 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700864 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700865 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800866 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700867 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
868 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700869 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800870 size_t non_image_dex_caches = 0;
871 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800872 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
873 mirror::DexCache* dex_cache =
874 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800875 non_image_dex_caches += IsInBootImage(dex_cache) ? 0u : 1u;
876 }
877 CHECK_EQ(dex_cache_count, non_image_dex_caches)
878 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700879 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800880 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
881 mirror::DexCache* dex_cache =
882 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800883 if (!IsInBootImage(dex_cache)) {
884 dex_caches->Set<false>(i, dex_cache);
885 ++i;
886 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700887 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700888 }
889
890 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -0700891 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700892 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700893 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100894 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700895 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700896 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700897 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700898 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700899}
900
Mathieu Chartier590fee92013-09-13 13:46:47 -0700901// Walk instance fields of the given Class. Separate function to allow recursion on the super
902// class.
903void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
904 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700905 StackHandleScope<1> hs(Thread::Current());
906 Handle<mirror::Class> h_class(hs.NewHandle(klass));
907 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700908 if (super != nullptr) {
909 WalkInstanceFields(obj, super);
910 }
911 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700912 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000913 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700914 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700915 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700916 if (value != nullptr) {
917 WalkFieldsInOrder(value);
918 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000919 field_offset = MemberOffset(field_offset.Uint32Value() +
920 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700921 }
922}
923
924// For an unvisited object, visit it then all its children found via fields.
925void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800926 if (IsInBootImage(obj)) {
927 // Object is in the image, don't need to fix it up.
928 return;
929 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800930 // Use our own visitor routine (instead of GC visitor) to get better locality between
931 // an object and its fields
932 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700933 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700934 StackHandleScope<2> hs(Thread::Current());
935 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
936 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700937 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800938 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700939 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700940 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700941 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700942 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700943 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700944 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700945 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700946 if (value != nullptr) {
947 WalkFieldsInOrder(value);
948 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000949 field_offset = MemberOffset(field_offset.Uint32Value() +
950 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700951 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700952 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700953 auto* as_klass = h_obj->AsClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700954 LengthPrefixedArray<ArtField>* fields[] = {
955 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
956 };
957 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
958 // Total array length including header.
959 if (cur_fields != nullptr) {
960 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
961 // Forward the entire array at once.
962 auto it = native_object_relocations_.find(cur_fields);
963 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
964 << " already forwarded";
965 size_t& offset = bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800966 DCHECK(!IsInBootImage(cur_fields));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700967 native_object_relocations_.emplace(
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800968 cur_fields,
969 NativeObjectRelocation {offset, kNativeObjectRelocationTypeArtFieldArray });
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700970 offset += header_size;
971 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +0100972 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700973 // Need to forward arrays separate of fields.
974 ArtField* field = &cur_fields->At(i);
975 auto it2 = native_object_relocations_.find(field);
976 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
977 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800978 DCHECK(!IsInBootImage(field));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700979 native_object_relocations_.emplace(
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800980 field,
981 NativeObjectRelocation {offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700982 offset += sizeof(ArtField);
983 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700984 }
985 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700986 // Visit and assign offsets for methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700987 LengthPrefixedArray<ArtMethod>* method_arrays[] = {
988 as_klass->GetDirectMethodsPtr(), as_klass->GetVirtualMethodsPtr(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700989 };
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700990 for (LengthPrefixedArray<ArtMethod>* array : method_arrays) {
991 if (array == nullptr) {
992 continue;
993 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700994 bool any_dirty = false;
995 size_t count = 0;
Vladimir Marko14632852015-08-17 12:07:23 +0100996 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
997 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +0100998 auto iteration_range =
999 MakeIterationRangeFromLengthPrefixedArray(array, method_size, method_alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001000 for (auto& m : iteration_range) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001001 any_dirty = any_dirty || WillMethodBeDirty(&m);
1002 ++count;
1003 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001004 NativeObjectRelocationType type = any_dirty
1005 ? kNativeObjectRelocationTypeArtMethodDirty
1006 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001007 Bin bin_type = BinTypeForNativeRelocationType(type);
1008 // Forward the entire array at once, but header first.
Vladimir Markocf36d492015-08-12 19:27:26 +01001009 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1010 method_size,
1011 method_alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001012 auto it = native_object_relocations_.find(array);
1013 CHECK(it == native_object_relocations_.end()) << "Method array " << array
1014 << " already forwarded";
1015 size_t& offset = bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001016 DCHECK(!IsInBootImage(array));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001017 native_object_relocations_.emplace(array, NativeObjectRelocation { offset,
1018 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty :
1019 kNativeObjectRelocationTypeArtMethodArrayClean });
1020 offset += header_size;
1021 for (auto& m : iteration_range) {
1022 AssignMethodOffset(&m, type);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001023 }
1024 (any_dirty ? dirty_methods_ : clean_methods_) += count;
1025 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001026 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001027 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001028 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001029 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001030 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001031 mirror::Object* value = obj_array->Get(i);
1032 if (value != nullptr) {
1033 WalkFieldsInOrder(value);
1034 }
1035 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001036 } else if (h_obj->IsClassLoader()) {
1037 // Register the class loader if it has a class table.
1038 // The fake boot class loader should not get registered and we should end up with only one
1039 // class loader.
1040 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1041 if (class_loader->GetClassTable() != nullptr) {
1042 class_loaders_.insert(class_loader);
1043 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001044 }
1045 }
1046}
1047
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001048void ImageWriter::AssignMethodOffset(ArtMethod* method, NativeObjectRelocationType type) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001049 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001050 auto it = native_object_relocations_.find(method);
1051 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001052 << PrettyMethod(method);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001053 size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
1054 native_object_relocations_.emplace(method, NativeObjectRelocation { offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001055 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001056}
1057
Mathieu Chartier590fee92013-09-13 13:46:47 -07001058void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1059 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1060 DCHECK(writer != nullptr);
1061 writer->WalkFieldsInOrder(obj);
1062}
1063
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001064void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1065 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1066 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001067 if (!writer->IsInBootImage(obj)) {
1068 writer->UnbinObjectsIntoOffset(obj);
1069 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001070}
1071
1072void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001073 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001074 CHECK(obj != nullptr);
1075
1076 // We know the bin slot, and the total bin sizes for all objects by now,
1077 // so calculate the object's final image offset.
1078
1079 DCHECK(IsImageBinSlotAssigned(obj));
1080 BinSlot bin_slot = GetImageBinSlot(obj);
1081 // Change the lockword from a bin slot into an offset
1082 AssignImageOffset(obj, bin_slot);
1083}
1084
Vladimir Markof4da6752014-08-01 19:04:18 +01001085void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001086 Thread* const self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001087 StackHandleScope<1> hs(self);
1088 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001089
Mathieu Chartiere401d142015-04-22 13:56:20 -07001090 auto* runtime = Runtime::Current();
1091 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001092 DCHECK_EQ(0U, image_end_);
1093
Mathieu Chartier31e89252013-08-28 11:29:12 -07001094 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001095 // know where image_roots is going to end up
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001096 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001097
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001098 image_objects_offset_begin_ = image_end_;
1099 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1100 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001101 // Write the image runtime methods.
1102 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1103 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1104 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1105 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1106 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1107 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1108 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1109 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001110
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001111 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001112 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1113 auto it = native_object_relocations_.find(&image_method_array_);
1114 CHECK(it == native_object_relocations_.end());
1115 size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001116 if (!compile_app_image_) {
1117 native_object_relocations_.emplace(&image_method_array_,
1118 NativeObjectRelocation { offset, image_method_type });
1119 }
Vladimir Marko14632852015-08-17 12:07:23 +01001120 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001121 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001122 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001123 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001124 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001125 for (auto* m : image_methods_) {
1126 CHECK(m != nullptr);
1127 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001128 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1129 if (!IsInBootImage(m)) {
1130 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean);
1131 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001132 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001133 // Calculate size of the dex cache arrays slot and prepare offsets.
1134 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001135
Vladimir Markocf36d492015-08-12 19:27:26 +01001136 // Calculate bin slot offsets.
1137 size_t bin_offset = image_objects_offset_begin_;
Vladimir Marko20f85592015-03-19 10:07:02 +00001138 for (size_t i = 0; i != kBinSize; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +01001139 bin_slot_offsets_[i] = bin_offset;
1140 bin_offset += bin_slot_sizes_[i];
1141 if (i == kBinArtField) {
1142 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1143 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1144 DCHECK_ALIGNED(bin_offset, 4u);
1145 DCHECK(method_alignment == 4u || method_alignment == 8u);
1146 bin_offset = RoundUp(bin_offset, method_alignment);
1147 }
Vladimir Marko20f85592015-03-19 10:07:02 +00001148 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001149 // NOTE: There may be additional padding between the bin slots and the intern table.
1150
Mathieu Chartierc7853442015-03-27 14:35:38 -07001151 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
1152
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001153 // Transform each object's bin slot into an offset which will be used to do the final copy.
1154 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001155
Mathieu Chartierc7853442015-03-27 14:35:38 -07001156 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001157
Vladimir Markof4da6752014-08-01 19:04:18 +01001158 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
1159
Mathieu Chartiere401d142015-04-22 13:56:20 -07001160 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001161 for (auto& pair : native_object_relocations_) {
1162 NativeObjectRelocation& relocation = pair.second;
1163 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Markocf36d492015-08-12 19:27:26 +01001164 relocation.offset += bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001165 }
1166
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001167 // Calculate how big the intern table will be after being serialized.
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001168 InternTable* const intern_table = runtime->GetInternTable();
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001169 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1170 intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1171
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001172 // Write out the class table.
1173 ClassLinker* class_linker = runtime->GetClassLinker();
1174 if (boot_image_space_ == nullptr) {
1175 // Compiling the boot image, add null class loader.
1176 class_loaders_.insert(nullptr);
1177 }
1178 if (!class_loaders_.empty()) {
1179 CHECK_EQ(class_loaders_.size(), 1u) << "Should only have one real class loader in the image";
1180 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1181 for (mirror::ClassLoader* loader : class_loaders_) {
1182 ClassTable* table = class_linker->ClassTableForClassLoader(loader);
1183 CHECK(table != nullptr);
1184 class_table_bytes_ += table->WriteToMemory(nullptr);
1185 }
1186 }
1187
Mathieu Chartiere401d142015-04-22 13:56:20 -07001188 // Note that image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001189}
1190
1191void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
1192 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -07001193 const uint8_t* oat_file_begin = GetOatFileBegin();
1194 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001195 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -07001196 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001197
1198 // Create the image sections.
1199 ImageSection sections[ImageHeader::kSectionCount];
1200 // Objects section
1201 auto* objects_section = &sections[ImageHeader::kSectionObjects];
1202 *objects_section = ImageSection(0u, image_end_);
1203 size_t cur_pos = objects_section->End();
1204 // Add field section.
1205 auto* field_section = &sections[ImageHeader::kSectionArtFields];
1206 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
Vladimir Markocf36d492015-08-12 19:27:26 +01001207 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001208 cur_pos = field_section->End();
Vladimir Markocf36d492015-08-12 19:27:26 +01001209 // Round up to the alignment the required by the method section.
Vladimir Marko14632852015-08-17 12:07:23 +01001210 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001211 // Add method section.
1212 auto* methods_section = &sections[ImageHeader::kSectionArtMethods];
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001213 *methods_section = ImageSection(cur_pos,
1214 bin_slot_sizes_[kBinArtMethodClean] +
1215 bin_slot_sizes_[kBinArtMethodDirty]);
Vladimir Markocf36d492015-08-12 19:27:26 +01001216 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001217 cur_pos = methods_section->End();
Vladimir Marko05792b92015-08-03 11:56:49 +01001218 // Add dex cache arrays section.
1219 auto* dex_cache_arrays_section = &sections[ImageHeader::kSectionDexCacheArrays];
1220 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1221 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1222 cur_pos = dex_cache_arrays_section->End();
Nicolas Geoffray7bf2b4f2015-07-08 10:11:59 +00001223 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1224 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001225 // Calculate the size of the interned strings.
1226 auto* interned_strings_section = &sections[ImageHeader::kSectionInternedStrings];
1227 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1228 cur_pos = interned_strings_section->End();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001229 // Calculate the size of the class table section.
1230 auto* class_table_section = &sections[ImageHeader::kSectionClassTable];
1231 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
1232 cur_pos = class_table_section->End();
1233 // Image end goes right before the start of the image bitmap.
1234 const size_t image_end = static_cast<uint32_t>(cur_pos);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001235 // Finally bitmap section.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001236 const size_t bitmap_bytes = image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001237 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
1238 *bitmap_section = ImageSection(RoundUp(cur_pos, kPageSize), RoundUp(bitmap_bytes, kPageSize));
1239 cur_pos = bitmap_section->End();
1240 if (kIsDebugBuild) {
1241 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001242 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001243 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1244 ++idx;
1245 }
1246 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
1247 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001248 CHECK_EQ(AlignUp(image_begin_ + image_end, kPageSize), oat_file_begin) <<
1249 "Oat file should be right after the image.";
Nicolas Geoffray83d4d722015-12-10 08:26:32 +00001250 // Create the header.
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001251 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
1252 image_end,
1253 sections,
1254 image_roots_address_,
1255 oat_file_->GetOatHeader().GetChecksum(),
1256 PointerToLowMemUInt32(oat_file_begin),
1257 PointerToLowMemUInt32(oat_data_begin_),
1258 PointerToLowMemUInt32(oat_data_end),
1259 PointerToLowMemUInt32(oat_file_end),
1260 target_ptr_size_,
Nicolas Geoffray83d4d722015-12-10 08:26:32 +00001261 compile_pic_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001262}
1263
1264ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001265 auto it = native_object_relocations_.find(method);
1266 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001267 CHECK_GE(it->second.offset, image_end_) << "ArtMethods should be after Objects";
1268 return reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001269}
1270
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001271class FixupRootVisitor : public RootVisitor {
1272 public:
1273 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1274 }
1275
1276 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001277 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001278 for (size_t i = 0; i < count; ++i) {
1279 *roots[i] = ImageAddress(*roots[i]);
1280 }
1281 }
1282
1283 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1284 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001285 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001286 for (size_t i = 0; i < count; ++i) {
1287 roots[i]->Assign(ImageAddress(roots[i]->AsMirrorPtr()));
1288 }
1289 }
1290
1291 private:
1292 ImageWriter* const image_writer_;
1293
Mathieu Chartier90443472015-07-16 20:32:27 -07001294 mirror::Object* ImageAddress(mirror::Object* obj) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001295 const size_t offset = image_writer_->GetImageOffset(obj);
1296 auto* const dest = reinterpret_cast<Object*>(image_writer_->image_begin_ + offset);
1297 VLOG(compiler) << "Update root from " << obj << " to " << dest;
1298 return dest;
1299 }
1300};
1301
Mathieu Chartierc7853442015-03-27 14:35:38 -07001302void ImageWriter::CopyAndFixupNativeData() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001303 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001304 for (auto& pair : native_object_relocations_) {
1305 NativeObjectRelocation& relocation = pair.second;
1306 auto* dest = image_->Begin() + relocation.offset;
1307 DCHECK_GE(dest, image_->Begin() + image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001308 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001309 switch (relocation.type) {
1310 case kNativeObjectRelocationTypeArtField: {
1311 memcpy(dest, pair.first, sizeof(ArtField));
1312 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1313 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1314 break;
1315 }
1316 case kNativeObjectRelocationTypeArtMethodClean:
1317 case kNativeObjectRelocationTypeArtMethodDirty: {
1318 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
1319 reinterpret_cast<ArtMethod*>(dest));
1320 break;
1321 }
1322 // For arrays, copy just the header since the elements will get copied by their corresponding
1323 // relocations.
1324 case kNativeObjectRelocationTypeArtFieldArray: {
1325 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1326 break;
1327 }
1328 case kNativeObjectRelocationTypeArtMethodArrayClean:
1329 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001330 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1331 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001332 ArtMethod::Size(target_ptr_size_),
1333 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001334 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001335 case kNativeObjectRelocationTypeDexCacheArray:
1336 // Nothing to copy here, everything is done in FixupDexCache().
1337 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001338 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001339 }
1340 }
1341 // Fixup the image method roots.
1342 auto* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001343 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001344 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001345 ArtMethod* method = image_methods_[i];
1346 CHECK(method != nullptr);
1347 if (!IsInBootImage(method)) {
1348 auto it = native_object_relocations_.find(method);
1349 CHECK(it != native_object_relocations_.end()) << "No fowarding for " << PrettyMethod(method);
1350 NativeObjectRelocation& relocation = it->second;
1351 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1352 << methods_section;
1353 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
1354 method = reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
1355 }
1356 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001357 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001358 FixupRootVisitor root_visitor(this);
1359
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001360 // Write the intern table into the image.
1361 const ImageSection& intern_table_section = image_header->GetImageSection(
1362 ImageHeader::kSectionInternedStrings);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001363 Runtime* const runtime = Runtime::Current();
1364 InternTable* const intern_table = runtime->GetInternTable();
1365 uint8_t* const intern_table_memory_ptr = image_->Begin() + intern_table_section.Offset();
1366 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1367 CHECK_EQ(intern_table_bytes, intern_table_bytes_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001368 // Fixup the pointers in the newly written intern table to contain image addresses.
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001369 InternTable temp_intern_table;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001370 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1371 // the VisitRoots() will update the memory directly rather than the copies.
1372 // This also relies on visit roots not doing any verification which could fail after we update
1373 // the roots to be the image addresses.
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001374 temp_intern_table.ReadFromMemory(intern_table_memory_ptr);
1375 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1376 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1377
1378 // Write the class table(s) into the image.
1379 ClassLinker* const class_linker = runtime->GetClassLinker();
1380 const ImageSection& class_table_section = image_header->GetImageSection(
1381 ImageHeader::kSectionClassTable);
1382 uint8_t* const class_table_memory_ptr = image_->Begin() + class_table_section.Offset();
1383 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1384 size_t class_table_bytes = 0;
1385 for (mirror::ClassLoader* loader : class_loaders_) {
1386 ClassTable* table = class_linker->ClassTableForClassLoader(loader);
1387 CHECK(table != nullptr);
1388 uint8_t* memory_ptr = class_table_memory_ptr + class_table_bytes;
1389 class_table_bytes += table->WriteToMemory(memory_ptr);
1390 // Fixup the pointers in the newly written class table to contain image addresses. See
1391 // above comment for intern tables.
1392 ClassTable temp_class_table;
1393 temp_class_table.ReadFromMemory(memory_ptr);
1394 // CHECK_EQ(temp_class_table.NumNonZygoteClasses(), table->NumNonZygoteClasses());
1395 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1396 RootInfo(kRootUnknown));
1397 temp_class_table.VisitRoots(buffered_visitor);
1398 }
1399 CHECK_EQ(class_table_bytes, class_table_bytes_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001400}
1401
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001402void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001403 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001404 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1405 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001406 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001407 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001408 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1409 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001410 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001411 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001412}
1413
Mathieu Chartier590fee92013-09-13 13:46:47 -07001414void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001415 DCHECK(obj != nullptr);
1416 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001417 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1418}
1419
Mathieu Chartiere401d142015-04-22 13:56:20 -07001420void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1421 mirror::Class* klass, Bin array_type) {
1422 CHECK(klass->IsArrayClass());
1423 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1424 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001425 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001426 dst->SetClass(GetImageAddress(arr->GetClass()));
1427 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001428 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001429 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1430 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001431 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001432 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001433 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001434 auto* method = reinterpret_cast<ArtMethod*>(elem);
1435 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1436 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1437 << PrettyClass(method->GetDeclaringClass());
1438 } else {
1439 CHECK_EQ(array_type, kBinArtField);
1440 auto* field = reinterpret_cast<ArtField*>(elem);
1441 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1442 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1443 << PrettyClass(field->GetDeclaringClass());
1444 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001445 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001446 } else {
1447 elem = image_begin_ + it->second.offset;
1448 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001449 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001450 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001451 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001452}
1453
1454void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001455 if (IsInBootImage(obj)) {
1456 return;
1457 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001458 size_t offset = GetImageOffset(obj);
1459 auto* dst = reinterpret_cast<Object*>(image_->Begin() + offset);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001460 DCHECK_LT(offset, image_end_);
1461 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001462
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001463 image_bitmap_->Set(dst); // Mark the obj as live.
1464
1465 const size_t n = obj->SizeOf();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001466 DCHECK_LE(offset + n, image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001467 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001468
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001469 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1470 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001471 const auto it = saved_hashcode_map_.find(obj);
1472 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1473 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001474 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001475}
1476
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001477// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001478class FixupVisitor {
1479 public:
1480 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1481 }
1482
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001483 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1484 // with other logic.
1485 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1486 const {}
1487 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1488
1489
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001490 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001491 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001492 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001493 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1494 // image.
1495 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001496 offset,
1497 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001498 }
1499
1500 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001501 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001502 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001503 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001504 mirror::Reference::ReferentOffset(),
1505 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001506 }
1507
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001508 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001509 ImageWriter* const image_writer_;
1510 mirror::Object* const copy_;
1511};
1512
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001513class FixupClassVisitor FINAL : public FixupVisitor {
1514 public:
1515 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1516 }
1517
Mathieu Chartierc7853442015-03-27 14:35:38 -07001518 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001519 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001520 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001521 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001522 }
1523
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001524 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1525 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001526 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001527 LOG(FATAL) << "Reference not expected here.";
1528 }
1529};
1530
Vladimir Marko05792b92015-08-03 11:56:49 +01001531uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1532 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001533 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001534 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001535 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1536 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001537 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001538 return relocation.offset;
1539}
1540
1541template <typename T>
1542T* ImageWriter::NativeLocationInImage(T* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001543 return (obj == nullptr || IsInBootImage(obj))
1544 ? obj
1545 : reinterpret_cast<T*>(image_begin_ + NativeOffsetInImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001546}
1547
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001548template <typename T>
1549T* ImageWriter::NativeCopyLocation(T* obj) {
1550 return (obj == nullptr || IsInBootImage(obj))
1551 ? obj
1552 : reinterpret_cast<T*>(image_->Begin() + NativeOffsetInImage(obj));
1553}
1554
1555class NativeLocationVisitor {
1556 public:
1557 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1558
1559 template <typename T>
1560 T* operator()(T* ptr) const {
1561 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001562 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001563
1564 private:
1565 ImageWriter* const image_writer_;
1566};
1567
1568void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
1569 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001570 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001571 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001572}
1573
Ian Rogersef7d42f2014-01-06 12:55:46 -08001574void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001575 DCHECK(orig != nullptr);
1576 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001577 if (kUseBakerOrBrooksReadBarrier) {
1578 orig->AssertReadBarrierPointer();
1579 if (kUseBrooksReadBarrier) {
1580 // Note the address 'copy' isn't the same as the image address of 'orig'.
1581 copy->SetReadBarrierPointer(GetImageAddress(orig));
1582 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1583 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001584 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001585 auto* klass = orig->GetClass();
1586 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001587 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001588 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1589 if (it != pointer_arrays_.end()) {
1590 // Should only need to fixup every pointer array exactly once.
1591 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1592 pointer_arrays_.erase(it);
1593 return;
1594 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001595 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001596 if (orig->IsClass()) {
1597 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001598 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001599 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1600 // Need to go update the ArtMethod.
1601 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1602 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1603 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001604 auto it = native_object_relocations_.find(src_method);
1605 CHECK(it != native_object_relocations_.end())
1606 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001607 dest->SetArtMethod(
1608 reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001609 } else if (!klass->IsArrayClass()) {
1610 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1611 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1612 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001613 } else if (klass->IsClassLoaderClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001614 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1615 // ClassLoader.
1616 down_cast<mirror::ClassLoader*>(copy)->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001617 // Also set allocator to null to be safe. The allocator is created when we create the class
1618 // table. We also never expect to unload things in the image since they are held live as
1619 // roots.
1620 down_cast<mirror::ClassLoader*>(copy)->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001621 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001622 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001623 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001624 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001625 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001626}
1627
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001628
1629class ImageAddressVisitor {
1630 public:
1631 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1632
1633 template <typename T>
1634 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1635 return image_writer_->GetImageAddress(ptr);
1636 }
1637
1638 private:
1639 ImageWriter* const image_writer_;
1640};
1641
1642
Vladimir Marko05792b92015-08-03 11:56:49 +01001643void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1644 mirror::DexCache* copy_dex_cache) {
1645 // Though the DexCache array fields are usually treated as native pointers, we set the full
1646 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1647 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1648 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1649 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1650 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001651 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
1652 NativeLocationInImage(orig_strings),
1653 /*pointer size*/8u);
1654 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings), ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001655 }
1656 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1657 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001658 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
1659 NativeLocationInImage(orig_types),
1660 /*pointer size*/8u);
1661 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types), ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001662 }
1663 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1664 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001665 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
1666 NativeLocationInImage(orig_methods),
1667 /*pointer size*/8u);
1668 ArtMethod** copy_methods = NativeCopyLocation(orig_methods);
Vladimir Marko05792b92015-08-03 11:56:49 +01001669 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1670 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001671 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001672 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1673 }
1674 }
1675 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1676 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001677 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
1678 NativeLocationInImage(orig_fields),
1679 /*pointer size*/8u);
1680 ArtField** copy_fields = NativeCopyLocation(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +01001681 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1682 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001683 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001684 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1685 }
1686 }
1687}
1688
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001689const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1690 DCHECK_LT(type, kOatAddressCount);
1691 // If we are compiling an app image, we need to use the stubs of the boot image.
1692 if (compile_app_image_) {
1693 // Use the current image pointers.
Mathieu Chartier073b16c2015-11-10 14:13:23 -08001694 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetBootImageSpace();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001695 DCHECK(image_space != nullptr);
1696 const OatFile* oat_file = image_space->GetOatFile();
1697 CHECK(oat_file != nullptr);
1698 const OatHeader& header = oat_file->GetOatHeader();
1699 switch (type) {
1700 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1701 case kOatAddressQuickGenericJNITrampoline:
1702 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1703 case kOatAddressInterpreterToInterpreterBridge:
1704 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1705 case kOatAddressInterpreterToCompiledCodeBridge:
1706 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1707 case kOatAddressJNIDlsymLookup:
1708 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1709 case kOatAddressQuickIMTConflictTrampoline:
1710 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1711 case kOatAddressQuickResolutionTrampoline:
1712 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1713 case kOatAddressQuickToInterpreterBridge:
1714 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1715 default:
1716 UNREACHABLE();
1717 }
1718 }
1719 return GetOatAddressForOffset(oat_address_offsets_[type]);
1720}
1721
Mathieu Chartiere401d142015-04-22 13:56:20 -07001722const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method, bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001723 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
1724 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
1725 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07001726 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001727 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001728
1729 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1730 // trampoline.
1731
1732 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001733 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1734 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001735 const uint8_t* quick_code = GetOatAddressForOffset(quick_oat_code_offset);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001736 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001737 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
1738 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001739 // We have code for a non-static or initialized method, just use the code.
1740 } else if (quick_code == nullptr && method->IsNative() &&
1741 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1742 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001743 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001744 } else if (quick_code == nullptr && !method->IsNative()) {
1745 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001746 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001747 *quick_is_interpreted = true;
1748 } else {
1749 CHECK(!method->GetDeclaringClass()->IsInitialized());
1750 // We have code for a static method, but need to go through the resolution stub for class
1751 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001752 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
1753 }
1754 if (!IsInBootOatFile(quick_code)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001755 DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001756 }
1757 return quick_code;
1758}
1759
Mathieu Chartiere401d142015-04-22 13:56:20 -07001760const uint8_t* ImageWriter::GetQuickEntryPoint(ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001761 // Calculate the quick entry point following the same logic as FixupMethod() below.
1762 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001763 Runtime* runtime = Runtime::Current();
1764 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001765 return GetOatAddress(kOatAddressQuickResolutionTrampoline);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001766 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
1767 method == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001768 return GetOatAddress(kOatAddressQuickIMTConflictTrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001769 } else {
1770 // We assume all methods have code. If they don't currently then we set them to the use the
1771 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1772 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07001773 if (UNLIKELY(!method->IsInvokable())) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001774 return GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001775 } else {
1776 bool quick_is_interpreted;
1777 return GetQuickCode(method, &quick_is_interpreted);
1778 }
1779 }
1780}
1781
Mathieu Chartiere401d142015-04-22 13:56:20 -07001782void ImageWriter::CopyAndFixupMethod(ArtMethod* orig, ArtMethod* copy) {
Vladimir Marko14632852015-08-17 12:07:23 +01001783 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001784
1785 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01001786
1787 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
1788 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
1789 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
1790 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001791
Ian Rogers848871b2013-08-05 10:56:33 -07001792 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1793 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07001794
Ian Rogers848871b2013-08-05 10:56:33 -07001795 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001796 Runtime* runtime = Runtime::Current();
1797 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001798 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001799 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001800 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1801 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001802 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001803 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001804 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
1805 bool found_one = false;
1806 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
1807 auto idx = static_cast<Runtime::CalleeSaveType>(i);
1808 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
1809 found_one = true;
1810 break;
1811 }
1812 }
1813 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
1814 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001815 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001816 // We assume all methods have code. If they don't currently then we set them to the use the
1817 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1818 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07001819 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001820 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001821 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001822 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001823 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -07001824 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001825 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001826
Sebastien Hertze1d07812014-05-21 15:44:09 +02001827 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001828 if (orig->IsNative()) {
1829 // The native method's pointer is set to a stub to lookup via dlsym.
1830 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001831 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001832 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001833 }
1834 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001835 }
1836}
1837
Alex Lighta59dd802014-07-02 16:28:08 -07001838static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001839 uint64_t data_sec_offset;
1840 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1841 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001842 return nullptr;
1843 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001844 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001845}
1846
Vladimir Markof4da6752014-08-01 19:04:18 +01001847void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001848 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001849 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file,
1850 PROT_READ | PROT_WRITE,
1851 MAP_SHARED,
1852 &error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07001853 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001854 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001855 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001856 }
Alex Lighta59dd802014-07-02 16:28:08 -07001857 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1858 CHECK(oat_header != nullptr);
1859 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001860
Brian Carlstrom7940e442013-07-12 13:46:57 -07001861 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001862 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001863}
1864
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001865size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1866 DCHECK_LE(up_to, kBinSize);
1867 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1868}
1869
1870ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1871 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07001872 static_assert(kBinBits == 3, "wrong number of bin bits");
1873 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001874 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1875
1876 DCHECK_LT(GetBin(), kBinSize);
1877 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1878}
1879
1880ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1881 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1882 DCHECK_EQ(index, GetIndex());
1883}
1884
1885ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1886 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1887}
1888
1889uint32_t ImageWriter::BinSlot::GetIndex() const {
1890 return lockword_ & ~kBinMask;
1891}
1892
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001893uint8_t* ImageWriter::GetOatFileBegin() const {
1894 DCHECK_GT(intern_table_bytes_, 0u);
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001895 size_t native_sections_size = bin_slot_sizes_[kBinArtField] +
1896 bin_slot_sizes_[kBinArtMethodDirty] +
1897 bin_slot_sizes_[kBinArtMethodClean] +
1898 bin_slot_sizes_[kBinDexCacheArray] +
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001899 intern_table_bytes_ +
1900 class_table_bytes_;
Vladimir Marko05792b92015-08-03 11:56:49 +01001901 return image_begin_ + RoundUp(image_end_ + native_sections_size, kPageSize);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001902}
1903
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001904ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
1905 switch (type) {
1906 case kNativeObjectRelocationTypeArtField:
1907 case kNativeObjectRelocationTypeArtFieldArray:
1908 return kBinArtField;
1909 case kNativeObjectRelocationTypeArtMethodClean:
1910 case kNativeObjectRelocationTypeArtMethodArrayClean:
1911 return kBinArtMethodClean;
1912 case kNativeObjectRelocationTypeArtMethodDirty:
1913 case kNativeObjectRelocationTypeArtMethodArrayDirty:
1914 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01001915 case kNativeObjectRelocationTypeDexCacheArray:
1916 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001917 }
1918 UNREACHABLE();
1919}
1920
Brian Carlstrom7940e442013-07-12 13:46:57 -07001921} // namespace art