blob: 6f8884a9ab2a2525909db1e072e8c06b1cb5a911 [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"
28#include "class_linker.h"
29#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;
73
Andreas Gampedd9d0552015-03-09 12:57:41 -070074static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
75 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
76 Class* klass = obj->GetClass();
77 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
78}
79
80static void CheckNoDexObjects() {
81 ScopedObjectAccess soa(Thread::Current());
82 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
83}
84
Vladimir Markof4da6752014-08-01 19:04:18 +010085bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -080086 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +010087 {
88 Thread::Current()->TransitionFromSuspendedToRunnable();
89 PruneNonImageClasses(); // Remove junk
90 ComputeLazyFieldsForImageClasses(); // Add useful information
Vladimir Marko3389ca72014-12-03 14:35:54 +000091 ProcessStrings();
Vladimir Markof4da6752014-08-01 19:04:18 +010092 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
93 }
94 gc::Heap* heap = Runtime::Current()->GetHeap();
95 heap->CollectGarbage(false); // Remove garbage.
96
Andreas Gampedd9d0552015-03-09 12:57:41 -070097 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
98 // dex files.
99 //
100 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
101 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
102 // true.
103 if (kIsDebugBuild) {
104 CheckNoDexObjects();
105 }
106
Vladimir Markof4da6752014-08-01 19:04:18 +0100107 if (!AllocMemory()) {
108 return false;
109 }
110
111 if (kIsDebugBuild) {
112 ScopedObjectAccess soa(Thread::Current());
113 CheckNonImageClassesRemoved();
114 }
115
116 Thread::Current()->TransitionFromSuspendedToRunnable();
117 CalculateNewObjectOffsets();
118 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
119
120 return true;
121}
122
Brian Carlstrom7940e442013-07-12 13:46:57 -0700123bool ImageWriter::Write(const std::string& image_filename,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700124 const std::string& oat_filename,
125 const std::string& oat_location) {
126 CHECK(!image_filename.empty());
127
Brian Carlstrom7940e442013-07-12 13:46:57 -0700128 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700129
Ian Rogers700a4022014-05-19 16:49:03 -0700130 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700131 if (oat_file.get() == NULL) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800132 PLOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700133 return false;
134 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700135 std::string error_msg;
Richard Uhlere5fed032015-03-18 08:21:11 -0700136 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, nullptr, &error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700137 if (oat_file_ == nullptr) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800138 PLOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700139 << ": " << error_msg;
Andreas Gampe0b7fcf92015-03-13 16:54:54 -0700140 oat_file->Erase();
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700141 return false;
142 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700143 CHECK_EQ(class_linker->RegisterOatFile(oat_file_), oat_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700144
Ian Rogers848871b2013-08-05 10:56:33 -0700145 interpreter_to_interpreter_bridge_offset_ =
146 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
147 interpreter_to_compiled_code_bridge_offset_ =
148 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
149
150 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
151
Andreas Gampe2da88232014-02-27 12:26:20 -0800152 quick_generic_jni_trampoline_offset_ =
153 oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
Jeff Hao88474b42013-10-23 16:24:40 -0700154 quick_imt_conflict_trampoline_offset_ =
155 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700156 quick_resolution_trampoline_offset_ =
157 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
158 quick_to_interpreter_bridge_offset_ =
159 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700160
Brian Carlstrom7940e442013-07-12 13:46:57 -0700161 size_t oat_loaded_size = 0;
162 size_t oat_data_offset = 0;
163 ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
Alex Light53cb16b2014-06-12 11:26:29 -0700164
Vladimir Markof4da6752014-08-01 19:04:18 +0100165 Thread::Current()->TransitionFromSuspendedToRunnable();
166 CreateHeader(oat_loaded_size, oat_data_offset);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700167 // TODO: heap validation can't handle these fix up passes.
168 Runtime::Current()->GetHeap()->DisableObjectValidation();
169 CopyAndFixupNativeData();
Vladimir Markof4da6752014-08-01 19:04:18 +0100170 CopyAndFixupObjects();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700171 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
172
Vladimir Markof4da6752014-08-01 19:04:18 +0100173 SetOatChecksumFromElfFile(oat_file.get());
174
Andreas Gampe4303ba92014-11-06 01:00:46 -0800175 if (oat_file->FlushCloseOrErase() != 0) {
176 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename << " for " << oat_location;
177 return false;
178 }
179
Ian Rogers700a4022014-05-19 16:49:03 -0700180 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700181 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700182 if (image_file.get() == NULL) {
183 LOG(ERROR) << "Failed to open image file " << image_filename;
184 return false;
185 }
186 if (fchmod(image_file->Fd(), 0644) != 0) {
187 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800188 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700189 return EXIT_FAILURE;
190 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700191
Mathieu Chartierc7853442015-03-27 14:35:38 -0700192 // Write out the image + fields.
193 const auto write_count = image_header->GetImageSize() + image_header->GetArtFieldsSize();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700194 CHECK_EQ(image_end_, image_header->GetImageSize());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700195 if (!image_file->WriteFully(image_->Begin(), write_count)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700196 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800197 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700198 return false;
199 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700200
201 // Write out the image bitmap at the page aligned start of the image end.
202 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
203 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
204 image_header->GetImageBitmapSize(),
205 image_header->GetImageBitmapOffset())) {
206 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800207 image_file->Erase();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700208 return false;
209 }
210
Mathieu Chartierc7853442015-03-27 14:35:38 -0700211 CHECK_EQ(image_header->GetImageBitmapOffset() + image_header->GetImageBitmapSize(),
212 static_cast<size_t>(image_file->GetLength()));
Andreas Gampe4303ba92014-11-06 01:00:46 -0800213 if (image_file->FlushCloseOrErase() != 0) {
214 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
215 return false;
216 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700217 return true;
218}
219
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800220void ImageWriter::SetImageOffset(mirror::Object* object,
221 ImageWriter::BinSlot bin_slot,
222 size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700223 DCHECK(object != nullptr);
224 DCHECK_NE(offset, 0U);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700225 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
226 DCHECK_ALIGNED(obj, kObjectAlignment);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800227
Mathieu Chartierc7853442015-03-27 14:35:38 -0700228 static size_t max_offset = 0;
229 max_offset = std::max(max_offset, offset);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800230 image_bitmap_->Set(obj); // Mark the obj as mutated, since we will end up changing it.
231 {
232 // Remember the object-inside-of-the-image's hash code so we can restore it after the copy.
233 auto hash_it = saved_hashes_map_.find(bin_slot);
234 if (hash_it != saved_hashes_map_.end()) {
235 std::pair<BinSlot, uint32_t> slot_hash = *hash_it;
236 saved_hashes_.push_back(std::make_pair(obj, slot_hash.second));
237 saved_hashes_map_.erase(hash_it);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700238 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700239 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800240 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700241 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700242 DCHECK(IsImageOffsetAssigned(object));
243}
244
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800245void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700246 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800247 DCHECK_NE(image_objects_offset_begin_, 0u);
248
Vladimir Marko20f85592015-03-19 10:07:02 +0000249 size_t previous_bin_sizes = bin_slot_previous_sizes_[bin_slot.GetBin()];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800250 size_t new_offset = image_objects_offset_begin_ + previous_bin_sizes + bin_slot.GetIndex();
251 DCHECK_ALIGNED(new_offset, kObjectAlignment);
252
253 SetImageOffset(object, bin_slot, new_offset);
254 DCHECK_LT(new_offset, image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700255}
256
Ian Rogersef7d42f2014-01-06 12:55:46 -0800257bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800258 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700259 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700260 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700261}
262
Ian Rogersef7d42f2014-01-06 12:55:46 -0800263size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700264 DCHECK(object != nullptr);
265 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700266 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700267 size_t offset = lock_word.ForwardingAddress();
268 DCHECK_LT(offset, image_end_);
269 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700270}
271
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800272void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
273 DCHECK(object != nullptr);
274 DCHECK(!IsImageOffsetAssigned(object));
275 DCHECK(!IsImageBinSlotAssigned(object));
276
277 // Before we stomp over the lock word, save the hash code for later.
278 Monitor::Deflate(Thread::Current(), object);;
279 LockWord lw(object->GetLockWord(false));
280 switch (lw.GetState()) {
281 case LockWord::kFatLocked: {
282 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
283 break;
284 }
285 case LockWord::kThinLocked: {
286 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
287 break;
288 }
289 case LockWord::kUnlocked:
290 // No hash, don't need to save it.
291 break;
292 case LockWord::kHashCode:
293 saved_hashes_map_[bin_slot] = lw.GetHashCode();
294 break;
295 default:
296 LOG(FATAL) << "Unreachable.";
297 UNREACHABLE();
298 }
299 object->SetLockWord(LockWord::FromForwardingAddress(static_cast<uint32_t>(bin_slot)),
300 false);
301 DCHECK(IsImageBinSlotAssigned(object));
302}
303
Vladimir Marko20f85592015-03-19 10:07:02 +0000304void ImageWriter::PrepareDexCacheArraySlots() {
305 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
306 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
307 size_t dex_cache_count = class_linker->GetDexCacheCount();
308 uint32_t size = 0u;
309 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
310 DexCache* dex_cache = class_linker->GetDexCache(idx);
311 const DexFile* dex_file = dex_cache->GetDexFile();
312 dex_cache_array_starts_.Put(dex_file, size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700313 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000314 DCHECK(layout.Valid());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700315 auto types_size = layout.TypesSize(dex_file->NumTypeIds());
316 auto methods_size = layout.MethodsSize(dex_file->NumMethodIds());
317 auto fields_size = layout.FieldsSize(dex_file->NumFieldIds());
318 auto strings_size = layout.StringsSize(dex_file->NumStringIds());
319 dex_cache_array_indexes_.Put(
320 dex_cache->GetResolvedTypes(),
321 DexCacheArrayLocation {size + layout.TypesOffset(), types_size});
322 dex_cache_array_indexes_.Put(
323 dex_cache->GetResolvedMethods(),
324 DexCacheArrayLocation {size + layout.MethodsOffset(), methods_size});
325 dex_cache_array_indexes_.Put(
326 dex_cache->GetResolvedFields(),
327 DexCacheArrayLocation {size + layout.FieldsOffset(), fields_size});
328 dex_cache_array_indexes_.Put(
329 dex_cache->GetStrings(),
330 DexCacheArrayLocation {size + layout.StringsOffset(), strings_size});
Vladimir Marko20f85592015-03-19 10:07:02 +0000331 size += layout.Size();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700332 CHECK_EQ(layout.Size(), types_size + methods_size + fields_size + strings_size);
Vladimir Marko20f85592015-03-19 10:07:02 +0000333 }
334 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
335 // when AssignImageBinSlot() assigns their indexes out or order.
336 bin_slot_sizes_[kBinDexCacheArray] = size;
337}
338
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800339void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
340 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800341 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800342
343 // The magic happens here. We segregate objects into different bins based
344 // on how likely they are to get dirty at runtime.
345 //
346 // Likely-to-dirty objects get packed together into the same bin so that
347 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
348 // maximized.
349 //
350 // This means more pages will stay either clean or shared dirty (with zygote) and
351 // the app will use less of its own (private) memory.
352 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000353 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800354
355 if (kBinObjects) {
356 //
357 // Changing the bin of an object is purely a memory-use tuning.
358 // It has no change on runtime correctness.
359 //
360 // Memory analysis has determined that the following types of objects get dirtied
361 // the most:
362 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000363 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
364 // a fixed layout which helps improve generated code (using PC-relative addressing),
365 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
366 // Since these arrays are huge, most pages do not overlap other objects and it's not
367 // really important where they are for the clean/dirty separation. Due to their
368 // special PC-relative addressing, we arbitrarily keep them at the beginning.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800369 // * Class'es which are verified [their clinit runs only at runtime]
370 // - classes in general [because their static fields get overwritten]
371 // - initialized classes with all-final statics are unlikely to be ever dirty,
372 // so bin them separately
373 // * Art Methods that are:
374 // - native [their native entry point is not looked up until runtime]
375 // - have declaring classes that aren't initialized
376 // [their interpreter/quick entry points are trampolines until the class
377 // becomes initialized]
378 //
379 // We also assume the following objects get dirtied either never or extremely rarely:
380 // * Strings (they are immutable)
381 // * Art methods that aren't native and have initialized declared classes
382 //
383 // We assume that "regular" bin objects are highly unlikely to become dirtied,
384 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
385 //
386 if (object->IsClass()) {
387 bin = kBinClassVerified;
388 mirror::Class* klass = object->AsClass();
389
390 if (klass->GetStatus() == Class::kStatusInitialized) {
391 bin = kBinClassInitialized;
392
393 // If the class's static fields are all final, put it into a separate bin
394 // since it's very likely it will stay clean.
395 uint32_t num_static_fields = klass->NumStaticFields();
396 if (num_static_fields == 0) {
397 bin = kBinClassInitializedFinalStatics;
398 } else {
399 // Maybe all the statics are final?
400 bool all_final = true;
401 for (uint32_t i = 0; i < num_static_fields; ++i) {
402 ArtField* field = klass->GetStaticField(i);
403 if (!field->IsFinal()) {
404 all_final = false;
405 break;
406 }
407 }
408
409 if (all_final) {
410 bin = kBinClassInitializedFinalStatics;
411 }
412 }
413 }
414 } else if (object->IsArtMethod<kVerifyNone>()) {
415 mirror::ArtMethod* art_method = down_cast<ArtMethod*>(object);
416 if (art_method->IsNative()) {
417 bin = kBinArtMethodNative;
418 } else {
419 mirror::Class* declaring_class = art_method->GetDeclaringClass();
420 if (declaring_class->GetStatus() != Class::kStatusInitialized) {
421 bin = kBinArtMethodNotInitialized;
422 } else {
423 // This is highly unlikely to dirty since there's no entry points to mutate.
424 bin = kBinArtMethodsManagedInitialized;
425 }
426 }
427 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
428 bin = kBinString; // Strings are almost always immutable (except for object header).
Mathieu Chartierc7853442015-03-27 14:35:38 -0700429 } else if (object->IsArrayInstance()) {
430 mirror::Class* klass = object->GetClass<kVerifyNone>();
431 auto* component_type = klass->GetComponentType();
432 if (!component_type->IsPrimitive() || component_type->IsPrimitiveInt() ||
433 component_type->IsPrimitiveLong()) {
434 auto it = dex_cache_array_indexes_.find(object);
435 if (it != dex_cache_array_indexes_.end()) {
436 bin = kBinDexCacheArray;
437 // Use prepared offset defined by the DexCacheLayout.
438 current_offset = it->second.offset_;
439 // Override incase of cross compilation.
440 object_size = it->second.length_;
441 } // else bin = kBinRegular
442 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800443 } // else bin = kBinRegular
444 }
445
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800446 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Vladimir Marko20f85592015-03-19 10:07:02 +0000447 if (bin != kBinDexCacheArray) {
448 current_offset = bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
449 // Move the current bin size up to accomodate the object we just assigned a bin slot.
450 bin_slot_sizes_[bin] += offset_delta;
451 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800452
453 BinSlot new_bin_slot(bin, current_offset);
454 SetImageBinSlot(object, new_bin_slot);
455
456 ++bin_slot_count_[bin];
457
458 DCHECK_LT(GetBinSizeSum(), image_->Size());
459
460 // Grow the image closer to the end by the object we just assigned.
461 image_end_ += offset_delta;
462 DCHECK_LT(image_end_, image_->Size());
463}
464
465bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
466 DCHECK(object != nullptr);
467
468 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
469 // If it's in some other state, then we haven't yet assigned an image bin slot.
470 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
471 return false;
472 } else if (kIsDebugBuild) {
473 LockWord lock_word = object->GetLockWord(false);
474 size_t offset = lock_word.ForwardingAddress();
475 BinSlot bin_slot(offset);
476 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()])
477 << "bin slot offset should not exceed the size of that bin";
478 }
479 return true;
480}
481
482ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
483 DCHECK(object != nullptr);
484 DCHECK(IsImageBinSlotAssigned(object));
485
486 LockWord lock_word = object->GetLockWord(false);
487 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
488 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
489
490 BinSlot bin_slot(static_cast<uint32_t>(offset));
491 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()]);
492
493 return bin_slot;
494}
495
Brian Carlstrom7940e442013-07-12 13:46:57 -0700496bool ImageWriter::AllocMemory() {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700497 auto* runtime = Runtime::Current();
498 const size_t heap_size = runtime->GetHeap()->GetTotalMemory();
499 // Add linear alloc usage since we need to have room for the ArtFields.
500 const size_t length = RoundUp(heap_size + runtime->GetLinearAlloc()->GetUsedMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700501 std::string error_msg;
Vladimir Marko5c42c292015-02-25 12:02:49 +0000502 image_.reset(MemMap::MapAnonymous("image writer image", nullptr, length, PROT_READ | PROT_WRITE,
503 false, false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700504 if (UNLIKELY(image_.get() == nullptr)) {
505 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700506 return false;
507 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700508
509 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700510 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
Mathieu Chartierc7853442015-03-27 14:35:38 -0700511 RoundUp(length, kPageSize)));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700512 if (image_bitmap_.get() == nullptr) {
513 LOG(ERROR) << "Failed to allocate memory for image bitmap";
514 return false;
515 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700516 return true;
517}
518
519void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700520 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700521 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
522}
523
524bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700525 Thread* self = Thread::Current();
526 StackHandleScope<1> hs(self);
527 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700528 return true;
529}
530
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800531// Count the number of strings in the heap and put the result in arg as a size_t pointer.
532static void CountStringsCallback(Object* obj, void* arg)
533 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
534 if (obj->GetClass()->IsStringClass()) {
535 ++*reinterpret_cast<size_t*>(arg);
536 }
537}
538
539// Collect all the java.lang.String in the heap and put them in the output strings_ array.
540class StringCollector {
541 public:
542 StringCollector(Handle<mirror::ObjectArray<mirror::String>> strings, size_t index)
543 : strings_(strings), index_(index) {
544 }
545 static void Callback(Object* obj, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
546 auto* collector = reinterpret_cast<StringCollector*>(arg);
547 if (obj->GetClass()->IsStringClass()) {
548 collector->strings_->SetWithoutChecks<false>(collector->index_++, obj->AsString());
549 }
550 }
551 size_t GetIndex() const {
552 return index_;
553 }
554
555 private:
556 Handle<mirror::ObjectArray<mirror::String>> strings_;
557 size_t index_;
558};
559
560// Compare strings based on length, used for sorting strings by length / reverse length.
Vladimir Markofaeda182014-12-04 14:52:25 +0000561class LexicographicalStringComparator {
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800562 public:
Vladimir Markofaeda182014-12-04 14:52:25 +0000563 bool operator()(const mirror::HeapReference<mirror::String>& lhs,
564 const mirror::HeapReference<mirror::String>& rhs) const
565 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
566 mirror::String* lhs_s = lhs.AsMirrorPtr();
567 mirror::String* rhs_s = rhs.AsMirrorPtr();
568 uint16_t* lhs_begin = lhs_s->GetCharArray()->GetData() + lhs_s->GetOffset();
569 uint16_t* rhs_begin = rhs_s->GetCharArray()->GetData() + rhs_s->GetOffset();
570 return std::lexicographical_compare(lhs_begin, lhs_begin + lhs_s->GetLength(),
571 rhs_begin, rhs_begin + rhs_s->GetLength());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800572 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800573};
574
Vladimir Markofaeda182014-12-04 14:52:25 +0000575static bool IsPrefix(mirror::String* pref, mirror::String* full)
576 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
577 if (pref->GetLength() > full->GetLength()) {
578 return false;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800579 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000580 uint16_t* pref_begin = pref->GetCharArray()->GetData() + pref->GetOffset();
581 uint16_t* full_begin = full->GetCharArray()->GetData() + full->GetOffset();
582 return std::equal(pref_begin, pref_begin + pref->GetLength(), full_begin);
583}
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800584
585void ImageWriter::ProcessStrings() {
586 size_t total_strings = 0;
587 gc::Heap* heap = Runtime::Current()->GetHeap();
588 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800589 // Count the strings.
590 heap->VisitObjects(CountStringsCallback, &total_strings);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800591 Thread* self = Thread::Current();
592 StackHandleScope<1> hs(self);
593 auto strings = hs.NewHandle(cl->AllocStringArray(self, total_strings));
594 StringCollector string_collector(strings, 0U);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800595 // Read strings into the array.
596 heap->VisitObjects(StringCollector::Callback, &string_collector);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800597 // Some strings could have gotten freed if AllocStringArray caused a GC.
598 CHECK_LE(string_collector.GetIndex(), total_strings);
599 total_strings = string_collector.GetIndex();
Vladimir Markofaeda182014-12-04 14:52:25 +0000600 auto* strings_begin = reinterpret_cast<mirror::HeapReference<mirror::String>*>(
601 strings->GetRawData(sizeof(mirror::HeapReference<mirror::String>), 0));
602 std::sort(strings_begin, strings_begin + total_strings, LexicographicalStringComparator());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800603 // Characters of strings which are non equal prefix of another string (not the same string).
604 // We don't count the savings from equal strings since these would get interned later anyways.
605 size_t prefix_saved_chars = 0;
Vladimir Markofaeda182014-12-04 14:52:25 +0000606 // Count characters needed for the strings.
607 size_t num_chars = 0u;
608 mirror::String* prev_s = nullptr;
609 for (size_t idx = 0; idx != total_strings; ++idx) {
610 mirror::String* s = strings->GetWithoutChecks(idx);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800611 size_t length = s->GetLength();
Vladimir Markofaeda182014-12-04 14:52:25 +0000612 num_chars += length;
613 if (prev_s != nullptr && IsPrefix(prev_s, s)) {
614 size_t prev_length = prev_s->GetLength();
615 num_chars -= prev_length;
616 if (prev_length != length) {
617 prefix_saved_chars += prev_length;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800618 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800619 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000620 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800621 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000622 // Create character array, copy characters and point the strings there.
623 mirror::CharArray* array = mirror::CharArray::Alloc(self, num_chars);
Andreas Gampe245ee002014-12-04 21:25:04 -0800624 string_data_array_ = array;
Vladimir Markofaeda182014-12-04 14:52:25 +0000625 uint16_t* array_data = array->GetData();
626 size_t pos = 0u;
627 prev_s = nullptr;
628 for (size_t idx = 0; idx != total_strings; ++idx) {
629 mirror::String* s = strings->GetWithoutChecks(idx);
630 uint16_t* s_data = s->GetCharArray()->GetData() + s->GetOffset();
631 int32_t s_length = s->GetLength();
632 int32_t prefix_length = 0u;
633 if (idx != 0u && IsPrefix(prev_s, s)) {
634 prefix_length = prev_s->GetLength();
635 }
636 memcpy(array_data + pos, s_data + prefix_length, (s_length - prefix_length) * sizeof(*s_data));
637 s->SetOffset(pos - prefix_length);
638 s->SetArray(array);
639 pos += s_length - prefix_length;
640 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800641 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000642 CHECK_EQ(pos, num_chars);
643
Andreas Gampedc843012015-01-20 16:17:19 -0800644 if (kIsDebugBuild || VLOG_IS_ON(compiler)) {
645 LOG(INFO) << "Total # image strings=" << total_strings << " combined length="
646 << num_chars << " prefix saved chars=" << prefix_saved_chars;
647 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800648 ComputeEagerResolvedStrings();
649}
650
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700651void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700652 if (!obj->GetClass()->IsStringClass()) {
653 return;
654 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700655 mirror::String* string = obj->AsString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700656 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
Vladimir Markoa48aef42014-12-03 17:53:53 +0000657 size_t utf16_length = static_cast<size_t>(string->GetLength());
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700658 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
659 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
660 size_t dex_cache_count = class_linker->GetDexCacheCount();
661 for (size_t i = 0; i < dex_cache_count; ++i) {
662 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700663 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800664 const DexFile::StringId* string_id;
Vladimir Markoa48aef42014-12-03 17:53:53 +0000665 if (UNLIKELY(utf16_length == 0)) {
Ian Rogers24c534d2013-11-14 00:15:00 -0800666 string_id = dex_file.FindStringId("");
667 } else {
Vladimir Markoa48aef42014-12-03 17:53:53 +0000668 string_id = dex_file.FindStringId(utf16_string, utf16_length);
Ian Rogers24c534d2013-11-14 00:15:00 -0800669 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700670 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700671 // This string occurs in this dex file, assign the dex cache entry.
672 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
673 if (dex_cache->GetResolvedString(string_idx) == NULL) {
674 dex_cache->SetResolvedString(string_idx, string);
675 }
676 }
677 }
678}
679
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800680void ImageWriter::ComputeEagerResolvedStrings() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700681 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700682}
683
Ian Rogersef7d42f2014-01-06 12:55:46 -0800684bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700685 std::string temp;
686 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700687}
688
689struct NonImageClasses {
690 ImageWriter* image_writer;
691 std::set<std::string>* non_image_classes;
692};
693
694void ImageWriter::PruneNonImageClasses() {
695 if (compiler_driver_.GetImageClasses() == NULL) {
696 return;
697 }
698 Runtime* runtime = Runtime::Current();
699 ClassLinker* class_linker = runtime->GetClassLinker();
700
701 // Make a list of classes we would like to prune.
702 std::set<std::string> non_image_classes;
703 NonImageClasses context;
704 context.image_writer = this;
705 context.non_image_classes = &non_image_classes;
706 class_linker->VisitClasses(NonImageClassesVisitor, &context);
707
708 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700709 for (const std::string& it : non_image_classes) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800710 bool result = class_linker->RemoveClass(it.c_str(), NULL);
711 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700712 }
713
714 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700715 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700716 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
717 size_t dex_cache_count = class_linker->GetDexCacheCount();
718 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
719 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700720 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
721 Class* klass = dex_cache->GetResolvedType(i);
722 if (klass != NULL && !IsImageClass(klass)) {
723 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700724 }
725 }
726 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700727 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700728 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
729 dex_cache->SetResolvedMethod(i, resolution_method);
730 }
731 }
732 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700733 ArtField* field = dex_cache->GetResolvedField(i, sizeof(void*));
734 if (field != nullptr && !IsImageClass(field->GetDeclaringClass())) {
735 dex_cache->SetResolvedField(i, nullptr, sizeof(void*));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700736 }
737 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700738 // Clean the dex field. It might have been populated during the initialization phase, but
739 // contains data only valid during a real run.
740 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700741 }
742}
743
744bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
745 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
746 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700747 std::string temp;
748 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700749 }
750 return true;
751}
752
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800753void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700754 if (compiler_driver_.GetImageClasses() != nullptr) {
755 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700756 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700757 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700758}
759
760void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
761 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700762 if (obj->IsClass()) {
763 Class* klass = obj->AsClass();
764 if (!image_writer->IsImageClass(klass)) {
765 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700766 std::string temp;
767 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700768 << " " << PrettyDescriptor(klass);
769 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700770 }
771}
772
773void ImageWriter::DumpImageClasses() {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700774 const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700775 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700776 for (const std::string& image_class : *image_classes) {
777 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700778 }
779}
780
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800781void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700782 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700783 // if it is a string, we want to intern it if its not interned.
784 if (obj->GetClass()->IsStringClass()) {
785 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800786 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700787 DCHECK_EQ(obj, obj->AsString()->Intern());
788 return;
789 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700790 mirror::String* const interned = obj->AsString()->Intern();
791 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800792 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700793 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800794 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700795 }
796 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800797 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700798 return;
799 }
800 // else (obj == interned), nothing to do but fall through to the normal case
801 }
802
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800803 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700804}
805
806ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
807 Runtime* runtime = Runtime::Current();
808 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700809 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700810 StackHandleScope<3> hs(self);
811 Handle<Class> object_array_class(hs.NewHandle(
812 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700813
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700814 // build an Object[] of all the DexCaches used in the source_space_.
815 // Since we can't hold the dex lock when allocating the dex_caches
816 // ObjectArray, we lock the dex lock twice, first to get the number
817 // of dex caches first and then lock it again to copy the dex
818 // caches. We check that the number of dex caches does not change.
819 size_t dex_cache_count;
820 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700821 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700822 dex_cache_count = class_linker->GetDexCacheCount();
823 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700824 Handle<ObjectArray<Object>> dex_caches(
825 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700826 dex_cache_count)));
827 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
828 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700829 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700830 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
831 << "The number of dex caches changed.";
832 for (size_t i = 0; i < dex_cache_count; ++i) {
833 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
834 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700835 }
836
837 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700838 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700839 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100840 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
841 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700842 image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
843 runtime->GetImtUnimplementedMethod());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100844 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
845 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
846 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
847 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
848 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
849 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
850 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700851 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100852 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700853 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
854 CHECK(image_roots->Get(i) != NULL);
855 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700856 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700857}
858
Mathieu Chartier590fee92013-09-13 13:46:47 -0700859// Walk instance fields of the given Class. Separate function to allow recursion on the super
860// class.
861void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
862 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700863 StackHandleScope<1> hs(Thread::Current());
864 Handle<mirror::Class> h_class(hs.NewHandle(klass));
865 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700866 if (super != nullptr) {
867 WalkInstanceFields(obj, super);
868 }
869 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700870 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000871 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700872 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700873 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700874 if (value != nullptr) {
875 WalkFieldsInOrder(value);
876 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000877 field_offset = MemberOffset(field_offset.Uint32Value() +
878 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700879 }
880}
881
882// For an unvisited object, visit it then all its children found via fields.
883void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800884 // Use our own visitor routine (instead of GC visitor) to get better locality between
885 // an object and its fields
886 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700887 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700888 StackHandleScope<2> hs(Thread::Current());
889 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
890 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700891 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800892 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700893 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700894 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700895 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700896 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000897 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700898 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700899 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700900 if (value != nullptr) {
901 WalkFieldsInOrder(value);
902 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000903 field_offset = MemberOffset(field_offset.Uint32Value() +
904 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700905 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700906
907 // Visit and assign offsets for fields.
908 ArtField* fields[2] = { h_obj->AsClass()->GetSFields(), h_obj->AsClass()->GetIFields() };
909 size_t num_fields[2] = { h_obj->AsClass()->NumStaticFields(),
910 h_obj->AsClass()->NumInstanceFields() };
911 for (size_t i = 0; i < 2; ++i) {
912 for (size_t j = 0; j < num_fields[i]; ++j) {
913 auto* field = fields[i] + j;
914 auto it = art_field_reloc_.find(field);
915 CHECK(it == art_field_reloc_.end()) << "Field at index " << i << ":" << j
916 << " already assigned " << PrettyField(field);
917 art_field_reloc_.emplace(field, bin_slot_sizes_[kBinArtField]);
918 bin_slot_sizes_[kBinArtField] += sizeof(ArtField);
919 }
920 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700921 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700922 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700923 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700924 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700925 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700926 mirror::Object* value = obj_array->Get(i);
927 if (value != nullptr) {
928 WalkFieldsInOrder(value);
929 }
930 }
931 }
932 }
933}
934
935void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
936 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
937 DCHECK(writer != nullptr);
938 writer->WalkFieldsInOrder(obj);
939}
940
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800941void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
942 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
943 DCHECK(writer != nullptr);
944 writer->UnbinObjectsIntoOffset(obj);
945}
946
947void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
948 CHECK(obj != nullptr);
949
950 // We know the bin slot, and the total bin sizes for all objects by now,
951 // so calculate the object's final image offset.
952
953 DCHECK(IsImageBinSlotAssigned(obj));
954 BinSlot bin_slot = GetImageBinSlot(obj);
955 // Change the lockword from a bin slot into an offset
956 AssignImageOffset(obj, bin_slot);
957}
958
Vladimir Markof4da6752014-08-01 19:04:18 +0100959void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700960 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700961 StackHandleScope<1> hs(self);
962 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700963
964 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700965 DCHECK_EQ(0U, image_end_);
966
Mathieu Chartier31e89252013-08-28 11:29:12 -0700967 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700968 // know where image_roots is going to end up
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800969 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700970
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800971 DCHECK_LT(image_end_, image_->Size());
972 image_objects_offset_begin_ = image_end_;
Vladimir Marko20f85592015-03-19 10:07:02 +0000973 // Prepare bin slots for dex cache arrays.
974 PrepareDexCacheArraySlots();
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800975 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
976 heap->VisitObjects(WalkFieldsCallback, this);
Vladimir Marko20f85592015-03-19 10:07:02 +0000977 // Calculate cumulative bin slot sizes.
978 size_t previous_sizes = 0u;
979 for (size_t i = 0; i != kBinSize; ++i) {
980 bin_slot_previous_sizes_[i] = previous_sizes;
981 previous_sizes += bin_slot_sizes_[i];
982 }
983 DCHECK_EQ(previous_sizes, GetBinSizeSum());
Mathieu Chartierc7853442015-03-27 14:35:38 -0700984 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
985
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800986 // Transform each object's bin slot into an offset which will be used to do the final copy.
987 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
988 DCHECK(saved_hashes_map_.empty()); // All binslot hashes should've been put into vector by now.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700989
Mathieu Chartierc7853442015-03-27 14:35:38 -0700990 DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800991
Vladimir Markof4da6752014-08-01 19:04:18 +0100992 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
993
Mathieu Chartierc7853442015-03-27 14:35:38 -0700994 // Note that image_end_ is left at end of used mirror space
Vladimir Markof4da6752014-08-01 19:04:18 +0100995}
996
997void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
998 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -0700999 const uint8_t* oat_file_begin = GetOatFileBegin();
1000 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001001 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -07001002 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001003 // Write out sections.
1004 size_t cur_pos = image_end_;
1005 // Add fields.
1006 auto fields_offset = cur_pos;
1007 CHECK_EQ(image_objects_offset_begin_ + GetBinSizeSum(kBinArtField), fields_offset);
1008 auto fields_size = bin_slot_sizes_[kBinArtField];
1009 cur_pos += fields_size;
Mathieu Chartier31e89252013-08-28 11:29:12 -07001010 // Return to write header at start of image with future location of image_roots. At this point,
Mathieu Chartierc7853442015-03-27 14:35:38 -07001011 // image_end_ is the size of the image (excluding bitmaps, ArtFields).
1012 /*
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -07001013 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -08001014 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
1015 heap_bytes_per_bitmap_byte;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001016 */
1017 const size_t bitmap_bytes = image_bitmap_->Size();
1018 auto bitmap_offset = RoundUp(cur_pos, kPageSize);
1019 auto bitmap_size = RoundUp(bitmap_bytes, kPageSize);
1020 cur_pos += bitmap_size;
Vladimir Markof4da6752014-08-01 19:04:18 +01001021 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
1022 static_cast<uint32_t>(image_end_),
Mathieu Chartierc7853442015-03-27 14:35:38 -07001023 fields_offset, fields_size,
1024 bitmap_offset, bitmap_size,
Vladimir Markof4da6752014-08-01 19:04:18 +01001025 image_roots_address_,
1026 oat_file_->GetOatHeader().GetChecksum(),
1027 PointerToLowMemUInt32(oat_file_begin),
1028 PointerToLowMemUInt32(oat_data_begin_),
1029 PointerToLowMemUInt32(oat_data_end),
Igor Murashkin46774762014-10-22 11:37:02 -07001030 PointerToLowMemUInt32(oat_file_end),
1031 compile_pic_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001032}
1033
Mathieu Chartierc7853442015-03-27 14:35:38 -07001034void ImageWriter::CopyAndFixupNativeData() {
1035 // Copy ArtFields to their locations and update the array for convenience.
1036 auto fields_offset = image_objects_offset_begin_ + GetBinSizeSum(kBinArtField);
1037 for (auto& pair : art_field_reloc_) {
1038 pair.second += fields_offset;
1039 auto* dest = image_->Begin() + pair.second;
1040 DCHECK_GE(dest, image_->Begin() + image_end_);
1041 memcpy(dest, pair.first, sizeof(ArtField));
1042 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1043 down_cast<Class*>(GetImageAddress(pair.first->GetDeclaringClass())));
1044 }
1045}
1046
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001047void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001048 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001049 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1050 // Fix up the object previously had hash codes.
1051 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001052 Object* obj = hash_pair.first;
1053 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0U);
1054 obj->SetLockWord(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001055 }
1056 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001057}
1058
Mathieu Chartier590fee92013-09-13 13:46:47 -07001059void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001060 DCHECK(obj != nullptr);
1061 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001062 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1063}
1064
1065bool ImageWriter::CopyAndFixupIfDexCacheFieldArray(mirror::Object* dst, mirror::Object* obj,
1066 mirror::Class* klass) {
1067 if (!klass->IsArrayClass()) {
1068 return false;
1069 }
1070 auto* component_type = klass->GetComponentType();
1071 bool is_int_arr = component_type->IsPrimitiveInt();
1072 bool is_long_arr = component_type->IsPrimitiveLong();
1073 if (!is_int_arr && !is_long_arr) {
1074 return false;
1075 }
1076 auto it = dex_cache_array_indexes_.find(obj); // Is this a dex cache array?
1077 if (it == dex_cache_array_indexes_.end()) {
1078 return false;
1079 }
1080 mirror::Array* arr = obj->AsArray();
1081 CHECK_EQ(reinterpret_cast<Object*>(
1082 image_->Begin() + it->second.offset_ + image_objects_offset_begin_), dst);
1083 dex_cache_array_indexes_.erase(it);
1084 // Fixup int pointers for the field array.
1085 CHECK(!arr->IsObjectArray());
1086 const size_t num_elements = arr->GetLength();
1087 if (target_ptr_size_ == 4) {
1088 // Will get fixed up by fixup object.
1089 dst->SetClass(down_cast<mirror::Class*>(
1090 GetImageAddress(mirror::IntArray::GetArrayClass())));
1091 } else {
1092 DCHECK_EQ(target_ptr_size_, 8u);
1093 dst->SetClass(down_cast<mirror::Class*>(
1094 GetImageAddress(mirror::LongArray::GetArrayClass())));
1095 }
1096 mirror::Array* dest_array = down_cast<mirror::Array*>(dst);
1097 dest_array->SetLength(num_elements);
1098 for (size_t i = 0, count = num_elements; i < count; ++i) {
1099 ArtField* field = reinterpret_cast<ArtField*>(is_int_arr ?
1100 arr->AsIntArray()->GetWithoutChecks(i) : arr->AsLongArray()->GetWithoutChecks(i));
1101 uint8_t* fixup_location = nullptr;
1102 if (field != nullptr) {
1103 auto it2 = art_field_reloc_.find(field);
1104 CHECK(it2 != art_field_reloc_.end()) << "No relocation for field " << PrettyField(field);
1105 fixup_location = image_begin_ + it2->second;
1106 }
1107 if (target_ptr_size_ == 4) {
1108 down_cast<mirror::IntArray*>(dest_array)->SetWithoutChecks<kVerifyNone>(
1109 i, static_cast<uint32_t>(reinterpret_cast<uint64_t>(fixup_location)));
1110 } else {
1111 down_cast<mirror::LongArray*>(dest_array)->SetWithoutChecks<kVerifyNone>(
1112 i, reinterpret_cast<uint64_t>(fixup_location));
1113 }
1114 }
1115 dst->SetLockWord(LockWord::Default(), false);
1116 return true;
1117}
1118
1119void ImageWriter::CopyAndFixupObject(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001120 // see GetLocalAddress for similar computation
Mathieu Chartierc7853442015-03-27 14:35:38 -07001121 size_t offset = GetImageOffset(obj);
1122 auto* dst = reinterpret_cast<Object*>(image_->Begin() + offset);
Ian Rogers13735952014-10-08 12:43:28 -07001123 const uint8_t* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001124 size_t n;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001125 mirror::Class* klass = obj->GetClass();
1126
1127 if (CopyAndFixupIfDexCacheFieldArray(dst, obj, klass)) {
1128 return;
1129 }
1130 if (klass->IsArtMethodClass()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001131 // Size without pointer fields since we don't want to overrun the buffer if target art method
1132 // is 32 bits but source is 64 bits.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001133 n = mirror::ArtMethod::SizeWithoutPointerFields(target_ptr_size_);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001134 } else {
1135 n = obj->SizeOf();
1136 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001137 DCHECK_LE(offset + n, image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001138 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001139
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001140 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1141 // word.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001142 dst->SetLockWord(LockWord::Default(), false);
1143 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001144}
1145
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001146// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001147class FixupVisitor {
1148 public:
1149 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1150 }
1151
1152 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
1153 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001154 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001155 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1156 // image.
1157 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001158 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001159 }
1160
1161 // java.lang.ref.Reference visitor.
1162 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
1163 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1164 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1165 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001166 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001167 }
1168
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001169 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001170 ImageWriter* const image_writer_;
1171 mirror::Object* const copy_;
1172};
1173
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001174class FixupClassVisitor FINAL : public FixupVisitor {
1175 public:
1176 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1177 }
1178
Mathieu Chartierc7853442015-03-27 14:35:38 -07001179 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001180 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1181 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001182 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001183 }
1184
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001185 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1186 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001187 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1188 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1189 LOG(FATAL) << "Reference not expected here.";
1190 }
1191};
1192
Mathieu Chartierc7853442015-03-27 14:35:38 -07001193void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
1194 // Copy and fix up ArtFields in the class.
1195 ArtField* fields[2] = { orig->AsClass()->GetSFields(), orig->AsClass()->GetIFields() };
1196 size_t num_fields[2] = { orig->AsClass()->NumStaticFields(),
1197 orig->AsClass()->NumInstanceFields() };
1198 // Update the arrays.
1199 for (size_t i = 0; i < 2; ++i) {
1200 if (num_fields[i] == 0) {
1201 CHECK(fields[i] == nullptr);
1202 continue;
1203 }
1204 auto it = art_field_reloc_.find(fields[i]);
1205 CHECK(it != art_field_reloc_.end()) << PrettyClass(orig->AsClass()) << " : "
1206 << PrettyField(fields[i]);
1207 auto* image_fields = reinterpret_cast<ArtField*>(image_begin_ + it->second);
1208 if (i == 0) {
1209 down_cast<Class*>(copy)->SetSFieldsUnchecked(image_fields);
1210 } else {
1211 down_cast<Class*>(copy)->SetIFieldsUnchecked(image_fields);
1212 }
1213 }
1214 FixupClassVisitor visitor(this, copy);
1215 static_cast<mirror::Object*>(orig)->VisitReferences<true /*visit class*/>(visitor, visitor);
1216}
1217
Ian Rogersef7d42f2014-01-06 12:55:46 -08001218void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001219 DCHECK(orig != nullptr);
1220 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001221 if (kUseBakerOrBrooksReadBarrier) {
1222 orig->AssertReadBarrierPointer();
1223 if (kUseBrooksReadBarrier) {
1224 // Note the address 'copy' isn't the same as the image address of 'orig'.
1225 copy->SetReadBarrierPointer(GetImageAddress(orig));
1226 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1227 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001228 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001229 if (orig->IsClass()) {
1230 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001231 } else {
1232 FixupVisitor visitor(this, copy);
1233 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
1234 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001235 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001236 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001237 }
1238}
1239
Ian Rogers13735952014-10-08 12:43:28 -07001240const uint8_t* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001241 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001242 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001243
1244 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1245 // trampoline.
1246
1247 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001248 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1249 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
1250 const uint8_t* quick_code = GetOatAddress(quick_oat_code_offset);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001251 *quick_is_interpreted = false;
1252 if (quick_code != nullptr &&
1253 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
1254 // We have code for a non-static or initialized method, just use the code.
1255 } else if (quick_code == nullptr && method->IsNative() &&
1256 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1257 // Non-static or initialized native method missing compiled code, use generic JNI version.
1258 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
1259 } else if (quick_code == nullptr && !method->IsNative()) {
1260 // We don't have code at all for a non-native method, use the interpreter.
1261 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
1262 *quick_is_interpreted = true;
1263 } else {
1264 CHECK(!method->GetDeclaringClass()->IsInitialized());
1265 // We have code for a static method, but need to go through the resolution stub for class
1266 // initialization.
1267 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
1268 }
1269 return quick_code;
1270}
1271
Ian Rogers13735952014-10-08 12:43:28 -07001272const uint8_t* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001273 // Calculate the quick entry point following the same logic as FixupMethod() below.
1274 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001275 Runtime* runtime = Runtime::Current();
1276 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001277 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001278 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
1279 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001280 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
1281 } else {
1282 // We assume all methods have code. If they don't currently then we set them to the use the
1283 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1284 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1285 if (UNLIKELY(method->IsAbstract())) {
1286 return GetOatAddress(quick_to_interpreter_bridge_offset_);
1287 } else {
1288 bool quick_is_interpreted;
1289 return GetQuickCode(method, &quick_is_interpreted);
1290 }
1291 }
1292}
1293
Ian Rogersef7d42f2014-01-06 12:55:46 -08001294void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -07001295 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1296 // oat_begin_
Mathieu Chartier2d721012014-11-10 11:08:06 -08001297 // For 64 bit targets we need to repack the current runtime pointer sized fields to the right
1298 // locations.
1299 // Copy all of the fields from the runtime methods to the target methods first since we did a
1300 // bytewise copy earlier.
Jeff Haoc7d11882015-02-03 15:08:39 -08001301 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1302 orig->GetEntryPointFromInterpreterPtrSize(target_ptr_size_), target_ptr_size_);
1303 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(
1304 orig->GetEntryPointFromJniPtrSize(target_ptr_size_), target_ptr_size_);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001305 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
Jeff Haoc7d11882015-02-03 15:08:39 -08001306 orig->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001307
Ian Rogers848871b2013-08-05 10:56:33 -07001308 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001309 Runtime* runtime = Runtime::Current();
1310 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001311 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1312 GetOatAddress(quick_resolution_trampoline_offset_), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001313 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1314 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001315 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1316 GetOatAddress(quick_imt_conflict_trampoline_offset_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001317 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001318 // We assume all methods have code. If they don't currently then we set them to the use the
1319 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1320 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1321 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001322 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1323 GetOatAddress(quick_to_interpreter_bridge_offset_), target_ptr_size_);
1324 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1325 reinterpret_cast<EntryPointFromInterpreter*>(const_cast<uint8_t*>(
1326 GetOatAddress(interpreter_to_interpreter_bridge_offset_))), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001327 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001328 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -07001329 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001330 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001331
Sebastien Hertze1d07812014-05-21 15:44:09 +02001332 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001333 if (orig->IsNative()) {
1334 // The native method's pointer is set to a stub to lookup via dlsym.
1335 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier2d721012014-11-10 11:08:06 -08001336 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_),
1337 target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001338 }
Sebastien Hertze1d07812014-05-21 15:44:09 +02001339
1340 // Interpreter entrypoint:
1341 // Set the interpreter entrypoint depending on whether there is compiled code or not.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001342 uint32_t interpreter_code = (quick_is_interpreted)
Sebastien Hertze1d07812014-05-21 15:44:09 +02001343 ? interpreter_to_interpreter_bridge_offset_
1344 : interpreter_to_compiled_code_bridge_offset_;
Mathieu Chartier2d721012014-11-10 11:08:06 -08001345 EntryPointFromInterpreter* interpreter_entrypoint =
Sebastien Hertze1d07812014-05-21 15:44:09 +02001346 reinterpret_cast<EntryPointFromInterpreter*>(
Mathieu Chartier2d721012014-11-10 11:08:06 -08001347 const_cast<uint8_t*>(GetOatAddress(interpreter_code)));
1348 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1349 interpreter_entrypoint, target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001350 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001351 }
1352}
1353
Alex Lighta59dd802014-07-02 16:28:08 -07001354static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001355 uint64_t data_sec_offset;
1356 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1357 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001358 return nullptr;
1359 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001360 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001361}
1362
Vladimir Markof4da6752014-08-01 19:04:18 +01001363void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001364 std::string error_msg;
1365 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
1366 MAP_SHARED, &error_msg));
1367 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001368 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001369 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001370 }
Alex Lighta59dd802014-07-02 16:28:08 -07001371 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1372 CHECK(oat_header != nullptr);
1373 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001374
Brian Carlstrom7940e442013-07-12 13:46:57 -07001375 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001376 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001377}
1378
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001379size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1380 DCHECK_LE(up_to, kBinSize);
1381 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1382}
1383
1384ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1385 // These values may need to get updated if more bins are added to the enum Bin
Vladimir Marko20f85592015-03-19 10:07:02 +00001386 static_assert(kBinBits == 4, "wrong number of bin bits");
1387 static_assert(kBinShift == 28, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001388 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1389
1390 DCHECK_LT(GetBin(), kBinSize);
1391 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1392}
1393
1394ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1395 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1396 DCHECK_EQ(index, GetIndex());
1397}
1398
1399ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1400 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1401}
1402
1403uint32_t ImageWriter::BinSlot::GetIndex() const {
1404 return lockword_ & ~kBinMask;
1405}
1406
Andreas Gampe245ee002014-12-04 21:25:04 -08001407void ImageWriter::FreeStringDataArray() {
1408 if (string_data_array_ != nullptr) {
1409 gc::space::LargeObjectSpace* los = Runtime::Current()->GetHeap()->GetLargeObjectsSpace();
1410 if (los != nullptr) {
1411 los->Free(Thread::Current(), reinterpret_cast<mirror::Object*>(string_data_array_));
1412 }
1413 }
1414}
1415
Brian Carlstrom7940e442013-07-12 13:46:57 -07001416} // namespace art