blob: af2a4f9426ab3fd6d2685ddd7eb3241ad2d58d4a [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>
Brian Carlstrom7940e442013-07-12 13:46:57 -070023#include <vector>
24
Mathieu Chartierc7853442015-03-27 14:35:38 -070025#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070026#include "art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070027#include "base/logging.h"
28#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010029#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070030#include "compiled_method.h"
31#include "dex_file-inl.h"
32#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070033#include "elf_file.h"
34#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070035#include "elf_writer.h"
36#include "gc/accounting/card_table-inl.h"
37#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070038#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070039#include "gc/heap.h"
40#include "gc/space/large_object_space.h"
41#include "gc/space/space-inl.h"
42#include "globals.h"
43#include "image.h"
44#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070045#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070046#include "lock_word.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070047#include "mirror/abstract_method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070048#include "mirror/array-inl.h"
49#include "mirror/class-inl.h"
50#include "mirror/class_loader.h"
51#include "mirror/dex_cache-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070052#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070053#include "mirror/object-inl.h"
54#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070055#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "oat.h"
57#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070058#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "runtime.h"
60#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070061#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000062#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070064using ::art::mirror::Class;
65using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070066using ::art::mirror::Object;
67using ::art::mirror::ObjectArray;
68using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070069
70namespace art {
71
Igor Murashkinf5b4c502014-11-14 15:01:59 -080072// Separate objects into multiple bins to optimize dirty memory use.
73static constexpr bool kBinObjects = true;
74
Andreas Gampedd9d0552015-03-09 12:57:41 -070075static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -070076 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -070077 Class* klass = obj->GetClass();
78 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
79}
80
81static void CheckNoDexObjects() {
82 ScopedObjectAccess soa(Thread::Current());
83 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
84}
85
Vladimir Markof4da6752014-08-01 19:04:18 +010086bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -080087 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +010088 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -070089 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +010090 PruneNonImageClasses(); // Remove junk
91 ComputeLazyFieldsForImageClasses(); // Add useful information
Vladimir Markof4da6752014-08-01 19:04:18 +010092 }
93 gc::Heap* heap = Runtime::Current()->GetHeap();
94 heap->CollectGarbage(false); // Remove garbage.
95
Andreas Gampedd9d0552015-03-09 12:57:41 -070096 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
97 // dex files.
98 //
99 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
100 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
101 // true.
102 if (kIsDebugBuild) {
103 CheckNoDexObjects();
104 }
105
Vladimir Markof4da6752014-08-01 19:04:18 +0100106 if (kIsDebugBuild) {
107 ScopedObjectAccess soa(Thread::Current());
108 CheckNonImageClassesRemoved();
109 }
110
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700111 {
112 ScopedObjectAccess soa(Thread::Current());
113 CalculateNewObjectOffsets();
114 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100115
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700116 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
117 // bin size sums being calculated.
118 if (!AllocMemory()) {
119 return false;
120 }
121
Vladimir Markof4da6752014-08-01 19:04:18 +0100122 return true;
123}
124
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700125bool ImageWriter::Write(int image_fd,
126 const std::string& image_filename,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700127 const std::string& oat_filename,
128 const std::string& oat_location) {
129 CHECK(!image_filename.empty());
130
Ian Rogers700a4022014-05-19 16:49:03 -0700131 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700132 if (oat_file.get() == nullptr) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800133 PLOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700134 return false;
135 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700136 std::string error_msg;
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700137 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, nullptr, &error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700138 if (oat_file_ == nullptr) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800139 PLOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700140 << ": " << error_msg;
Andreas Gampe0b7fcf92015-03-13 16:54:54 -0700141 oat_file->Erase();
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700142 return false;
143 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700144 Runtime::Current()->GetOatFileManager().RegisterOatFile(
145 std::unique_ptr<const OatFile>(oat_file_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700146
Ian Rogers848871b2013-08-05 10:56:33 -0700147 interpreter_to_interpreter_bridge_offset_ =
148 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
149 interpreter_to_compiled_code_bridge_offset_ =
150 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
151
152 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
153
Andreas Gampe2da88232014-02-27 12:26:20 -0800154 quick_generic_jni_trampoline_offset_ =
155 oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
Jeff Hao88474b42013-10-23 16:24:40 -0700156 quick_imt_conflict_trampoline_offset_ =
157 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700158 quick_resolution_trampoline_offset_ =
159 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
160 quick_to_interpreter_bridge_offset_ =
161 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700162
Brian Carlstrom7940e442013-07-12 13:46:57 -0700163 size_t oat_loaded_size = 0;
164 size_t oat_data_offset = 0;
Vladimir Marko3fc99032015-05-13 19:06:30 +0100165 ElfWriter::GetOatElfInformation(oat_file.get(), &oat_loaded_size, &oat_data_offset);
Alex Light53cb16b2014-06-12 11:26:29 -0700166
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700167 {
168 ScopedObjectAccess soa(Thread::Current());
169 CreateHeader(oat_loaded_size, oat_data_offset);
170 CopyAndFixupNativeData();
171 // TODO: heap validation can't handle these fix up passes.
172 Runtime::Current()->GetHeap()->DisableObjectValidation();
173 CopyAndFixupObjects();
174 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700175
Vladimir Markof4da6752014-08-01 19:04:18 +0100176 SetOatChecksumFromElfFile(oat_file.get());
177
Andreas Gampe4303ba92014-11-06 01:00:46 -0800178 if (oat_file->FlushCloseOrErase() != 0) {
179 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename << " for " << oat_location;
180 return false;
181 }
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700182 std::unique_ptr<File> image_file;
183 if (image_fd != kInvalidImageFd) {
184 image_file.reset(new File(image_fd, image_filename, unix_file::kCheckSafeUsage));
185 } else {
186 image_file.reset(OS::CreateEmptyFile(image_filename.c_str()));
187 }
188 if (image_file == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700189 LOG(ERROR) << "Failed to open image file " << image_filename;
190 return false;
191 }
192 if (fchmod(image_file->Fd(), 0644) != 0) {
193 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800194 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700195 return EXIT_FAILURE;
196 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700197
Mathieu Chartiere401d142015-04-22 13:56:20 -0700198 // Write out the image + fields + methods.
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700199 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700200 const auto write_count = image_header->GetImageSize();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700201 if (!image_file->WriteFully(image_->Begin(), write_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700202 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800203 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700204 return false;
205 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700206
207 // Write out the image bitmap at the page aligned start of the image end.
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700208 const ImageSection& bitmap_section = image_header->GetImageSection(
209 ImageHeader::kSectionImageBitmap);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700210 CHECK_ALIGNED(bitmap_section.Offset(), kPageSize);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700211 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700212 bitmap_section.Size(), bitmap_section.Offset())) {
Mathieu Chartier31e89252013-08-28 11:29:12 -0700213 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800214 image_file->Erase();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700215 return false;
216 }
217
Mathieu Chartiere401d142015-04-22 13:56:20 -0700218 CHECK_EQ(bitmap_section.End(), static_cast<size_t>(image_file->GetLength()));
Andreas Gampe4303ba92014-11-06 01:00:46 -0800219 if (image_file->FlushCloseOrErase() != 0) {
220 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
221 return false;
222 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700223 return true;
224}
225
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700226void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700227 DCHECK(object != nullptr);
228 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800229
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800230 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700231 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700232 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700233 DCHECK(IsImageOffsetAssigned(object));
234}
235
Mathieu Chartiere401d142015-04-22 13:56:20 -0700236void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
237 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
238 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
239 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
240}
241
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800242void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700243 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800244 DCHECK_NE(image_objects_offset_begin_, 0u);
245
Vladimir Markocf36d492015-08-12 19:27:26 +0100246 size_t bin_slot_offset = bin_slot_offsets_[bin_slot.GetBin()];
247 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800248 DCHECK_ALIGNED(new_offset, kObjectAlignment);
249
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700250 SetImageOffset(object, new_offset);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800251 DCHECK_LT(new_offset, image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700252}
253
Ian Rogersef7d42f2014-01-06 12:55:46 -0800254bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800255 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700256 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700257 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700258}
259
Ian Rogersef7d42f2014-01-06 12:55:46 -0800260size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700261 DCHECK(object != nullptr);
262 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700263 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700264 size_t offset = lock_word.ForwardingAddress();
265 DCHECK_LT(offset, image_end_);
266 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700267}
268
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800269void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
270 DCHECK(object != nullptr);
271 DCHECK(!IsImageOffsetAssigned(object));
272 DCHECK(!IsImageBinSlotAssigned(object));
273
274 // Before we stomp over the lock word, save the hash code for later.
275 Monitor::Deflate(Thread::Current(), object);;
276 LockWord lw(object->GetLockWord(false));
277 switch (lw.GetState()) {
278 case LockWord::kFatLocked: {
279 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
280 break;
281 }
282 case LockWord::kThinLocked: {
283 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
284 break;
285 }
286 case LockWord::kUnlocked:
287 // No hash, don't need to save it.
288 break;
289 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700290 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
291 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800292 break;
293 default:
294 LOG(FATAL) << "Unreachable.";
295 UNREACHABLE();
296 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700297 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700298 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800299 DCHECK(IsImageBinSlotAssigned(object));
300}
301
Vladimir Marko20f85592015-03-19 10:07:02 +0000302void ImageWriter::PrepareDexCacheArraySlots() {
303 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700304 Thread* const self = Thread::Current();
305 ReaderMutexLock mu(self, *class_linker->DexLock());
Vladimir Marko20f85592015-03-19 10:07:02 +0000306 uint32_t size = 0u;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700307 for (jobject weak_root : class_linker->GetDexCaches()) {
308 mirror::DexCache* dex_cache =
309 down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
310 if (dex_cache == nullptr) {
311 continue;
312 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000313 const DexFile* dex_file = dex_cache->GetDexFile();
314 dex_cache_array_starts_.Put(dex_file, size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700315 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000316 DCHECK(layout.Valid());
Vladimir Marko05792b92015-08-03 11:56:49 +0100317 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
318 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(), size + layout.TypesOffset());
319 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
320 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(), size + layout.MethodsOffset());
321 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
322 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(), size + layout.FieldsOffset());
323 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
324 AddDexCacheArrayRelocation(dex_cache->GetStrings(), size + layout.StringsOffset());
Vladimir Marko20f85592015-03-19 10:07:02 +0000325 size += layout.Size();
326 }
327 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
328 // when AssignImageBinSlot() assigns their indexes out or order.
329 bin_slot_sizes_[kBinDexCacheArray] = size;
330}
331
Vladimir Marko05792b92015-08-03 11:56:49 +0100332void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset) {
333 if (array != nullptr) {
334 native_object_relocations_.emplace(
335 array,
336 NativeObjectRelocation { offset, kNativeObjectRelocationTypeDexCacheArray });
337 }
338}
339
Mathieu Chartiere401d142015-04-22 13:56:20 -0700340void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
341 DCHECK(arr != nullptr);
342 if (kIsDebugBuild) {
343 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
344 auto* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
345 if (method != nullptr && !method->IsRuntimeMethod()) {
346 auto* klass = method->GetDeclaringClass();
347 CHECK(klass == nullptr || IsImageClass(klass)) << PrettyClass(klass)
348 << " should be an image class";
349 }
350 }
351 }
352 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
353 // ArtMethods.
354 pointer_arrays_.emplace(arr, kBinArtMethodClean);
355}
356
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800357void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
358 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800359 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800360
361 // The magic happens here. We segregate objects into different bins based
362 // on how likely they are to get dirty at runtime.
363 //
364 // Likely-to-dirty objects get packed together into the same bin so that
365 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
366 // maximized.
367 //
368 // This means more pages will stay either clean or shared dirty (with zygote) and
369 // the app will use less of its own (private) memory.
370 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000371 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800372
373 if (kBinObjects) {
374 //
375 // Changing the bin of an object is purely a memory-use tuning.
376 // It has no change on runtime correctness.
377 //
378 // Memory analysis has determined that the following types of objects get dirtied
379 // the most:
380 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000381 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
382 // a fixed layout which helps improve generated code (using PC-relative addressing),
383 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
384 // Since these arrays are huge, most pages do not overlap other objects and it's not
385 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100386 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800387 // * Class'es which are verified [their clinit runs only at runtime]
388 // - classes in general [because their static fields get overwritten]
389 // - initialized classes with all-final statics are unlikely to be ever dirty,
390 // so bin them separately
391 // * Art Methods that are:
392 // - native [their native entry point is not looked up until runtime]
393 // - have declaring classes that aren't initialized
394 // [their interpreter/quick entry points are trampolines until the class
395 // becomes initialized]
396 //
397 // We also assume the following objects get dirtied either never or extremely rarely:
398 // * Strings (they are immutable)
399 // * Art methods that aren't native and have initialized declared classes
400 //
401 // We assume that "regular" bin objects are highly unlikely to become dirtied,
402 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
403 //
404 if (object->IsClass()) {
405 bin = kBinClassVerified;
406 mirror::Class* klass = object->AsClass();
407
Mathieu Chartiere401d142015-04-22 13:56:20 -0700408 // Add non-embedded vtable to the pointer array table if there is one.
409 auto* vtable = klass->GetVTable();
410 if (vtable != nullptr) {
411 AddMethodPointerArray(vtable);
412 }
413 auto* iftable = klass->GetIfTable();
414 if (iftable != nullptr) {
415 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
416 if (iftable->GetMethodArrayCount(i) > 0) {
417 AddMethodPointerArray(iftable->GetMethodArray(i));
418 }
419 }
420 }
421
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800422 if (klass->GetStatus() == Class::kStatusInitialized) {
423 bin = kBinClassInitialized;
424
425 // If the class's static fields are all final, put it into a separate bin
426 // since it's very likely it will stay clean.
427 uint32_t num_static_fields = klass->NumStaticFields();
428 if (num_static_fields == 0) {
429 bin = kBinClassInitializedFinalStatics;
430 } else {
431 // Maybe all the statics are final?
432 bool all_final = true;
433 for (uint32_t i = 0; i < num_static_fields; ++i) {
434 ArtField* field = klass->GetStaticField(i);
435 if (!field->IsFinal()) {
436 all_final = false;
437 break;
438 }
439 }
440
441 if (all_final) {
442 bin = kBinClassInitializedFinalStatics;
443 }
444 }
445 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800446 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
447 bin = kBinString; // Strings are almost always immutable (except for object header).
448 } // else bin = kBinRegular
449 }
450
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800451 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Vladimir Marko05792b92015-08-03 11:56:49 +0100452 current_offset = bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
453 // Move the current bin size up to accomodate the object we just assigned a bin slot.
454 bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800455
456 BinSlot new_bin_slot(bin, current_offset);
457 SetImageBinSlot(object, new_bin_slot);
458
459 ++bin_slot_count_[bin];
460
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800461 // Grow the image closer to the end by the object we just assigned.
462 image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800463}
464
Mathieu Chartiere401d142015-04-22 13:56:20 -0700465bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
466 if (m->IsNative()) {
467 return true;
468 }
469 mirror::Class* declaring_class = m->GetDeclaringClass();
470 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
471 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
472}
473
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800474bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
475 DCHECK(object != nullptr);
476
477 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
478 // If it's in some other state, then we haven't yet assigned an image bin slot.
479 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
480 return false;
481 } else if (kIsDebugBuild) {
482 LockWord lock_word = object->GetLockWord(false);
483 size_t offset = lock_word.ForwardingAddress();
484 BinSlot bin_slot(offset);
485 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()])
486 << "bin slot offset should not exceed the size of that bin";
487 }
488 return true;
489}
490
491ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
492 DCHECK(object != nullptr);
493 DCHECK(IsImageBinSlotAssigned(object));
494
495 LockWord lock_word = object->GetLockWord(false);
496 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
497 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
498
499 BinSlot bin_slot(static_cast<uint32_t>(offset));
500 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()]);
501
502 return bin_slot;
503}
504
Brian Carlstrom7940e442013-07-12 13:46:57 -0700505bool ImageWriter::AllocMemory() {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700506 const size_t length = RoundUp(image_objects_offset_begin_ + GetBinSizeSum() + intern_table_bytes_,
507 kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700508 std::string error_msg;
Vladimir Marko5c42c292015-02-25 12:02:49 +0000509 image_.reset(MemMap::MapAnonymous("image writer image", nullptr, length, PROT_READ | PROT_WRITE,
510 false, false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700511 if (UNLIKELY(image_.get() == nullptr)) {
512 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700513 return false;
514 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700515
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700516 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
517 CHECK_LE(image_end_, length);
518 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
519 "image bitmap", image_->Begin(), RoundUp(image_end_, kPageSize)));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700520 if (image_bitmap_.get() == nullptr) {
521 LOG(ERROR) << "Failed to allocate memory for image bitmap";
522 return false;
523 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700524 return true;
525}
526
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700527class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
528 public:
529 bool Visit(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
530 StackHandleScope<1> hs(Thread::Current());
531 mirror::Class::ComputeName(hs.NewHandle(c));
532 return true;
533 }
534};
535
Brian Carlstrom7940e442013-07-12 13:46:57 -0700536void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700537 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700538 ComputeLazyFieldsForClassesVisitor visitor;
539 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700540}
541
Ian Rogersef7d42f2014-01-06 12:55:46 -0800542bool ImageWriter::IsImageClass(Class* klass) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700543 if (klass == nullptr) {
544 return false;
545 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700546 std::string temp;
547 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700548}
549
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700550class NonImageClassesVisitor : public ClassVisitor {
551 public:
552 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
553
554 bool Visit(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
555 if (!image_writer_->IsImageClass(klass)) {
556 std::string temp;
557 non_image_classes_.insert(klass->GetDescriptor(&temp));
558 }
559 return true;
560 }
561
562 std::set<std::string> non_image_classes_;
563 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700564};
565
566void ImageWriter::PruneNonImageClasses() {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700567 if (compiler_driver_.GetImageClasses() == nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700568 return;
569 }
570 Runtime* runtime = Runtime::Current();
571 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700572 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700573
574 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700575 NonImageClassesVisitor visitor(this);
576 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700577
578 // Remove the undesired classes from the class roots.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700579 for (const std::string& it : visitor.non_image_classes_) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700580 bool result = class_linker->RemoveClass(it.c_str(), nullptr);
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800581 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700582 }
583
584 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100585 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700586
587 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
588 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
589 ReaderMutexLock mu2(self, *class_linker->DexLock());
590 for (jobject weak_root : class_linker->GetDexCaches()) {
591 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
592 if (dex_cache == nullptr) {
593 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700594 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700595 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
596 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700597 if (klass != nullptr && !IsImageClass(klass)) {
598 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700599 }
600 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100601 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
602 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
603 ArtMethod* method =
604 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700605 if (method != nullptr) {
606 auto* declaring_class = method->GetDeclaringClass();
607 // Miranda methods may be held live by a class which was not an image class but have a
608 // declaring class which is an image class. Set it to the resolution method to be safe and
609 // prevent dangling pointers.
610 if (method->IsMiranda() || !IsImageClass(declaring_class)) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100611 mirror::DexCache::SetElementPtrSize(resolved_methods,
612 i,
613 resolution_method,
614 target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700615 } else {
616 // Check that the class is still in the classes table.
617 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
618 << PrettyClass(declaring_class) << " not in class linker table";
619 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700620 }
621 }
622 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700623 ArtField* field = dex_cache->GetResolvedField(i, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700624 if (field != nullptr && !IsImageClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700625 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700626 }
627 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700628 // Clean the dex field. It might have been populated during the initialization phase, but
629 // contains data only valid during a real run.
630 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700631 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700632
633 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
634 class_linker->DropFindArrayClassCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700635}
636
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800637void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700638 if (compiler_driver_.GetImageClasses() != nullptr) {
639 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700640 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700641 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700642}
643
644void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
645 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700646 if (obj->IsClass()) {
647 Class* klass = obj->AsClass();
648 if (!image_writer->IsImageClass(klass)) {
649 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700650 std::string temp;
651 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700652 << " " << PrettyDescriptor(klass);
653 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700654 }
655}
656
657void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700658 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700659 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700660 for (const std::string& image_class : *image_classes) {
661 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700662 }
663}
664
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800665void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700666 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700667 // if it is a string, we want to intern it if its not interned.
668 if (obj->GetClass()->IsStringClass()) {
669 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800670 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700671 DCHECK_EQ(obj, obj->AsString()->Intern());
672 return;
673 }
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700674 // InternImageString allows us to intern while holding the heap bitmap lock. This is safe since
675 // we are guaranteed to not have GC during image writing.
Mathieu Chartier90ef3db2015-08-04 15:19:41 -0700676 mirror::String* const interned = Runtime::Current()->GetInternTable()->InternStrongImageString(
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700677 obj->AsString());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700678 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800679 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700680 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800681 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700682 }
683 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800684 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700685 return;
686 }
687 // else (obj == interned), nothing to do but fall through to the normal case
688 }
689
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800690 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700691}
692
693ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
694 Runtime* runtime = Runtime::Current();
695 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700696 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700697 StackHandleScope<3> hs(self);
698 Handle<Class> object_array_class(hs.NewHandle(
699 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700700
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700701 // build an Object[] of all the DexCaches used in the source_space_.
702 // Since we can't hold the dex lock when allocating the dex_caches
703 // ObjectArray, we lock the dex lock twice, first to get the number
704 // of dex caches first and then lock it again to copy the dex
705 // caches. We check that the number of dex caches does not change.
706 size_t dex_cache_count;
707 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700708 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700709 dex_cache_count = class_linker->GetDexCacheCount();
710 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700711 Handle<ObjectArray<Object>> dex_caches(
712 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700713 dex_cache_count)));
714 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
715 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700716 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700717 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
718 << "The number of dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700719 size_t i = 0;
720 for (jobject weak_root : class_linker->GetDexCaches()) {
721 mirror::DexCache* dex_cache =
722 down_cast<mirror::DexCache*>(self->DecodeJObject(weak_root));
723 dex_caches->Set<false>(i, dex_cache);
724 ++i;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700725 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700726 }
727
728 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -0700729 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700730 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700731 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100732 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700733 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700734 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700735 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700736 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700737}
738
Mathieu Chartier590fee92013-09-13 13:46:47 -0700739// Walk instance fields of the given Class. Separate function to allow recursion on the super
740// class.
741void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
742 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700743 StackHandleScope<1> hs(Thread::Current());
744 Handle<mirror::Class> h_class(hs.NewHandle(klass));
745 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700746 if (super != nullptr) {
747 WalkInstanceFields(obj, super);
748 }
749 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700750 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000751 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700752 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700753 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700754 if (value != nullptr) {
755 WalkFieldsInOrder(value);
756 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000757 field_offset = MemberOffset(field_offset.Uint32Value() +
758 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700759 }
760}
761
762// For an unvisited object, visit it then all its children found via fields.
763void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800764 // Use our own visitor routine (instead of GC visitor) to get better locality between
765 // an object and its fields
766 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700767 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700768 StackHandleScope<2> hs(Thread::Current());
769 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
770 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700771 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800772 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700773 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700774 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700775 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700776 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700777 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700778 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700779 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700780 if (value != nullptr) {
781 WalkFieldsInOrder(value);
782 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000783 field_offset = MemberOffset(field_offset.Uint32Value() +
784 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700785 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700786 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700787 auto* as_klass = h_obj->AsClass();
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700788 LengthPrefixedArray<ArtField>* fields[] = {
789 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
790 };
791 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
792 // Total array length including header.
793 if (cur_fields != nullptr) {
794 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
795 // Forward the entire array at once.
796 auto it = native_object_relocations_.find(cur_fields);
797 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
798 << " already forwarded";
799 size_t& offset = bin_slot_sizes_[kBinArtField];
800 native_object_relocations_.emplace(
801 cur_fields, NativeObjectRelocation {
802 offset, kNativeObjectRelocationTypeArtFieldArray });
803 offset += header_size;
804 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +0100805 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700806 // Need to forward arrays separate of fields.
807 ArtField* field = &cur_fields->At(i);
808 auto it2 = native_object_relocations_.find(field);
809 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
810 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
811 native_object_relocations_.emplace(
812 field, NativeObjectRelocation {offset, kNativeObjectRelocationTypeArtField });
813 offset += sizeof(ArtField);
814 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700815 }
816 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700817 // Visit and assign offsets for methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700818 LengthPrefixedArray<ArtMethod>* method_arrays[] = {
819 as_klass->GetDirectMethodsPtr(), as_klass->GetVirtualMethodsPtr(),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700820 };
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700821 for (LengthPrefixedArray<ArtMethod>* array : method_arrays) {
822 if (array == nullptr) {
823 continue;
824 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700825 bool any_dirty = false;
826 size_t count = 0;
Vladimir Marko14632852015-08-17 12:07:23 +0100827 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
828 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +0100829 auto iteration_range =
830 MakeIterationRangeFromLengthPrefixedArray(array, method_size, method_alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700831 for (auto& m : iteration_range) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700832 any_dirty = any_dirty || WillMethodBeDirty(&m);
833 ++count;
834 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700835 NativeObjectRelocationType type = any_dirty ? kNativeObjectRelocationTypeArtMethodDirty :
836 kNativeObjectRelocationTypeArtMethodClean;
837 Bin bin_type = BinTypeForNativeRelocationType(type);
838 // Forward the entire array at once, but header first.
Vladimir Markocf36d492015-08-12 19:27:26 +0100839 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
840 method_size,
841 method_alignment);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700842 auto it = native_object_relocations_.find(array);
843 CHECK(it == native_object_relocations_.end()) << "Method array " << array
844 << " already forwarded";
845 size_t& offset = bin_slot_sizes_[bin_type];
846 native_object_relocations_.emplace(array, NativeObjectRelocation { offset,
847 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty :
848 kNativeObjectRelocationTypeArtMethodArrayClean });
849 offset += header_size;
850 for (auto& m : iteration_range) {
851 AssignMethodOffset(&m, type);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700852 }
853 (any_dirty ? dirty_methods_ : clean_methods_) += count;
854 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700855 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700856 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700857 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700858 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700859 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700860 mirror::Object* value = obj_array->Get(i);
861 if (value != nullptr) {
862 WalkFieldsInOrder(value);
863 }
864 }
865 }
866 }
867}
868
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700869void ImageWriter::AssignMethodOffset(ArtMethod* method, NativeObjectRelocationType type) {
870 auto it = native_object_relocations_.find(method);
871 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -0700872 << PrettyMethod(method);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700873 size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
874 native_object_relocations_.emplace(method, NativeObjectRelocation { offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +0100875 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700876}
877
Mathieu Chartier590fee92013-09-13 13:46:47 -0700878void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
879 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
880 DCHECK(writer != nullptr);
881 writer->WalkFieldsInOrder(obj);
882}
883
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800884void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
885 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
886 DCHECK(writer != nullptr);
887 writer->UnbinObjectsIntoOffset(obj);
888}
889
890void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
891 CHECK(obj != nullptr);
892
893 // We know the bin slot, and the total bin sizes for all objects by now,
894 // so calculate the object's final image offset.
895
896 DCHECK(IsImageBinSlotAssigned(obj));
897 BinSlot bin_slot = GetImageBinSlot(obj);
898 // Change the lockword from a bin slot into an offset
899 AssignImageOffset(obj, bin_slot);
900}
901
Vladimir Markof4da6752014-08-01 19:04:18 +0100902void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700903 Thread* const self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700904 StackHandleScope<1> hs(self);
905 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700906
Mathieu Chartiere401d142015-04-22 13:56:20 -0700907 auto* runtime = Runtime::Current();
908 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700909 DCHECK_EQ(0U, image_end_);
910
Mathieu Chartier31e89252013-08-28 11:29:12 -0700911 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700912 // know where image_roots is going to end up
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800913 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700914
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800915 image_objects_offset_begin_ = image_end_;
916 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
917 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700918 // Write the image runtime methods.
919 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
920 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
921 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
922 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
923 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
924 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
925 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
926 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700927
928 // Add room for fake length prefixed array.
929 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
930 auto it = native_object_relocations_.find(&image_method_array_);
931 CHECK(it == native_object_relocations_.end());
932 size_t& offset = bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
933 native_object_relocations_.emplace(&image_method_array_,
934 NativeObjectRelocation { offset, image_method_type });
Vladimir Marko14632852015-08-17 12:07:23 +0100935 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -0700936 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +0100937 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +0100938 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -0700939 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700940 for (auto* m : image_methods_) {
941 CHECK(m != nullptr);
942 CHECK(m->IsRuntimeMethod());
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700943 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700944 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100945 // Calculate size of the dex cache arrays slot and prepare offsets.
946 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700947
Vladimir Markocf36d492015-08-12 19:27:26 +0100948 // Calculate bin slot offsets.
949 size_t bin_offset = image_objects_offset_begin_;
Vladimir Marko20f85592015-03-19 10:07:02 +0000950 for (size_t i = 0; i != kBinSize; ++i) {
Vladimir Markocf36d492015-08-12 19:27:26 +0100951 bin_slot_offsets_[i] = bin_offset;
952 bin_offset += bin_slot_sizes_[i];
953 if (i == kBinArtField) {
954 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
955 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
956 DCHECK_ALIGNED(bin_offset, 4u);
957 DCHECK(method_alignment == 4u || method_alignment == 8u);
958 bin_offset = RoundUp(bin_offset, method_alignment);
959 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000960 }
Vladimir Markocf36d492015-08-12 19:27:26 +0100961 // NOTE: There may be additional padding between the bin slots and the intern table.
962
Mathieu Chartierc7853442015-03-27 14:35:38 -0700963 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
964
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800965 // Transform each object's bin slot into an offset which will be used to do the final copy.
966 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700967
Mathieu Chartierc7853442015-03-27 14:35:38 -0700968 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800969
Vladimir Markof4da6752014-08-01 19:04:18 +0100970 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
971
Mathieu Chartiere401d142015-04-22 13:56:20 -0700972 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700973 for (auto& pair : native_object_relocations_) {
974 NativeObjectRelocation& relocation = pair.second;
975 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Vladimir Markocf36d492015-08-12 19:27:26 +0100976 relocation.offset += bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -0700977 }
978
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700979 // Calculate how big the intern table will be after being serialized.
980 auto* const intern_table = Runtime::Current()->GetInternTable();
981 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
982 intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
983
Mathieu Chartiere401d142015-04-22 13:56:20 -0700984 // Note that image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +0100985}
986
987void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
988 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -0700989 const uint8_t* oat_file_begin = GetOatFileBegin();
990 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700991 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -0700992 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700993
994 // Create the image sections.
995 ImageSection sections[ImageHeader::kSectionCount];
996 // Objects section
997 auto* objects_section = &sections[ImageHeader::kSectionObjects];
998 *objects_section = ImageSection(0u, image_end_);
999 size_t cur_pos = objects_section->End();
1000 // Add field section.
1001 auto* field_section = &sections[ImageHeader::kSectionArtFields];
1002 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
Vladimir Markocf36d492015-08-12 19:27:26 +01001003 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001004 cur_pos = field_section->End();
Vladimir Markocf36d492015-08-12 19:27:26 +01001005 // Round up to the alignment the required by the method section.
Vladimir Marko14632852015-08-17 12:07:23 +01001006 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001007 // Add method section.
1008 auto* methods_section = &sections[ImageHeader::kSectionArtMethods];
1009 *methods_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtMethodClean] +
1010 bin_slot_sizes_[kBinArtMethodDirty]);
Vladimir Markocf36d492015-08-12 19:27:26 +01001011 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001012 cur_pos = methods_section->End();
Vladimir Marko05792b92015-08-03 11:56:49 +01001013 // Add dex cache arrays section.
1014 auto* dex_cache_arrays_section = &sections[ImageHeader::kSectionDexCacheArrays];
1015 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1016 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1017 cur_pos = dex_cache_arrays_section->End();
Nicolas Geoffray7bf2b4f2015-07-08 10:11:59 +00001018 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1019 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001020 // Calculate the size of the interned strings.
1021 auto* interned_strings_section = &sections[ImageHeader::kSectionInternedStrings];
1022 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1023 cur_pos = interned_strings_section->End();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001024 // Finally bitmap section.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001025 const size_t bitmap_bytes = image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001026 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
1027 *bitmap_section = ImageSection(RoundUp(cur_pos, kPageSize), RoundUp(bitmap_bytes, kPageSize));
1028 cur_pos = bitmap_section->End();
1029 if (kIsDebugBuild) {
1030 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001031 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001032 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1033 ++idx;
1034 }
1035 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
1036 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001037 const size_t image_end = static_cast<uint32_t>(interned_strings_section->End());
1038 CHECK_EQ(AlignUp(image_begin_ + image_end, kPageSize), oat_file_begin) <<
1039 "Oat file should be right after the image.";
Mathieu Chartiere401d142015-04-22 13:56:20 -07001040 // Create the header.
1041 new (image_->Begin()) ImageHeader(
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001042 PointerToLowMemUInt32(image_begin_), image_end,
1043 sections, image_roots_address_, oat_file_->GetOatHeader().GetChecksum(),
Mathieu Chartiere401d142015-04-22 13:56:20 -07001044 PointerToLowMemUInt32(oat_file_begin), PointerToLowMemUInt32(oat_data_begin_),
1045 PointerToLowMemUInt32(oat_data_end), PointerToLowMemUInt32(oat_file_end), target_ptr_size_,
1046 compile_pic_);
1047}
1048
1049ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001050 auto it = native_object_relocations_.find(method);
1051 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001052 CHECK_GE(it->second.offset, image_end_) << "ArtMethods should be after Objects";
1053 return reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001054}
1055
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001056class FixupRootVisitor : public RootVisitor {
1057 public:
1058 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1059 }
1060
1061 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001062 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001063 for (size_t i = 0; i < count; ++i) {
1064 *roots[i] = ImageAddress(*roots[i]);
1065 }
1066 }
1067
1068 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1069 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001070 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001071 for (size_t i = 0; i < count; ++i) {
1072 roots[i]->Assign(ImageAddress(roots[i]->AsMirrorPtr()));
1073 }
1074 }
1075
1076 private:
1077 ImageWriter* const image_writer_;
1078
Mathieu Chartier90443472015-07-16 20:32:27 -07001079 mirror::Object* ImageAddress(mirror::Object* obj) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001080 const size_t offset = image_writer_->GetImageOffset(obj);
1081 auto* const dest = reinterpret_cast<Object*>(image_writer_->image_begin_ + offset);
1082 VLOG(compiler) << "Update root from " << obj << " to " << dest;
1083 return dest;
1084 }
1085};
1086
Mathieu Chartierc7853442015-03-27 14:35:38 -07001087void ImageWriter::CopyAndFixupNativeData() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001088 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001089 for (auto& pair : native_object_relocations_) {
1090 NativeObjectRelocation& relocation = pair.second;
1091 auto* dest = image_->Begin() + relocation.offset;
1092 DCHECK_GE(dest, image_->Begin() + image_end_);
1093 switch (relocation.type) {
1094 case kNativeObjectRelocationTypeArtField: {
1095 memcpy(dest, pair.first, sizeof(ArtField));
1096 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1097 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1098 break;
1099 }
1100 case kNativeObjectRelocationTypeArtMethodClean:
1101 case kNativeObjectRelocationTypeArtMethodDirty: {
1102 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
1103 reinterpret_cast<ArtMethod*>(dest));
1104 break;
1105 }
1106 // For arrays, copy just the header since the elements will get copied by their corresponding
1107 // relocations.
1108 case kNativeObjectRelocationTypeArtFieldArray: {
1109 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1110 break;
1111 }
1112 case kNativeObjectRelocationTypeArtMethodArrayClean:
1113 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001114 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1115 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001116 ArtMethod::Size(target_ptr_size_),
1117 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001118 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001119 case kNativeObjectRelocationTypeDexCacheArray:
1120 // Nothing to copy here, everything is done in FixupDexCache().
1121 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001122 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001123 }
1124 }
1125 // Fixup the image method roots.
1126 auto* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001127 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001128 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
1129 auto* m = image_methods_[i];
1130 CHECK(m != nullptr);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001131 auto it = native_object_relocations_.find(m);
1132 CHECK(it != native_object_relocations_.end()) << "No fowarding for " << PrettyMethod(m);
1133 NativeObjectRelocation& relocation = it->second;
1134 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001135 << methods_section;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001136 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001137 auto* dest = reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset);
1138 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), dest);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001139 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001140 // Write the intern table into the image.
1141 const ImageSection& intern_table_section = image_header->GetImageSection(
1142 ImageHeader::kSectionInternedStrings);
1143 InternTable* const intern_table = Runtime::Current()->GetInternTable();
1144 uint8_t* const memory_ptr = image_->Begin() + intern_table_section.Offset();
1145 const size_t intern_table_bytes = intern_table->WriteToMemory(memory_ptr);
1146 // Fixup the pointers in the newly written intern table to contain image addresses.
1147 InternTable temp_table;
1148 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1149 // the VisitRoots() will update the memory directly rather than the copies.
1150 // This also relies on visit roots not doing any verification which could fail after we update
1151 // the roots to be the image addresses.
1152 temp_table.ReadFromMemory(memory_ptr);
1153 CHECK_EQ(temp_table.Size(), intern_table->Size());
1154 FixupRootVisitor visitor(this);
1155 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
1156 CHECK_EQ(intern_table_bytes, intern_table_bytes_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001157}
1158
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001159void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001160 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001161 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1162 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001163 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001164 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001165 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1166 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001167 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001168 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001169}
1170
Mathieu Chartier590fee92013-09-13 13:46:47 -07001171void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001172 DCHECK(obj != nullptr);
1173 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001174 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1175}
1176
Mathieu Chartiere401d142015-04-22 13:56:20 -07001177void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1178 mirror::Class* klass, Bin array_type) {
1179 CHECK(klass->IsArrayClass());
1180 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1181 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001182 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001183 dst->SetClass(GetImageAddress(arr->GetClass()));
1184 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001185 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001186 auto* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1187 if (elem != nullptr) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001188 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001189 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001190 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001191 auto* method = reinterpret_cast<ArtMethod*>(elem);
1192 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1193 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1194 << PrettyClass(method->GetDeclaringClass());
1195 } else {
1196 CHECK_EQ(array_type, kBinArtField);
1197 auto* field = reinterpret_cast<ArtField*>(elem);
1198 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1199 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1200 << PrettyClass(field->GetDeclaringClass());
1201 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001202 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001203 } else {
1204 elem = image_begin_ + it->second.offset;
1205 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001206 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001207 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001208 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001209}
1210
1211void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001212 size_t offset = GetImageOffset(obj);
1213 auto* dst = reinterpret_cast<Object*>(image_->Begin() + offset);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001214 DCHECK_LT(offset, image_end_);
1215 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001216
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001217 image_bitmap_->Set(dst); // Mark the obj as live.
1218
1219 const size_t n = obj->SizeOf();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001220 DCHECK_LE(offset + n, image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001221 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001222
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001223 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1224 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001225 const auto it = saved_hashcode_map_.find(obj);
1226 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1227 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001228 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001229}
1230
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001231// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001232class FixupVisitor {
1233 public:
1234 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1235 }
1236
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001237 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1238 // with other logic.
1239 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1240 const {}
1241 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1242
1243
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001244 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001245 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001246 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001247 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1248 // image.
1249 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001250 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001251 }
1252
1253 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001254 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001255 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001256 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001257 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001258 }
1259
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001260 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001261 ImageWriter* const image_writer_;
1262 mirror::Object* const copy_;
1263};
1264
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001265class FixupClassVisitor FINAL : public FixupVisitor {
1266 public:
1267 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1268 }
1269
Mathieu Chartierc7853442015-03-27 14:35:38 -07001270 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001271 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001272 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001273 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001274 }
1275
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001276 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1277 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001278 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001279 LOG(FATAL) << "Reference not expected here.";
1280 }
1281};
1282
Vladimir Marko05792b92015-08-03 11:56:49 +01001283uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1284 DCHECK(obj != nullptr);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001285 auto it = native_object_relocations_.find(obj);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001286 CHECK(it != native_object_relocations_.end()) << obj;
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001287 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001288 return relocation.offset;
1289}
1290
1291template <typename T>
1292T* ImageWriter::NativeLocationInImage(T* obj) {
1293 if (obj == nullptr) {
1294 return nullptr;
1295 }
1296 return reinterpret_cast<T*>(image_begin_ + NativeOffsetInImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001297}
1298
Mathieu Chartierc7853442015-03-27 14:35:38 -07001299void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001300 // Update the field arrays.
Vladimir Marko05792b92015-08-03 11:56:49 +01001301 copy->SetSFieldsPtrUnchecked(NativeLocationInImage(orig->GetSFieldsPtr()));
1302 copy->SetIFieldsPtrUnchecked(NativeLocationInImage(orig->GetIFieldsPtr()));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001303 // Update direct and virtual method arrays.
Vladimir Marko05792b92015-08-03 11:56:49 +01001304 copy->SetDirectMethodsPtrUnchecked(NativeLocationInImage(orig->GetDirectMethodsPtr()));
1305 copy->SetVirtualMethodsPtr(NativeLocationInImage(orig->GetVirtualMethodsPtr()));
1306 // Update dex cache strings.
1307 copy->SetDexCacheStrings(NativeLocationInImage(orig->GetDexCacheStrings()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001308 // Fix up embedded tables.
1309 if (orig->ShouldHaveEmbeddedImtAndVTable()) {
1310 for (int32_t i = 0; i < orig->GetEmbeddedVTableLength(); ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001311 auto it = native_object_relocations_.find(orig->GetEmbeddedVTableEntry(i, target_ptr_size_));
1312 CHECK(it != native_object_relocations_.end()) << PrettyClass(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001313 copy->SetEmbeddedVTableEntryUnchecked(
1314 i, reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset), target_ptr_size_);
1315 }
1316 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001317 auto it = native_object_relocations_.find(orig->GetEmbeddedImTableEntry(i, target_ptr_size_));
1318 CHECK(it != native_object_relocations_.end()) << PrettyClass(orig);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001319 copy->SetEmbeddedImTableEntry(
1320 i, reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset), target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001321 }
1322 }
1323 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001324 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001325}
1326
Ian Rogersef7d42f2014-01-06 12:55:46 -08001327void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001328 DCHECK(orig != nullptr);
1329 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001330 if (kUseBakerOrBrooksReadBarrier) {
1331 orig->AssertReadBarrierPointer();
1332 if (kUseBrooksReadBarrier) {
1333 // Note the address 'copy' isn't the same as the image address of 'orig'.
1334 copy->SetReadBarrierPointer(GetImageAddress(orig));
1335 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1336 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001337 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001338 auto* klass = orig->GetClass();
1339 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001340 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001341 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1342 if (it != pointer_arrays_.end()) {
1343 // Should only need to fixup every pointer array exactly once.
1344 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1345 pointer_arrays_.erase(it);
1346 return;
1347 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001348 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001349 if (orig->IsClass()) {
1350 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001351 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001352 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1353 // Need to go update the ArtMethod.
1354 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1355 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1356 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001357 auto it = native_object_relocations_.find(src_method);
1358 CHECK(it != native_object_relocations_.end())
1359 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001360 dest->SetArtMethod(
1361 reinterpret_cast<ArtMethod*>(image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001362 } else if (!klass->IsArrayClass()) {
1363 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1364 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1365 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
1366 } else if (klass->IsSubClass(down_cast<mirror::Class*>(
1367 class_linker->GetClassRoot(ClassLinker::kJavaLangClassLoader)))) {
1368 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1369 // ClassLoader.
1370 down_cast<mirror::ClassLoader*>(copy)->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001371 // Also set allocator to null to be safe. The allocator is created when we create the class
1372 // table. We also never expect to unload things in the image since they are held live as
1373 // roots.
1374 down_cast<mirror::ClassLoader*>(copy)->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001375 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001376 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001377 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001378 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001379 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001380}
1381
Vladimir Marko05792b92015-08-03 11:56:49 +01001382void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1383 mirror::DexCache* copy_dex_cache) {
1384 // Though the DexCache array fields are usually treated as native pointers, we set the full
1385 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1386 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1387 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1388 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1389 if (orig_strings != nullptr) {
1390 uintptr_t copy_strings_offset = NativeOffsetInImage(orig_strings);
1391 copy_dex_cache->SetField64<false>(
1392 mirror::DexCache::StringsOffset(),
1393 static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + copy_strings_offset)));
1394 GcRoot<mirror::String>* copy_strings =
1395 reinterpret_cast<GcRoot<mirror::String>*>(image_->Begin() + copy_strings_offset);
1396 for (size_t i = 0, num = orig_dex_cache->NumStrings(); i != num; ++i) {
1397 copy_strings[i] = GcRoot<mirror::String>(GetImageAddress(orig_strings[i].Read()));
1398 }
1399 }
1400 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1401 if (orig_types != nullptr) {
1402 uintptr_t copy_types_offset = NativeOffsetInImage(orig_types);
1403 copy_dex_cache->SetField64<false>(
1404 mirror::DexCache::ResolvedTypesOffset(),
1405 static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + copy_types_offset)));
1406 GcRoot<mirror::Class>* copy_types =
1407 reinterpret_cast<GcRoot<mirror::Class>*>(image_->Begin() + copy_types_offset);
1408 for (size_t i = 0, num = orig_dex_cache->NumResolvedTypes(); i != num; ++i) {
1409 copy_types[i] = GcRoot<mirror::Class>(GetImageAddress(orig_types[i].Read()));
1410 }
1411 }
1412 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1413 if (orig_methods != nullptr) {
1414 uintptr_t copy_methods_offset = NativeOffsetInImage(orig_methods);
1415 copy_dex_cache->SetField64<false>(
1416 mirror::DexCache::ResolvedMethodsOffset(),
1417 static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + copy_methods_offset)));
1418 ArtMethod** copy_methods =
1419 reinterpret_cast<ArtMethod**>(image_->Begin() + copy_methods_offset);
1420 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1421 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
1422 ArtMethod* copy = NativeLocationInImage(orig);
1423 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1424 }
1425 }
1426 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1427 if (orig_fields != nullptr) {
1428 uintptr_t copy_fields_offset = NativeOffsetInImage(orig_fields);
1429 copy_dex_cache->SetField64<false>(
1430 mirror::DexCache::ResolvedFieldsOffset(),
1431 static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + copy_fields_offset)));
1432 ArtField** copy_fields = reinterpret_cast<ArtField**>(image_->Begin() + copy_fields_offset);
1433 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1434 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
1435 ArtField* copy = NativeLocationInImage(orig);
1436 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1437 }
1438 }
1439}
1440
Mathieu Chartiere401d142015-04-22 13:56:20 -07001441const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method, bool* quick_is_interpreted) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001442 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001443 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001444
1445 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1446 // trampoline.
1447
1448 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001449 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1450 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
1451 const uint8_t* quick_code = GetOatAddress(quick_oat_code_offset);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001452 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001453 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
1454 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001455 // We have code for a non-static or initialized method, just use the code.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001456 DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001457 } else if (quick_code == nullptr && method->IsNative() &&
1458 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1459 // Non-static or initialized native method missing compiled code, use generic JNI version.
1460 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001461 DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001462 } else if (quick_code == nullptr && !method->IsNative()) {
1463 // We don't have code at all for a non-native method, use the interpreter.
1464 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
1465 *quick_is_interpreted = true;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001466 DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001467 } else {
1468 CHECK(!method->GetDeclaringClass()->IsInitialized());
1469 // We have code for a static method, but need to go through the resolution stub for class
1470 // initialization.
1471 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001472 DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001473 }
1474 return quick_code;
1475}
1476
Mathieu Chartiere401d142015-04-22 13:56:20 -07001477const uint8_t* ImageWriter::GetQuickEntryPoint(ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001478 // Calculate the quick entry point following the same logic as FixupMethod() below.
1479 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001480 Runtime* runtime = Runtime::Current();
1481 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001482 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001483 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
1484 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001485 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
1486 } else {
1487 // We assume all methods have code. If they don't currently then we set them to the use the
1488 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1489 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1490 if (UNLIKELY(method->IsAbstract())) {
1491 return GetOatAddress(quick_to_interpreter_bridge_offset_);
1492 } else {
1493 bool quick_is_interpreted;
1494 return GetQuickCode(method, &quick_is_interpreted);
1495 }
1496 }
1497}
1498
Mathieu Chartiere401d142015-04-22 13:56:20 -07001499void ImageWriter::CopyAndFixupMethod(ArtMethod* orig, ArtMethod* copy) {
Vladimir Marko14632852015-08-17 12:07:23 +01001500 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001501
1502 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01001503
1504 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
1505 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
1506 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
1507 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001508
Ian Rogers848871b2013-08-05 10:56:33 -07001509 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1510 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07001511
Ian Rogers848871b2013-08-05 10:56:33 -07001512 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001513 Runtime* runtime = Runtime::Current();
1514 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001515 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartier2d721012014-11-10 11:08:06 -08001516 GetOatAddress(quick_resolution_trampoline_offset_), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001517 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1518 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001519 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartier2d721012014-11-10 11:08:06 -08001520 GetOatAddress(quick_imt_conflict_trampoline_offset_), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001521 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
1522 bool found_one = false;
1523 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
1524 auto idx = static_cast<Runtime::CalleeSaveType>(i);
1525 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
1526 found_one = true;
1527 break;
1528 }
1529 }
1530 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
1531 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001532 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001533 // We assume all methods have code. If they don't currently then we set them to the use the
1534 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1535 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1536 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001537 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartier2d721012014-11-10 11:08:06 -08001538 GetOatAddress(quick_to_interpreter_bridge_offset_), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001539 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001540 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -07001541 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001542 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001543
Sebastien Hertze1d07812014-05-21 15:44:09 +02001544 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001545 if (orig->IsNative()) {
1546 // The native method's pointer is set to a stub to lookup via dlsym.
1547 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001548 copy->SetEntryPointFromJniPtrSize(
1549 GetOatAddress(jni_dlsym_lookup_offset_), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001550 }
1551 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001552 }
1553}
1554
Alex Lighta59dd802014-07-02 16:28:08 -07001555static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001556 uint64_t data_sec_offset;
1557 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1558 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001559 return nullptr;
1560 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001561 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001562}
1563
Vladimir Markof4da6752014-08-01 19:04:18 +01001564void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001565 std::string error_msg;
1566 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
1567 MAP_SHARED, &error_msg));
1568 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001569 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001570 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001571 }
Alex Lighta59dd802014-07-02 16:28:08 -07001572 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1573 CHECK(oat_header != nullptr);
1574 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001575
Brian Carlstrom7940e442013-07-12 13:46:57 -07001576 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001577 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001578}
1579
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001580size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1581 DCHECK_LE(up_to, kBinSize);
1582 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1583}
1584
1585ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1586 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07001587 static_assert(kBinBits == 3, "wrong number of bin bits");
1588 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001589 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1590
1591 DCHECK_LT(GetBin(), kBinSize);
1592 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1593}
1594
1595ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1596 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1597 DCHECK_EQ(index, GetIndex());
1598}
1599
1600ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1601 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1602}
1603
1604uint32_t ImageWriter::BinSlot::GetIndex() const {
1605 return lockword_ & ~kBinMask;
1606}
1607
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001608uint8_t* ImageWriter::GetOatFileBegin() const {
1609 DCHECK_GT(intern_table_bytes_, 0u);
Vladimir Marko05792b92015-08-03 11:56:49 +01001610 size_t native_sections_size =
1611 bin_slot_sizes_[kBinArtField] + bin_slot_sizes_[kBinArtMethodDirty] +
1612 bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinDexCacheArray] +
1613 intern_table_bytes_;
1614 return image_begin_ + RoundUp(image_end_ + native_sections_size, kPageSize);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001615}
1616
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001617ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
1618 switch (type) {
1619 case kNativeObjectRelocationTypeArtField:
1620 case kNativeObjectRelocationTypeArtFieldArray:
1621 return kBinArtField;
1622 case kNativeObjectRelocationTypeArtMethodClean:
1623 case kNativeObjectRelocationTypeArtMethodArrayClean:
1624 return kBinArtMethodClean;
1625 case kNativeObjectRelocationTypeArtMethodDirty:
1626 case kNativeObjectRelocationTypeArtMethodArrayDirty:
1627 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01001628 case kNativeObjectRelocationTypeDexCacheArray:
1629 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001630 }
1631 UNREACHABLE();
1632}
1633
Brian Carlstrom7940e442013-07-12 13:46:57 -07001634} // namespace art