blob: a99ef3470dde7df683b7b4a91ccd4196f35c2abc [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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070026#include "base/logging.h"
27#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010028#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070029#include "compiled_method.h"
30#include "dex_file-inl.h"
31#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070032#include "elf_file.h"
33#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070034#include "elf_writer.h"
35#include "gc/accounting/card_table-inl.h"
36#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070037#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "gc/heap.h"
39#include "gc/space/large_object_space.h"
40#include "gc/space/space-inl.h"
41#include "globals.h"
42#include "image.h"
43#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070044#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070045#include "lock_word.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070046#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070047#include "mirror/array-inl.h"
48#include "mirror/class-inl.h"
49#include "mirror/class_loader.h"
50#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "mirror/object-inl.h"
52#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070053#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "oat.h"
55#include "oat_file.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "runtime.h"
57#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070058#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000059#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060
Brian Carlstromea46f952013-07-30 01:26:50 -070061using ::art::mirror::ArtMethod;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070062using ::art::mirror::Class;
63using ::art::mirror::DexCache;
64using ::art::mirror::EntryPointFromInterpreter;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070065using ::art::mirror::Object;
66using ::art::mirror::ObjectArray;
67using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070068
69namespace art {
70
Igor Murashkinf5b4c502014-11-14 15:01:59 -080071// Separate objects into multiple bins to optimize dirty memory use.
72static constexpr bool kBinObjects = true;
Mathieu Chartierde486922015-04-15 20:03:16 -070073static constexpr bool kComputeEagerResolvedStrings = false;
Igor Murashkinf5b4c502014-11-14 15:01:59 -080074
Andreas Gampedd9d0552015-03-09 12:57:41 -070075static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
76 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
77 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 {
89 Thread::Current()->TransitionFromSuspendedToRunnable();
90 PruneNonImageClasses(); // Remove junk
91 ComputeLazyFieldsForImageClasses(); // Add useful information
Vladimir Marko3389ca72014-12-03 14:35:54 +000092 ProcessStrings();
Vladimir Markof4da6752014-08-01 19:04:18 +010093 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
94 }
95 gc::Heap* heap = Runtime::Current()->GetHeap();
96 heap->CollectGarbage(false); // Remove garbage.
97
Andreas Gampedd9d0552015-03-09 12:57:41 -070098 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
99 // dex files.
100 //
101 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
102 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
103 // true.
104 if (kIsDebugBuild) {
105 CheckNoDexObjects();
106 }
107
Vladimir Markof4da6752014-08-01 19:04:18 +0100108 if (!AllocMemory()) {
109 return false;
110 }
111
112 if (kIsDebugBuild) {
113 ScopedObjectAccess soa(Thread::Current());
114 CheckNonImageClassesRemoved();
115 }
116
117 Thread::Current()->TransitionFromSuspendedToRunnable();
118 CalculateNewObjectOffsets();
119 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
120
121 return true;
122}
123
Brian Carlstrom7940e442013-07-12 13:46:57 -0700124bool ImageWriter::Write(const std::string& image_filename,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700125 const std::string& oat_filename,
126 const std::string& oat_location) {
127 CHECK(!image_filename.empty());
128
Brian Carlstrom7940e442013-07-12 13:46:57 -0700129 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700130
Ian Rogers700a4022014-05-19 16:49:03 -0700131 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700132 if (oat_file.get() == NULL) {
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;
Richard Uhlere5fed032015-03-18 08:21:11 -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 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700144 CHECK_EQ(class_linker->RegisterOatFile(oat_file_), oat_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700145
Ian Rogers848871b2013-08-05 10:56:33 -0700146 interpreter_to_interpreter_bridge_offset_ =
147 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
148 interpreter_to_compiled_code_bridge_offset_ =
149 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
150
151 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
152
Andreas Gampe2da88232014-02-27 12:26:20 -0800153 quick_generic_jni_trampoline_offset_ =
154 oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
Jeff Hao88474b42013-10-23 16:24:40 -0700155 quick_imt_conflict_trampoline_offset_ =
156 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700157 quick_resolution_trampoline_offset_ =
158 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
159 quick_to_interpreter_bridge_offset_ =
160 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700161
Brian Carlstrom7940e442013-07-12 13:46:57 -0700162 size_t oat_loaded_size = 0;
163 size_t oat_data_offset = 0;
164 ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
Alex Light53cb16b2014-06-12 11:26:29 -0700165
Vladimir Markof4da6752014-08-01 19:04:18 +0100166 Thread::Current()->TransitionFromSuspendedToRunnable();
167 CreateHeader(oat_loaded_size, oat_data_offset);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700168 // TODO: heap validation can't handle these fix up passes.
169 Runtime::Current()->GetHeap()->DisableObjectValidation();
170 CopyAndFixupNativeData();
Vladimir Markof4da6752014-08-01 19:04:18 +0100171 CopyAndFixupObjects();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700172 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
173
Vladimir Markof4da6752014-08-01 19:04:18 +0100174 SetOatChecksumFromElfFile(oat_file.get());
175
Andreas Gampe4303ba92014-11-06 01:00:46 -0800176 if (oat_file->FlushCloseOrErase() != 0) {
177 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename << " for " << oat_location;
178 return false;
179 }
180
Ian Rogers700a4022014-05-19 16:49:03 -0700181 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700182 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700183 if (image_file.get() == NULL) {
184 LOG(ERROR) << "Failed to open image file " << image_filename;
185 return false;
186 }
187 if (fchmod(image_file->Fd(), 0644) != 0) {
188 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800189 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190 return EXIT_FAILURE;
191 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700192
Mathieu Chartierc7853442015-03-27 14:35:38 -0700193 // Write out the image + fields.
194 const auto write_count = image_header->GetImageSize() + image_header->GetArtFieldsSize();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700195 CHECK_EQ(image_end_, image_header->GetImageSize());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700196 if (!image_file->WriteFully(image_->Begin(), write_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700197 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800198 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700199 return false;
200 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700201
202 // Write out the image bitmap at the page aligned start of the image end.
203 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
204 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
205 image_header->GetImageBitmapSize(),
206 image_header->GetImageBitmapOffset())) {
207 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800208 image_file->Erase();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700209 return false;
210 }
211
Mathieu Chartierc7853442015-03-27 14:35:38 -0700212 CHECK_EQ(image_header->GetImageBitmapOffset() + image_header->GetImageBitmapSize(),
213 static_cast<size_t>(image_file->GetLength()));
Andreas Gampe4303ba92014-11-06 01:00:46 -0800214 if (image_file->FlushCloseOrErase() != 0) {
215 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
216 return false;
217 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 return true;
219}
220
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800221void ImageWriter::SetImageOffset(mirror::Object* object,
222 ImageWriter::BinSlot bin_slot,
223 size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700224 DCHECK(object != nullptr);
225 DCHECK_NE(offset, 0U);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700226 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
227 DCHECK_ALIGNED(obj, kObjectAlignment);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800228
Mathieu Chartierc7853442015-03-27 14:35:38 -0700229 static size_t max_offset = 0;
230 max_offset = std::max(max_offset, offset);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800231 image_bitmap_->Set(obj); // Mark the obj as mutated, since we will end up changing it.
232 {
233 // Remember the object-inside-of-the-image's hash code so we can restore it after the copy.
234 auto hash_it = saved_hashes_map_.find(bin_slot);
235 if (hash_it != saved_hashes_map_.end()) {
236 std::pair<BinSlot, uint32_t> slot_hash = *hash_it;
237 saved_hashes_.push_back(std::make_pair(obj, slot_hash.second));
238 saved_hashes_map_.erase(hash_it);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700239 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700240 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800241 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700242 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700243 DCHECK(IsImageOffsetAssigned(object));
244}
245
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800246void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700247 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800248 DCHECK_NE(image_objects_offset_begin_, 0u);
249
Vladimir Marko20f85592015-03-19 10:07:02 +0000250 size_t previous_bin_sizes = bin_slot_previous_sizes_[bin_slot.GetBin()];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800251 size_t new_offset = image_objects_offset_begin_ + previous_bin_sizes + bin_slot.GetIndex();
252 DCHECK_ALIGNED(new_offset, kObjectAlignment);
253
254 SetImageOffset(object, bin_slot, new_offset);
255 DCHECK_LT(new_offset, image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700256}
257
Ian Rogersef7d42f2014-01-06 12:55:46 -0800258bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800259 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700260 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700261 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700262}
263
Ian Rogersef7d42f2014-01-06 12:55:46 -0800264size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700265 DCHECK(object != nullptr);
266 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700267 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700268 size_t offset = lock_word.ForwardingAddress();
269 DCHECK_LT(offset, image_end_);
270 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700271}
272
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800273void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
274 DCHECK(object != nullptr);
275 DCHECK(!IsImageOffsetAssigned(object));
276 DCHECK(!IsImageBinSlotAssigned(object));
277
278 // Before we stomp over the lock word, save the hash code for later.
279 Monitor::Deflate(Thread::Current(), object);;
280 LockWord lw(object->GetLockWord(false));
281 switch (lw.GetState()) {
282 case LockWord::kFatLocked: {
283 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
284 break;
285 }
286 case LockWord::kThinLocked: {
287 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
288 break;
289 }
290 case LockWord::kUnlocked:
291 // No hash, don't need to save it.
292 break;
293 case LockWord::kHashCode:
294 saved_hashes_map_[bin_slot] = lw.GetHashCode();
295 break;
296 default:
297 LOG(FATAL) << "Unreachable.";
298 UNREACHABLE();
299 }
300 object->SetLockWord(LockWord::FromForwardingAddress(static_cast<uint32_t>(bin_slot)),
301 false);
302 DCHECK(IsImageBinSlotAssigned(object));
303}
304
Vladimir Marko20f85592015-03-19 10:07:02 +0000305void ImageWriter::PrepareDexCacheArraySlots() {
306 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
307 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
308 size_t dex_cache_count = class_linker->GetDexCacheCount();
309 uint32_t size = 0u;
310 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
311 DexCache* dex_cache = class_linker->GetDexCache(idx);
312 const DexFile* dex_file = dex_cache->GetDexFile();
313 dex_cache_array_starts_.Put(dex_file, size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700314 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000315 DCHECK(layout.Valid());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700316 auto types_size = layout.TypesSize(dex_file->NumTypeIds());
317 auto methods_size = layout.MethodsSize(dex_file->NumMethodIds());
318 auto fields_size = layout.FieldsSize(dex_file->NumFieldIds());
319 auto strings_size = layout.StringsSize(dex_file->NumStringIds());
320 dex_cache_array_indexes_.Put(
321 dex_cache->GetResolvedTypes(),
322 DexCacheArrayLocation {size + layout.TypesOffset(), types_size});
323 dex_cache_array_indexes_.Put(
324 dex_cache->GetResolvedMethods(),
325 DexCacheArrayLocation {size + layout.MethodsOffset(), methods_size});
326 dex_cache_array_indexes_.Put(
327 dex_cache->GetResolvedFields(),
328 DexCacheArrayLocation {size + layout.FieldsOffset(), fields_size});
329 dex_cache_array_indexes_.Put(
330 dex_cache->GetStrings(),
331 DexCacheArrayLocation {size + layout.StringsOffset(), strings_size});
Vladimir Marko20f85592015-03-19 10:07:02 +0000332 size += layout.Size();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700333 CHECK_EQ(layout.Size(), types_size + methods_size + fields_size + strings_size);
Vladimir Marko20f85592015-03-19 10:07:02 +0000334 }
335 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
336 // when AssignImageBinSlot() assigns their indexes out or order.
337 bin_slot_sizes_[kBinDexCacheArray] = size;
338}
339
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800340void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
341 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800342 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800343
344 // The magic happens here. We segregate objects into different bins based
345 // on how likely they are to get dirty at runtime.
346 //
347 // Likely-to-dirty objects get packed together into the same bin so that
348 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
349 // maximized.
350 //
351 // This means more pages will stay either clean or shared dirty (with zygote) and
352 // the app will use less of its own (private) memory.
353 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000354 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800355
356 if (kBinObjects) {
357 //
358 // Changing the bin of an object is purely a memory-use tuning.
359 // It has no change on runtime correctness.
360 //
361 // Memory analysis has determined that the following types of objects get dirtied
362 // the most:
363 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000364 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
365 // a fixed layout which helps improve generated code (using PC-relative addressing),
366 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
367 // Since these arrays are huge, most pages do not overlap other objects and it's not
368 // really important where they are for the clean/dirty separation. Due to their
369 // special PC-relative addressing, we arbitrarily keep them at the beginning.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800370 // * Class'es which are verified [their clinit runs only at runtime]
371 // - classes in general [because their static fields get overwritten]
372 // - initialized classes with all-final statics are unlikely to be ever dirty,
373 // so bin them separately
374 // * Art Methods that are:
375 // - native [their native entry point is not looked up until runtime]
376 // - have declaring classes that aren't initialized
377 // [their interpreter/quick entry points are trampolines until the class
378 // becomes initialized]
379 //
380 // We also assume the following objects get dirtied either never or extremely rarely:
381 // * Strings (they are immutable)
382 // * Art methods that aren't native and have initialized declared classes
383 //
384 // We assume that "regular" bin objects are highly unlikely to become dirtied,
385 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
386 //
387 if (object->IsClass()) {
388 bin = kBinClassVerified;
389 mirror::Class* klass = object->AsClass();
390
391 if (klass->GetStatus() == Class::kStatusInitialized) {
392 bin = kBinClassInitialized;
393
394 // If the class's static fields are all final, put it into a separate bin
395 // since it's very likely it will stay clean.
396 uint32_t num_static_fields = klass->NumStaticFields();
397 if (num_static_fields == 0) {
398 bin = kBinClassInitializedFinalStatics;
399 } else {
400 // Maybe all the statics are final?
401 bool all_final = true;
402 for (uint32_t i = 0; i < num_static_fields; ++i) {
403 ArtField* field = klass->GetStaticField(i);
404 if (!field->IsFinal()) {
405 all_final = false;
406 break;
407 }
408 }
409
410 if (all_final) {
411 bin = kBinClassInitializedFinalStatics;
412 }
413 }
414 }
415 } else if (object->IsArtMethod<kVerifyNone>()) {
416 mirror::ArtMethod* art_method = down_cast<ArtMethod*>(object);
417 if (art_method->IsNative()) {
418 bin = kBinArtMethodNative;
419 } else {
420 mirror::Class* declaring_class = art_method->GetDeclaringClass();
421 if (declaring_class->GetStatus() != Class::kStatusInitialized) {
422 bin = kBinArtMethodNotInitialized;
423 } else {
424 // This is highly unlikely to dirty since there's no entry points to mutate.
425 bin = kBinArtMethodsManagedInitialized;
426 }
427 }
428 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
429 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartierc7853442015-03-27 14:35:38 -0700430 } else if (object->IsArrayInstance()) {
431 mirror::Class* klass = object->GetClass<kVerifyNone>();
432 auto* component_type = klass->GetComponentType();
433 if (!component_type->IsPrimitive() || component_type->IsPrimitiveInt() ||
434 component_type->IsPrimitiveLong()) {
435 auto it = dex_cache_array_indexes_.find(object);
436 if (it != dex_cache_array_indexes_.end()) {
437 bin = kBinDexCacheArray;
438 // Use prepared offset defined by the DexCacheLayout.
439 current_offset = it->second.offset_;
440 // Override incase of cross compilation.
441 object_size = it->second.length_;
442 } // else bin = kBinRegular
443 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800444 } // else bin = kBinRegular
445 }
446
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800447 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Vladimir Marko20f85592015-03-19 10:07:02 +0000448 if (bin != kBinDexCacheArray) {
449 current_offset = bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
450 // Move the current bin size up to accomodate the object we just assigned a bin slot.
451 bin_slot_sizes_[bin] += offset_delta;
452 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800453
454 BinSlot new_bin_slot(bin, current_offset);
455 SetImageBinSlot(object, new_bin_slot);
456
457 ++bin_slot_count_[bin];
458
459 DCHECK_LT(GetBinSizeSum(), image_->Size());
460
461 // Grow the image closer to the end by the object we just assigned.
462 image_end_ += offset_delta;
463 DCHECK_LT(image_end_, image_->Size());
464}
465
466bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
467 DCHECK(object != nullptr);
468
469 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
470 // If it's in some other state, then we haven't yet assigned an image bin slot.
471 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
472 return false;
473 } else if (kIsDebugBuild) {
474 LockWord lock_word = object->GetLockWord(false);
475 size_t offset = lock_word.ForwardingAddress();
476 BinSlot bin_slot(offset);
477 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()])
478 << "bin slot offset should not exceed the size of that bin";
479 }
480 return true;
481}
482
483ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
484 DCHECK(object != nullptr);
485 DCHECK(IsImageBinSlotAssigned(object));
486
487 LockWord lock_word = object->GetLockWord(false);
488 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
489 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
490
491 BinSlot bin_slot(static_cast<uint32_t>(offset));
492 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()]);
493
494 return bin_slot;
495}
496
Brian Carlstrom7940e442013-07-12 13:46:57 -0700497bool ImageWriter::AllocMemory() {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700498 auto* runtime = Runtime::Current();
499 const size_t heap_size = runtime->GetHeap()->GetTotalMemory();
500 // Add linear alloc usage since we need to have room for the ArtFields.
501 const size_t length = RoundUp(heap_size + runtime->GetLinearAlloc()->GetUsedMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700502 std::string error_msg;
Vladimir Marko5c42c292015-02-25 12:02:49 +0000503 image_.reset(MemMap::MapAnonymous("image writer image", nullptr, length, PROT_READ | PROT_WRITE,
504 false, false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700505 if (UNLIKELY(image_.get() == nullptr)) {
506 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700507 return false;
508 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700509
510 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700511 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
Mathieu Chartierc7853442015-03-27 14:35:38 -0700512 RoundUp(length, kPageSize)));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700513 if (image_bitmap_.get() == nullptr) {
514 LOG(ERROR) << "Failed to allocate memory for image bitmap";
515 return false;
516 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700517 return true;
518}
519
520void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700521 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700522 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
523}
524
525bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700526 Thread* self = Thread::Current();
527 StackHandleScope<1> hs(self);
528 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700529 return true;
530}
531
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800532// Count the number of strings in the heap and put the result in arg as a size_t pointer.
533static void CountStringsCallback(Object* obj, void* arg)
534 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
535 if (obj->GetClass()->IsStringClass()) {
536 ++*reinterpret_cast<size_t*>(arg);
537 }
538}
539
540// Collect all the java.lang.String in the heap and put them in the output strings_ array.
541class StringCollector {
542 public:
543 StringCollector(Handle<mirror::ObjectArray<mirror::String>> strings, size_t index)
544 : strings_(strings), index_(index) {
545 }
546 static void Callback(Object* obj, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
547 auto* collector = reinterpret_cast<StringCollector*>(arg);
548 if (obj->GetClass()->IsStringClass()) {
549 collector->strings_->SetWithoutChecks<false>(collector->index_++, obj->AsString());
550 }
551 }
552 size_t GetIndex() const {
553 return index_;
554 }
555
556 private:
557 Handle<mirror::ObjectArray<mirror::String>> strings_;
558 size_t index_;
559};
560
561// Compare strings based on length, used for sorting strings by length / reverse length.
Vladimir Markofaeda182014-12-04 14:52:25 +0000562class LexicographicalStringComparator {
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800563 public:
Vladimir Markofaeda182014-12-04 14:52:25 +0000564 bool operator()(const mirror::HeapReference<mirror::String>& lhs,
565 const mirror::HeapReference<mirror::String>& rhs) const
566 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
567 mirror::String* lhs_s = lhs.AsMirrorPtr();
568 mirror::String* rhs_s = rhs.AsMirrorPtr();
569 uint16_t* lhs_begin = lhs_s->GetCharArray()->GetData() + lhs_s->GetOffset();
570 uint16_t* rhs_begin = rhs_s->GetCharArray()->GetData() + rhs_s->GetOffset();
571 return std::lexicographical_compare(lhs_begin, lhs_begin + lhs_s->GetLength(),
572 rhs_begin, rhs_begin + rhs_s->GetLength());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800573 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800574};
575
Vladimir Markofaeda182014-12-04 14:52:25 +0000576static bool IsPrefix(mirror::String* pref, mirror::String* full)
577 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
578 if (pref->GetLength() > full->GetLength()) {
579 return false;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800580 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000581 uint16_t* pref_begin = pref->GetCharArray()->GetData() + pref->GetOffset();
582 uint16_t* full_begin = full->GetCharArray()->GetData() + full->GetOffset();
583 return std::equal(pref_begin, pref_begin + pref->GetLength(), full_begin);
584}
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800585
586void ImageWriter::ProcessStrings() {
587 size_t total_strings = 0;
588 gc::Heap* heap = Runtime::Current()->GetHeap();
589 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800590 // Count the strings.
591 heap->VisitObjects(CountStringsCallback, &total_strings);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800592 Thread* self = Thread::Current();
593 StackHandleScope<1> hs(self);
594 auto strings = hs.NewHandle(cl->AllocStringArray(self, total_strings));
595 StringCollector string_collector(strings, 0U);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800596 // Read strings into the array.
597 heap->VisitObjects(StringCollector::Callback, &string_collector);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800598 // Some strings could have gotten freed if AllocStringArray caused a GC.
599 CHECK_LE(string_collector.GetIndex(), total_strings);
600 total_strings = string_collector.GetIndex();
Vladimir Markofaeda182014-12-04 14:52:25 +0000601 auto* strings_begin = reinterpret_cast<mirror::HeapReference<mirror::String>*>(
602 strings->GetRawData(sizeof(mirror::HeapReference<mirror::String>), 0));
603 std::sort(strings_begin, strings_begin + total_strings, LexicographicalStringComparator());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800604 // Characters of strings which are non equal prefix of another string (not the same string).
605 // We don't count the savings from equal strings since these would get interned later anyways.
606 size_t prefix_saved_chars = 0;
Vladimir Markofaeda182014-12-04 14:52:25 +0000607 // Count characters needed for the strings.
608 size_t num_chars = 0u;
609 mirror::String* prev_s = nullptr;
610 for (size_t idx = 0; idx != total_strings; ++idx) {
611 mirror::String* s = strings->GetWithoutChecks(idx);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800612 size_t length = s->GetLength();
Vladimir Markofaeda182014-12-04 14:52:25 +0000613 num_chars += length;
614 if (prev_s != nullptr && IsPrefix(prev_s, s)) {
615 size_t prev_length = prev_s->GetLength();
616 num_chars -= prev_length;
617 if (prev_length != length) {
618 prefix_saved_chars += prev_length;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800619 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800620 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000621 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800622 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000623 // Create character array, copy characters and point the strings there.
624 mirror::CharArray* array = mirror::CharArray::Alloc(self, num_chars);
Andreas Gampe245ee002014-12-04 21:25:04 -0800625 string_data_array_ = array;
Vladimir Markofaeda182014-12-04 14:52:25 +0000626 uint16_t* array_data = array->GetData();
627 size_t pos = 0u;
628 prev_s = nullptr;
629 for (size_t idx = 0; idx != total_strings; ++idx) {
630 mirror::String* s = strings->GetWithoutChecks(idx);
631 uint16_t* s_data = s->GetCharArray()->GetData() + s->GetOffset();
632 int32_t s_length = s->GetLength();
633 int32_t prefix_length = 0u;
634 if (idx != 0u && IsPrefix(prev_s, s)) {
635 prefix_length = prev_s->GetLength();
636 }
637 memcpy(array_data + pos, s_data + prefix_length, (s_length - prefix_length) * sizeof(*s_data));
638 s->SetOffset(pos - prefix_length);
639 s->SetArray(array);
640 pos += s_length - prefix_length;
641 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800642 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000643 CHECK_EQ(pos, num_chars);
644
Andreas Gampedc843012015-01-20 16:17:19 -0800645 if (kIsDebugBuild || VLOG_IS_ON(compiler)) {
646 LOG(INFO) << "Total # image strings=" << total_strings << " combined length="
647 << num_chars << " prefix saved chars=" << prefix_saved_chars;
648 }
Mathieu Chartierde486922015-04-15 20:03:16 -0700649 // Calling this can in theory fill in some resolved strings. However, in practice it seems to
650 // never resolve any.
651 if (kComputeEagerResolvedStrings) {
652 ComputeEagerResolvedStrings();
653 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800654}
655
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700656void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700657 if (!obj->GetClass()->IsStringClass()) {
658 return;
659 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700660 mirror::String* string = obj->AsString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700661 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
Vladimir Markoa48aef42014-12-03 17:53:53 +0000662 size_t utf16_length = static_cast<size_t>(string->GetLength());
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700663 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
664 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
665 size_t dex_cache_count = class_linker->GetDexCacheCount();
666 for (size_t i = 0; i < dex_cache_count; ++i) {
667 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700668 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800669 const DexFile::StringId* string_id;
Vladimir Markoa48aef42014-12-03 17:53:53 +0000670 if (UNLIKELY(utf16_length == 0)) {
Ian Rogers24c534d2013-11-14 00:15:00 -0800671 string_id = dex_file.FindStringId("");
672 } else {
Vladimir Markoa48aef42014-12-03 17:53:53 +0000673 string_id = dex_file.FindStringId(utf16_string, utf16_length);
Ian Rogers24c534d2013-11-14 00:15:00 -0800674 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700675 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700676 // This string occurs in this dex file, assign the dex cache entry.
677 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
678 if (dex_cache->GetResolvedString(string_idx) == NULL) {
679 dex_cache->SetResolvedString(string_idx, string);
680 }
681 }
682 }
683}
684
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800685void ImageWriter::ComputeEagerResolvedStrings() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700686 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700687}
688
Ian Rogersef7d42f2014-01-06 12:55:46 -0800689bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700690 std::string temp;
691 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700692}
693
694struct NonImageClasses {
695 ImageWriter* image_writer;
696 std::set<std::string>* non_image_classes;
697};
698
699void ImageWriter::PruneNonImageClasses() {
700 if (compiler_driver_.GetImageClasses() == NULL) {
701 return;
702 }
703 Runtime* runtime = Runtime::Current();
704 ClassLinker* class_linker = runtime->GetClassLinker();
705
706 // Make a list of classes we would like to prune.
707 std::set<std::string> non_image_classes;
708 NonImageClasses context;
709 context.image_writer = this;
710 context.non_image_classes = &non_image_classes;
711 class_linker->VisitClasses(NonImageClassesVisitor, &context);
712
713 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700714 for (const std::string& it : non_image_classes) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800715 bool result = class_linker->RemoveClass(it.c_str(), NULL);
716 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700717 }
718
719 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700720 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700721 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
722 size_t dex_cache_count = class_linker->GetDexCacheCount();
723 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
724 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700725 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
726 Class* klass = dex_cache->GetResolvedType(i);
727 if (klass != NULL && !IsImageClass(klass)) {
728 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700729 }
730 }
731 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700732 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700733 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
734 dex_cache->SetResolvedMethod(i, resolution_method);
735 }
736 }
737 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700738 ArtField* field = dex_cache->GetResolvedField(i, sizeof(void*));
739 if (field != nullptr && !IsImageClass(field->GetDeclaringClass())) {
740 dex_cache->SetResolvedField(i, nullptr, sizeof(void*));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700741 }
742 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700743 // Clean the dex field. It might have been populated during the initialization phase, but
744 // contains data only valid during a real run.
745 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700746 }
747}
748
749bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
750 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
751 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700752 std::string temp;
753 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700754 }
755 return true;
756}
757
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800758void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700759 if (compiler_driver_.GetImageClasses() != nullptr) {
760 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700761 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700762 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700763}
764
765void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
766 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700767 if (obj->IsClass()) {
768 Class* klass = obj->AsClass();
769 if (!image_writer->IsImageClass(klass)) {
770 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700771 std::string temp;
772 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700773 << " " << PrettyDescriptor(klass);
774 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700775 }
776}
777
778void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700779 auto image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700780 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700781 for (const std::string& image_class : *image_classes) {
782 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700783 }
784}
785
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800786void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700787 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700788 // if it is a string, we want to intern it if its not interned.
789 if (obj->GetClass()->IsStringClass()) {
790 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800791 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700792 DCHECK_EQ(obj, obj->AsString()->Intern());
793 return;
794 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700795 mirror::String* const interned = obj->AsString()->Intern();
796 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800797 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700798 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800799 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700800 }
801 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800802 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700803 return;
804 }
805 // else (obj == interned), nothing to do but fall through to the normal case
806 }
807
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800808 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700809}
810
811ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
812 Runtime* runtime = Runtime::Current();
813 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700814 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700815 StackHandleScope<3> hs(self);
816 Handle<Class> object_array_class(hs.NewHandle(
817 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700818
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700819 // build an Object[] of all the DexCaches used in the source_space_.
820 // Since we can't hold the dex lock when allocating the dex_caches
821 // ObjectArray, we lock the dex lock twice, first to get the number
822 // of dex caches first and then lock it again to copy the dex
823 // caches. We check that the number of dex caches does not change.
824 size_t dex_cache_count;
825 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700826 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700827 dex_cache_count = class_linker->GetDexCacheCount();
828 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700829 Handle<ObjectArray<Object>> dex_caches(
830 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700831 dex_cache_count)));
832 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
833 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700834 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700835 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
836 << "The number of dex caches changed.";
837 for (size_t i = 0; i < dex_cache_count; ++i) {
838 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
839 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700840 }
841
842 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700843 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700844 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100845 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
846 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700847 image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
848 runtime->GetImtUnimplementedMethod());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100849 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
850 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
851 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
852 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
853 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
854 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
855 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700856 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100857 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700858 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
859 CHECK(image_roots->Get(i) != NULL);
860 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700861 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700862}
863
Mathieu Chartier590fee92013-09-13 13:46:47 -0700864// Walk instance fields of the given Class. Separate function to allow recursion on the super
865// class.
866void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
867 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700868 StackHandleScope<1> hs(Thread::Current());
869 Handle<mirror::Class> h_class(hs.NewHandle(klass));
870 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700871 if (super != nullptr) {
872 WalkInstanceFields(obj, super);
873 }
874 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700875 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000876 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700877 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700878 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700879 if (value != nullptr) {
880 WalkFieldsInOrder(value);
881 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000882 field_offset = MemberOffset(field_offset.Uint32Value() +
883 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700884 }
885}
886
887// For an unvisited object, visit it then all its children found via fields.
888void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800889 // Use our own visitor routine (instead of GC visitor) to get better locality between
890 // an object and its fields
891 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700892 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700893 StackHandleScope<2> hs(Thread::Current());
894 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
895 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700896 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800897 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700898 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700899 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700900 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700901 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000902 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700903 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700904 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700905 if (value != nullptr) {
906 WalkFieldsInOrder(value);
907 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000908 field_offset = MemberOffset(field_offset.Uint32Value() +
909 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700910 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700911
912 // Visit and assign offsets for fields.
913 ArtField* fields[2] = { h_obj->AsClass()->GetSFields(), h_obj->AsClass()->GetIFields() };
914 size_t num_fields[2] = { h_obj->AsClass()->NumStaticFields(),
915 h_obj->AsClass()->NumInstanceFields() };
916 for (size_t i = 0; i < 2; ++i) {
917 for (size_t j = 0; j < num_fields[i]; ++j) {
918 auto* field = fields[i] + j;
919 auto it = art_field_reloc_.find(field);
920 CHECK(it == art_field_reloc_.end()) << "Field at index " << i << ":" << j
921 << " already assigned " << PrettyField(field);
922 art_field_reloc_.emplace(field, bin_slot_sizes_[kBinArtField]);
923 bin_slot_sizes_[kBinArtField] += sizeof(ArtField);
924 }
925 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700926 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700927 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700928 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700929 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700930 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700931 mirror::Object* value = obj_array->Get(i);
932 if (value != nullptr) {
933 WalkFieldsInOrder(value);
934 }
935 }
936 }
937 }
938}
939
940void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
941 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
942 DCHECK(writer != nullptr);
943 writer->WalkFieldsInOrder(obj);
944}
945
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800946void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
947 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
948 DCHECK(writer != nullptr);
949 writer->UnbinObjectsIntoOffset(obj);
950}
951
952void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
953 CHECK(obj != nullptr);
954
955 // We know the bin slot, and the total bin sizes for all objects by now,
956 // so calculate the object's final image offset.
957
958 DCHECK(IsImageBinSlotAssigned(obj));
959 BinSlot bin_slot = GetImageBinSlot(obj);
960 // Change the lockword from a bin slot into an offset
961 AssignImageOffset(obj, bin_slot);
962}
963
Vladimir Markof4da6752014-08-01 19:04:18 +0100964void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700965 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700966 StackHandleScope<1> hs(self);
967 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700968
969 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700970 DCHECK_EQ(0U, image_end_);
971
Mathieu Chartier31e89252013-08-28 11:29:12 -0700972 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700973 // know where image_roots is going to end up
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800974 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700975
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800976 DCHECK_LT(image_end_, image_->Size());
977 image_objects_offset_begin_ = image_end_;
Vladimir Marko20f85592015-03-19 10:07:02 +0000978 // Prepare bin slots for dex cache arrays.
979 PrepareDexCacheArraySlots();
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800980 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
981 heap->VisitObjects(WalkFieldsCallback, this);
Vladimir Marko20f85592015-03-19 10:07:02 +0000982 // Calculate cumulative bin slot sizes.
983 size_t previous_sizes = 0u;
984 for (size_t i = 0; i != kBinSize; ++i) {
985 bin_slot_previous_sizes_[i] = previous_sizes;
986 previous_sizes += bin_slot_sizes_[i];
987 }
988 DCHECK_EQ(previous_sizes, GetBinSizeSum());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700989 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
990
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800991 // Transform each object's bin slot into an offset which will be used to do the final copy.
992 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
993 DCHECK(saved_hashes_map_.empty()); // All binslot hashes should've been put into vector by now.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700994
Mathieu Chartierc7853442015-03-27 14:35:38 -0700995 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800996
Vladimir Markof4da6752014-08-01 19:04:18 +0100997 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
998
Mathieu Chartierc7853442015-03-27 14:35:38 -0700999 // Note that image_end_ is left at end of used mirror space
Vladimir Markof4da6752014-08-01 19:04:18 +01001000}
1001
1002void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
1003 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -07001004 const uint8_t* oat_file_begin = GetOatFileBegin();
1005 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001006 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -07001007 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001008 // Write out sections.
1009 size_t cur_pos = image_end_;
1010 // Add fields.
1011 auto fields_offset = cur_pos;
1012 CHECK_EQ(image_objects_offset_begin_ + GetBinSizeSum(kBinArtField), fields_offset);
1013 auto fields_size = bin_slot_sizes_[kBinArtField];
1014 cur_pos += fields_size;
Mathieu Chartier31e89252013-08-28 11:29:12 -07001015 // Return to write header at start of image with future location of image_roots. At this point,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001016 // image_end_ is the size of the image (excluding bitmaps, ArtFields).
1017 /*
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001018 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -08001019 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
1020 heap_bytes_per_bitmap_byte;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001021 */
1022 const size_t bitmap_bytes = image_bitmap_->Size();
1023 auto bitmap_offset = RoundUp(cur_pos, kPageSize);
1024 auto bitmap_size = RoundUp(bitmap_bytes, kPageSize);
1025 cur_pos += bitmap_size;
Vladimir Markof4da6752014-08-01 19:04:18 +01001026 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
1027 static_cast<uint32_t>(image_end_),
Mathieu Chartierc7853442015-03-27 14:35:38 -07001028 fields_offset, fields_size,
1029 bitmap_offset, bitmap_size,
Vladimir Markof4da6752014-08-01 19:04:18 +01001030 image_roots_address_,
1031 oat_file_->GetOatHeader().GetChecksum(),
1032 PointerToLowMemUInt32(oat_file_begin),
1033 PointerToLowMemUInt32(oat_data_begin_),
1034 PointerToLowMemUInt32(oat_data_end),
Igor Murashkin46774762014-10-22 11:37:02 -07001035 PointerToLowMemUInt32(oat_file_end),
1036 compile_pic_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001037}
1038
Mathieu Chartierc7853442015-03-27 14:35:38 -07001039void ImageWriter::CopyAndFixupNativeData() {
1040 // Copy ArtFields to their locations and update the array for convenience.
1041 auto fields_offset = image_objects_offset_begin_ + GetBinSizeSum(kBinArtField);
1042 for (auto& pair : art_field_reloc_) {
1043 pair.second += fields_offset;
1044 auto* dest = image_->Begin() + pair.second;
1045 DCHECK_GE(dest, image_->Begin() + image_end_);
1046 memcpy(dest, pair.first, sizeof(ArtField));
1047 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1048 down_cast<Class*>(GetImageAddress(pair.first->GetDeclaringClass())));
1049 }
1050}
1051
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001052void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001053 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001054 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1055 // Fix up the object previously had hash codes.
1056 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001057 Object* obj = hash_pair.first;
1058 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0U);
1059 obj->SetLockWord(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001060 }
1061 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001062}
1063
Mathieu Chartier590fee92013-09-13 13:46:47 -07001064void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001065 DCHECK(obj != nullptr);
1066 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001067 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1068}
1069
1070bool ImageWriter::CopyAndFixupIfDexCacheFieldArray(mirror::Object* dst, mirror::Object* obj,
1071 mirror::Class* klass) {
1072 if (!klass->IsArrayClass()) {
1073 return false;
1074 }
1075 auto* component_type = klass->GetComponentType();
1076 bool is_int_arr = component_type->IsPrimitiveInt();
1077 bool is_long_arr = component_type->IsPrimitiveLong();
1078 if (!is_int_arr && !is_long_arr) {
1079 return false;
1080 }
1081 auto it = dex_cache_array_indexes_.find(obj); // Is this a dex cache array?
1082 if (it == dex_cache_array_indexes_.end()) {
1083 return false;
1084 }
1085 mirror::Array* arr = obj->AsArray();
1086 CHECK_EQ(reinterpret_cast<Object*>(
1087 image_->Begin() + it->second.offset_ + image_objects_offset_begin_), dst);
1088 dex_cache_array_indexes_.erase(it);
1089 // Fixup int pointers for the field array.
1090 CHECK(!arr->IsObjectArray());
1091 const size_t num_elements = arr->GetLength();
1092 if (target_ptr_size_ == 4) {
1093 // Will get fixed up by fixup object.
1094 dst->SetClass(down_cast<mirror::Class*>(
1095 GetImageAddress(mirror::IntArray::GetArrayClass())));
1096 } else {
1097 DCHECK_EQ(target_ptr_size_, 8u);
1098 dst->SetClass(down_cast<mirror::Class*>(
1099 GetImageAddress(mirror::LongArray::GetArrayClass())));
1100 }
1101 mirror::Array* dest_array = down_cast<mirror::Array*>(dst);
1102 dest_array->SetLength(num_elements);
1103 for (size_t i = 0, count = num_elements; i < count; ++i) {
1104 ArtField* field = reinterpret_cast<ArtField*>(is_int_arr ?
1105 arr->AsIntArray()->GetWithoutChecks(i) : arr->AsLongArray()->GetWithoutChecks(i));
1106 uint8_t* fixup_location = nullptr;
1107 if (field != nullptr) {
1108 auto it2 = art_field_reloc_.find(field);
1109 CHECK(it2 != art_field_reloc_.end()) << "No relocation for field " << PrettyField(field);
1110 fixup_location = image_begin_ + it2->second;
1111 }
1112 if (target_ptr_size_ == 4) {
1113 down_cast<mirror::IntArray*>(dest_array)->SetWithoutChecks<kVerifyNone>(
1114 i, static_cast<uint32_t>(reinterpret_cast<uint64_t>(fixup_location)));
1115 } else {
1116 down_cast<mirror::LongArray*>(dest_array)->SetWithoutChecks<kVerifyNone>(
1117 i, reinterpret_cast<uint64_t>(fixup_location));
1118 }
1119 }
1120 dst->SetLockWord(LockWord::Default(), false);
1121 return true;
1122}
1123
1124void ImageWriter::CopyAndFixupObject(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001125 // see GetLocalAddress for similar computation
Mathieu Chartierc7853442015-03-27 14:35:38 -07001126 size_t offset = GetImageOffset(obj);
1127 auto* dst = reinterpret_cast<Object*>(image_->Begin() + offset);
Ian Rogers13735952014-10-08 12:43:28 -07001128 const uint8_t* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001129 size_t n;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001130 mirror::Class* klass = obj->GetClass();
1131
1132 if (CopyAndFixupIfDexCacheFieldArray(dst, obj, klass)) {
1133 return;
1134 }
1135 if (klass->IsArtMethodClass()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001136 // Size without pointer fields since we don't want to overrun the buffer if target art method
1137 // is 32 bits but source is 64 bits.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001138 n = mirror::ArtMethod::SizeWithoutPointerFields(target_ptr_size_);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001139 } else {
1140 n = obj->SizeOf();
1141 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001142 DCHECK_LE(offset + n, image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001143 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001144
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001145 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1146 // word.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001147 dst->SetLockWord(LockWord::Default(), false);
1148 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001149}
1150
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001151// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001152class FixupVisitor {
1153 public:
1154 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1155 }
1156
1157 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
1158 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001159 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001160 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1161 // image.
1162 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001163 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001164 }
1165
1166 // java.lang.ref.Reference visitor.
1167 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
1168 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1169 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1170 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001171 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001172 }
1173
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001174 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001175 ImageWriter* const image_writer_;
1176 mirror::Object* const copy_;
1177};
1178
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001179class FixupClassVisitor FINAL : public FixupVisitor {
1180 public:
1181 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1182 }
1183
Mathieu Chartierc7853442015-03-27 14:35:38 -07001184 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001185 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1186 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001187 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001188 }
1189
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001190 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1191 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001192 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1193 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1194 LOG(FATAL) << "Reference not expected here.";
1195 }
1196};
1197
Mathieu Chartierc7853442015-03-27 14:35:38 -07001198void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
1199 // Copy and fix up ArtFields in the class.
1200 ArtField* fields[2] = { orig->AsClass()->GetSFields(), orig->AsClass()->GetIFields() };
1201 size_t num_fields[2] = { orig->AsClass()->NumStaticFields(),
1202 orig->AsClass()->NumInstanceFields() };
1203 // Update the arrays.
1204 for (size_t i = 0; i < 2; ++i) {
1205 if (num_fields[i] == 0) {
1206 CHECK(fields[i] == nullptr);
1207 continue;
1208 }
1209 auto it = art_field_reloc_.find(fields[i]);
1210 CHECK(it != art_field_reloc_.end()) << PrettyClass(orig->AsClass()) << " : "
1211 << PrettyField(fields[i]);
1212 auto* image_fields = reinterpret_cast<ArtField*>(image_begin_ + it->second);
1213 if (i == 0) {
1214 down_cast<Class*>(copy)->SetSFieldsUnchecked(image_fields);
1215 } else {
1216 down_cast<Class*>(copy)->SetIFieldsUnchecked(image_fields);
1217 }
1218 }
1219 FixupClassVisitor visitor(this, copy);
1220 static_cast<mirror::Object*>(orig)->VisitReferences<true /*visit class*/>(visitor, visitor);
1221}
1222
Ian Rogersef7d42f2014-01-06 12:55:46 -08001223void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001224 DCHECK(orig != nullptr);
1225 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001226 if (kUseBakerOrBrooksReadBarrier) {
1227 orig->AssertReadBarrierPointer();
1228 if (kUseBrooksReadBarrier) {
1229 // Note the address 'copy' isn't the same as the image address of 'orig'.
1230 copy->SetReadBarrierPointer(GetImageAddress(orig));
1231 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1232 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001233 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001234 if (orig->IsClass()) {
1235 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001236 } else {
1237 FixupVisitor visitor(this, copy);
1238 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
1239 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001240 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001241 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001242 }
1243}
1244
Ian Rogers13735952014-10-08 12:43:28 -07001245const uint8_t* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001246 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001247 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001248
1249 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1250 // trampoline.
1251
1252 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001253 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1254 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
1255 const uint8_t* quick_code = GetOatAddress(quick_oat_code_offset);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001256 *quick_is_interpreted = false;
1257 if (quick_code != nullptr &&
1258 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
1259 // We have code for a non-static or initialized method, just use the code.
1260 } else if (quick_code == nullptr && method->IsNative() &&
1261 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1262 // Non-static or initialized native method missing compiled code, use generic JNI version.
1263 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
1264 } else if (quick_code == nullptr && !method->IsNative()) {
1265 // We don't have code at all for a non-native method, use the interpreter.
1266 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
1267 *quick_is_interpreted = true;
1268 } else {
1269 CHECK(!method->GetDeclaringClass()->IsInitialized());
1270 // We have code for a static method, but need to go through the resolution stub for class
1271 // initialization.
1272 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
1273 }
1274 return quick_code;
1275}
1276
Ian Rogers13735952014-10-08 12:43:28 -07001277const uint8_t* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001278 // Calculate the quick entry point following the same logic as FixupMethod() below.
1279 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001280 Runtime* runtime = Runtime::Current();
1281 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001282 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001283 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
1284 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001285 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
1286 } else {
1287 // We assume all methods have code. If they don't currently then we set them to the use the
1288 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1289 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1290 if (UNLIKELY(method->IsAbstract())) {
1291 return GetOatAddress(quick_to_interpreter_bridge_offset_);
1292 } else {
1293 bool quick_is_interpreted;
1294 return GetQuickCode(method, &quick_is_interpreted);
1295 }
1296 }
1297}
1298
Ian Rogersef7d42f2014-01-06 12:55:46 -08001299void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -07001300 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1301 // oat_begin_
Mathieu Chartier2d721012014-11-10 11:08:06 -08001302 // For 64 bit targets we need to repack the current runtime pointer sized fields to the right
1303 // locations.
1304 // Copy all of the fields from the runtime methods to the target methods first since we did a
1305 // bytewise copy earlier.
Jeff Haoc7d11882015-02-03 15:08:39 -08001306 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1307 orig->GetEntryPointFromInterpreterPtrSize(target_ptr_size_), target_ptr_size_);
1308 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(
1309 orig->GetEntryPointFromJniPtrSize(target_ptr_size_), target_ptr_size_);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001310 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
Jeff Haoc7d11882015-02-03 15:08:39 -08001311 orig->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001312
Ian Rogers848871b2013-08-05 10:56:33 -07001313 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001314 Runtime* runtime = Runtime::Current();
1315 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001316 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1317 GetOatAddress(quick_resolution_trampoline_offset_), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001318 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1319 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001320 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1321 GetOatAddress(quick_imt_conflict_trampoline_offset_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001322 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001323 // We assume all methods have code. If they don't currently then we set them to the use the
1324 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1325 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1326 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001327 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1328 GetOatAddress(quick_to_interpreter_bridge_offset_), target_ptr_size_);
1329 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1330 reinterpret_cast<EntryPointFromInterpreter*>(const_cast<uint8_t*>(
1331 GetOatAddress(interpreter_to_interpreter_bridge_offset_))), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001332 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001333 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -07001334 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001335 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001336
Sebastien Hertze1d07812014-05-21 15:44:09 +02001337 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001338 if (orig->IsNative()) {
1339 // The native method's pointer is set to a stub to lookup via dlsym.
1340 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier2d721012014-11-10 11:08:06 -08001341 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_),
1342 target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001343 }
Sebastien Hertze1d07812014-05-21 15:44:09 +02001344
1345 // Interpreter entrypoint:
1346 // Set the interpreter entrypoint depending on whether there is compiled code or not.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001347 uint32_t interpreter_code = (quick_is_interpreted)
Sebastien Hertze1d07812014-05-21 15:44:09 +02001348 ? interpreter_to_interpreter_bridge_offset_
1349 : interpreter_to_compiled_code_bridge_offset_;
Mathieu Chartier2d721012014-11-10 11:08:06 -08001350 EntryPointFromInterpreter* interpreter_entrypoint =
Sebastien Hertze1d07812014-05-21 15:44:09 +02001351 reinterpret_cast<EntryPointFromInterpreter*>(
Mathieu Chartier2d721012014-11-10 11:08:06 -08001352 const_cast<uint8_t*>(GetOatAddress(interpreter_code)));
1353 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1354 interpreter_entrypoint, target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001355 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001356 }
1357}
1358
Alex Lighta59dd802014-07-02 16:28:08 -07001359static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001360 uint64_t data_sec_offset;
1361 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1362 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001363 return nullptr;
1364 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001365 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001366}
1367
Vladimir Markof4da6752014-08-01 19:04:18 +01001368void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001369 std::string error_msg;
1370 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
1371 MAP_SHARED, &error_msg));
1372 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001373 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001374 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001375 }
Alex Lighta59dd802014-07-02 16:28:08 -07001376 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1377 CHECK(oat_header != nullptr);
1378 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001379
Brian Carlstrom7940e442013-07-12 13:46:57 -07001380 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001381 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001382}
1383
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001384size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1385 DCHECK_LE(up_to, kBinSize);
1386 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1387}
1388
1389ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1390 // These values may need to get updated if more bins are added to the enum Bin
Vladimir Marko20f85592015-03-19 10:07:02 +00001391 static_assert(kBinBits == 4, "wrong number of bin bits");
1392 static_assert(kBinShift == 28, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001393 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1394
1395 DCHECK_LT(GetBin(), kBinSize);
1396 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1397}
1398
1399ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1400 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1401 DCHECK_EQ(index, GetIndex());
1402}
1403
1404ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1405 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1406}
1407
1408uint32_t ImageWriter::BinSlot::GetIndex() const {
1409 return lockword_ & ~kBinMask;
1410}
1411
Andreas Gampe245ee002014-12-04 21:25:04 -08001412void ImageWriter::FreeStringDataArray() {
1413 if (string_data_array_ != nullptr) {
1414 gc::space::LargeObjectSpace* los = Runtime::Current()->GetHeap()->GetLargeObjectsSpace();
1415 if (los != nullptr) {
1416 los->Free(Thread::Current(), reinterpret_cast<mirror::Object*>(string_data_array_));
1417 }
1418 }
1419}
1420
Brian Carlstrom7940e442013-07-12 13:46:57 -07001421} // namespace art