blob: 1ede228c4fb4c39b3b2283e38dcf225eb623ef6f [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
25#include "base/logging.h"
26#include "base/unix_file/fd_file.h"
27#include "class_linker.h"
28#include "compiled_method.h"
29#include "dex_file-inl.h"
30#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070031#include "elf_file.h"
32#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070033#include "elf_writer.h"
34#include "gc/accounting/card_table-inl.h"
35#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070036#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070037#include "gc/heap.h"
38#include "gc/space/large_object_space.h"
39#include "gc/space/space-inl.h"
40#include "globals.h"
41#include "image.h"
42#include "intern_table.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070043#include "lock_word.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070044#include "mirror/art_field-inl.h"
45#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "mirror/array-inl.h"
47#include "mirror/class-inl.h"
48#include "mirror/class_loader.h"
49#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "mirror/object-inl.h"
51#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070052#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070053#include "oat.h"
54#include "oat_file.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "runtime.h"
56#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070057#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000058#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059
Brian Carlstromea46f952013-07-30 01:26:50 -070060using ::art::mirror::ArtField;
61using ::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);
167 CopyAndFixupObjects();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700168 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
169
Vladimir Markof4da6752014-08-01 19:04:18 +0100170 SetOatChecksumFromElfFile(oat_file.get());
171
Andreas Gampe4303ba92014-11-06 01:00:46 -0800172 if (oat_file->FlushCloseOrErase() != 0) {
173 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename << " for " << oat_location;
174 return false;
175 }
176
Ian Rogers700a4022014-05-19 16:49:03 -0700177 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700178 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 if (image_file.get() == NULL) {
180 LOG(ERROR) << "Failed to open image file " << image_filename;
181 return false;
182 }
183 if (fchmod(image_file->Fd(), 0644) != 0) {
184 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800185 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700186 return EXIT_FAILURE;
187 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700188
189 // Write out the image.
190 CHECK_EQ(image_end_, image_header->GetImageSize());
191 if (!image_file->WriteFully(image_->Begin(), image_end_)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700192 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800193 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700194 return false;
195 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700196
197 // Write out the image bitmap at the page aligned start of the image end.
198 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
199 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
200 image_header->GetImageBitmapSize(),
201 image_header->GetImageBitmapOffset())) {
202 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800203 image_file->Erase();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700204 return false;
205 }
206
Andreas Gampe4303ba92014-11-06 01:00:46 -0800207 if (image_file->FlushCloseOrErase() != 0) {
208 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
209 return false;
210 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700211 return true;
212}
213
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800214void ImageWriter::SetImageOffset(mirror::Object* object,
215 ImageWriter::BinSlot bin_slot,
216 size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700217 DCHECK(object != nullptr);
218 DCHECK_NE(offset, 0U);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700219 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
220 DCHECK_ALIGNED(obj, kObjectAlignment);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800221
222 image_bitmap_->Set(obj); // Mark the obj as mutated, since we will end up changing it.
223 {
224 // Remember the object-inside-of-the-image's hash code so we can restore it after the copy.
225 auto hash_it = saved_hashes_map_.find(bin_slot);
226 if (hash_it != saved_hashes_map_.end()) {
227 std::pair<BinSlot, uint32_t> slot_hash = *hash_it;
228 saved_hashes_.push_back(std::make_pair(obj, slot_hash.second));
229 saved_hashes_map_.erase(hash_it);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700230 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700231 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800232 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700233 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700234 DCHECK(IsImageOffsetAssigned(object));
235}
236
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800237void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700238 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800239 DCHECK_NE(image_objects_offset_begin_, 0u);
240
Vladimir Marko20f85592015-03-19 10:07:02 +0000241 size_t previous_bin_sizes = bin_slot_previous_sizes_[bin_slot.GetBin()];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800242 size_t new_offset = image_objects_offset_begin_ + previous_bin_sizes + bin_slot.GetIndex();
243 DCHECK_ALIGNED(new_offset, kObjectAlignment);
244
245 SetImageOffset(object, bin_slot, new_offset);
246 DCHECK_LT(new_offset, image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700247}
248
Ian Rogersef7d42f2014-01-06 12:55:46 -0800249bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800250 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700251 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700252 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700253}
254
Ian Rogersef7d42f2014-01-06 12:55:46 -0800255size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700256 DCHECK(object != nullptr);
257 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700258 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700259 size_t offset = lock_word.ForwardingAddress();
260 DCHECK_LT(offset, image_end_);
261 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700262}
263
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800264void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
265 DCHECK(object != nullptr);
266 DCHECK(!IsImageOffsetAssigned(object));
267 DCHECK(!IsImageBinSlotAssigned(object));
268
269 // Before we stomp over the lock word, save the hash code for later.
270 Monitor::Deflate(Thread::Current(), object);;
271 LockWord lw(object->GetLockWord(false));
272 switch (lw.GetState()) {
273 case LockWord::kFatLocked: {
274 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
275 break;
276 }
277 case LockWord::kThinLocked: {
278 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
279 break;
280 }
281 case LockWord::kUnlocked:
282 // No hash, don't need to save it.
283 break;
284 case LockWord::kHashCode:
285 saved_hashes_map_[bin_slot] = lw.GetHashCode();
286 break;
287 default:
288 LOG(FATAL) << "Unreachable.";
289 UNREACHABLE();
290 }
291 object->SetLockWord(LockWord::FromForwardingAddress(static_cast<uint32_t>(bin_slot)),
292 false);
293 DCHECK(IsImageBinSlotAssigned(object));
294}
295
Vladimir Marko20f85592015-03-19 10:07:02 +0000296void ImageWriter::PrepareDexCacheArraySlots() {
297 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
298 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
299 size_t dex_cache_count = class_linker->GetDexCacheCount();
300 uint32_t size = 0u;
301 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
302 DexCache* dex_cache = class_linker->GetDexCache(idx);
303 const DexFile* dex_file = dex_cache->GetDexFile();
304 dex_cache_array_starts_.Put(dex_file, size);
305 DexCacheArraysLayout layout(dex_file);
306 DCHECK(layout.Valid());
307 dex_cache_array_indexes_.Put(dex_cache->GetResolvedTypes(), size + layout.TypesOffset());
308 dex_cache_array_indexes_.Put(dex_cache->GetResolvedMethods(), size + layout.MethodsOffset());
309 dex_cache_array_indexes_.Put(dex_cache->GetResolvedFields(), size + layout.FieldsOffset());
310 dex_cache_array_indexes_.Put(dex_cache->GetStrings(), size + layout.StringsOffset());
311 size += layout.Size();
312 }
313 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
314 // when AssignImageBinSlot() assigns their indexes out or order.
315 bin_slot_sizes_[kBinDexCacheArray] = size;
316}
317
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800318void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
319 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800320 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800321
322 // The magic happens here. We segregate objects into different bins based
323 // on how likely they are to get dirty at runtime.
324 //
325 // Likely-to-dirty objects get packed together into the same bin so that
326 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
327 // maximized.
328 //
329 // This means more pages will stay either clean or shared dirty (with zygote) and
330 // the app will use less of its own (private) memory.
331 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000332 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800333
334 if (kBinObjects) {
335 //
336 // Changing the bin of an object is purely a memory-use tuning.
337 // It has no change on runtime correctness.
338 //
339 // Memory analysis has determined that the following types of objects get dirtied
340 // the most:
341 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000342 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
343 // a fixed layout which helps improve generated code (using PC-relative addressing),
344 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
345 // Since these arrays are huge, most pages do not overlap other objects and it's not
346 // really important where they are for the clean/dirty separation. Due to their
347 // special PC-relative addressing, we arbitrarily keep them at the beginning.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800348 // * Class'es which are verified [their clinit runs only at runtime]
349 // - classes in general [because their static fields get overwritten]
350 // - initialized classes with all-final statics are unlikely to be ever dirty,
351 // so bin them separately
352 // * Art Methods that are:
353 // - native [their native entry point is not looked up until runtime]
354 // - have declaring classes that aren't initialized
355 // [their interpreter/quick entry points are trampolines until the class
356 // becomes initialized]
357 //
358 // We also assume the following objects get dirtied either never or extremely rarely:
359 // * Strings (they are immutable)
360 // * Art methods that aren't native and have initialized declared classes
361 //
362 // We assume that "regular" bin objects are highly unlikely to become dirtied,
363 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
364 //
365 if (object->IsClass()) {
366 bin = kBinClassVerified;
367 mirror::Class* klass = object->AsClass();
368
369 if (klass->GetStatus() == Class::kStatusInitialized) {
370 bin = kBinClassInitialized;
371
372 // If the class's static fields are all final, put it into a separate bin
373 // since it's very likely it will stay clean.
374 uint32_t num_static_fields = klass->NumStaticFields();
375 if (num_static_fields == 0) {
376 bin = kBinClassInitializedFinalStatics;
377 } else {
378 // Maybe all the statics are final?
379 bool all_final = true;
380 for (uint32_t i = 0; i < num_static_fields; ++i) {
381 ArtField* field = klass->GetStaticField(i);
382 if (!field->IsFinal()) {
383 all_final = false;
384 break;
385 }
386 }
387
388 if (all_final) {
389 bin = kBinClassInitializedFinalStatics;
390 }
391 }
392 }
393 } else if (object->IsArtMethod<kVerifyNone>()) {
394 mirror::ArtMethod* art_method = down_cast<ArtMethod*>(object);
395 if (art_method->IsNative()) {
396 bin = kBinArtMethodNative;
397 } else {
398 mirror::Class* declaring_class = art_method->GetDeclaringClass();
399 if (declaring_class->GetStatus() != Class::kStatusInitialized) {
400 bin = kBinArtMethodNotInitialized;
401 } else {
402 // This is highly unlikely to dirty since there's no entry points to mutate.
403 bin = kBinArtMethodsManagedInitialized;
404 }
405 }
406 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
407 bin = kBinString; // Strings are almost always immutable (except for object header).
Vladimir Marko20f85592015-03-19 10:07:02 +0000408 } else if (object->IsObjectArray()) {
409 auto it = dex_cache_array_indexes_.find(object);
410 if (it != dex_cache_array_indexes_.end()) {
411 bin = kBinDexCacheArray;
412 current_offset = it->second; // Use prepared offset defined by the DexCacheLayout.
413 } // else bin = kBinRegular
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800414 } // else bin = kBinRegular
415 }
416
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800417 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Vladimir Marko20f85592015-03-19 10:07:02 +0000418 if (bin != kBinDexCacheArray) {
419 current_offset = bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
420 // Move the current bin size up to accomodate the object we just assigned a bin slot.
421 bin_slot_sizes_[bin] += offset_delta;
422 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800423
424 BinSlot new_bin_slot(bin, current_offset);
425 SetImageBinSlot(object, new_bin_slot);
426
427 ++bin_slot_count_[bin];
428
429 DCHECK_LT(GetBinSizeSum(), image_->Size());
430
431 // Grow the image closer to the end by the object we just assigned.
432 image_end_ += offset_delta;
433 DCHECK_LT(image_end_, image_->Size());
434}
435
436bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
437 DCHECK(object != nullptr);
438
439 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
440 // If it's in some other state, then we haven't yet assigned an image bin slot.
441 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
442 return false;
443 } else if (kIsDebugBuild) {
444 LockWord lock_word = object->GetLockWord(false);
445 size_t offset = lock_word.ForwardingAddress();
446 BinSlot bin_slot(offset);
447 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()])
448 << "bin slot offset should not exceed the size of that bin";
449 }
450 return true;
451}
452
453ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
454 DCHECK(object != nullptr);
455 DCHECK(IsImageBinSlotAssigned(object));
456
457 LockWord lock_word = object->GetLockWord(false);
458 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
459 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
460
461 BinSlot bin_slot(static_cast<uint32_t>(offset));
462 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()]);
463
464 return bin_slot;
465}
466
Brian Carlstrom7940e442013-07-12 13:46:57 -0700467bool ImageWriter::AllocMemory() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700468 size_t length = RoundUp(Runtime::Current()->GetHeap()->GetTotalMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700469 std::string error_msg;
Vladimir Marko5c42c292015-02-25 12:02:49 +0000470 image_.reset(MemMap::MapAnonymous("image writer image", nullptr, length, PROT_READ | PROT_WRITE,
471 false, false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700472 if (UNLIKELY(image_.get() == nullptr)) {
473 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700474 return false;
475 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700476
477 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700478 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
479 length));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700480 if (image_bitmap_.get() == nullptr) {
481 LOG(ERROR) << "Failed to allocate memory for image bitmap";
482 return false;
483 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700484 return true;
485}
486
487void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700488 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700489 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
490}
491
492bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700493 Thread* self = Thread::Current();
494 StackHandleScope<1> hs(self);
495 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700496 return true;
497}
498
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800499// Count the number of strings in the heap and put the result in arg as a size_t pointer.
500static void CountStringsCallback(Object* obj, void* arg)
501 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
502 if (obj->GetClass()->IsStringClass()) {
503 ++*reinterpret_cast<size_t*>(arg);
504 }
505}
506
507// Collect all the java.lang.String in the heap and put them in the output strings_ array.
508class StringCollector {
509 public:
510 StringCollector(Handle<mirror::ObjectArray<mirror::String>> strings, size_t index)
511 : strings_(strings), index_(index) {
512 }
513 static void Callback(Object* obj, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
514 auto* collector = reinterpret_cast<StringCollector*>(arg);
515 if (obj->GetClass()->IsStringClass()) {
516 collector->strings_->SetWithoutChecks<false>(collector->index_++, obj->AsString());
517 }
518 }
519 size_t GetIndex() const {
520 return index_;
521 }
522
523 private:
524 Handle<mirror::ObjectArray<mirror::String>> strings_;
525 size_t index_;
526};
527
528// Compare strings based on length, used for sorting strings by length / reverse length.
Vladimir Markofaeda182014-12-04 14:52:25 +0000529class LexicographicalStringComparator {
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800530 public:
Vladimir Markofaeda182014-12-04 14:52:25 +0000531 bool operator()(const mirror::HeapReference<mirror::String>& lhs,
532 const mirror::HeapReference<mirror::String>& rhs) const
533 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
534 mirror::String* lhs_s = lhs.AsMirrorPtr();
535 mirror::String* rhs_s = rhs.AsMirrorPtr();
536 uint16_t* lhs_begin = lhs_s->GetCharArray()->GetData() + lhs_s->GetOffset();
537 uint16_t* rhs_begin = rhs_s->GetCharArray()->GetData() + rhs_s->GetOffset();
538 return std::lexicographical_compare(lhs_begin, lhs_begin + lhs_s->GetLength(),
539 rhs_begin, rhs_begin + rhs_s->GetLength());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800540 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800541};
542
Vladimir Markofaeda182014-12-04 14:52:25 +0000543static bool IsPrefix(mirror::String* pref, mirror::String* full)
544 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
545 if (pref->GetLength() > full->GetLength()) {
546 return false;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800547 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000548 uint16_t* pref_begin = pref->GetCharArray()->GetData() + pref->GetOffset();
549 uint16_t* full_begin = full->GetCharArray()->GetData() + full->GetOffset();
550 return std::equal(pref_begin, pref_begin + pref->GetLength(), full_begin);
551}
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800552
553void ImageWriter::ProcessStrings() {
554 size_t total_strings = 0;
555 gc::Heap* heap = Runtime::Current()->GetHeap();
556 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800557 // Count the strings.
558 heap->VisitObjects(CountStringsCallback, &total_strings);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800559 Thread* self = Thread::Current();
560 StackHandleScope<1> hs(self);
561 auto strings = hs.NewHandle(cl->AllocStringArray(self, total_strings));
562 StringCollector string_collector(strings, 0U);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800563 // Read strings into the array.
564 heap->VisitObjects(StringCollector::Callback, &string_collector);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800565 // Some strings could have gotten freed if AllocStringArray caused a GC.
566 CHECK_LE(string_collector.GetIndex(), total_strings);
567 total_strings = string_collector.GetIndex();
Vladimir Markofaeda182014-12-04 14:52:25 +0000568 auto* strings_begin = reinterpret_cast<mirror::HeapReference<mirror::String>*>(
569 strings->GetRawData(sizeof(mirror::HeapReference<mirror::String>), 0));
570 std::sort(strings_begin, strings_begin + total_strings, LexicographicalStringComparator());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800571 // Characters of strings which are non equal prefix of another string (not the same string).
572 // We don't count the savings from equal strings since these would get interned later anyways.
573 size_t prefix_saved_chars = 0;
Vladimir Markofaeda182014-12-04 14:52:25 +0000574 // Count characters needed for the strings.
575 size_t num_chars = 0u;
576 mirror::String* prev_s = nullptr;
577 for (size_t idx = 0; idx != total_strings; ++idx) {
578 mirror::String* s = strings->GetWithoutChecks(idx);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800579 size_t length = s->GetLength();
Vladimir Markofaeda182014-12-04 14:52:25 +0000580 num_chars += length;
581 if (prev_s != nullptr && IsPrefix(prev_s, s)) {
582 size_t prev_length = prev_s->GetLength();
583 num_chars -= prev_length;
584 if (prev_length != length) {
585 prefix_saved_chars += prev_length;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800586 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800587 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000588 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800589 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000590 // Create character array, copy characters and point the strings there.
591 mirror::CharArray* array = mirror::CharArray::Alloc(self, num_chars);
Andreas Gampe245ee002014-12-04 21:25:04 -0800592 string_data_array_ = array;
Vladimir Markofaeda182014-12-04 14:52:25 +0000593 uint16_t* array_data = array->GetData();
594 size_t pos = 0u;
595 prev_s = nullptr;
596 for (size_t idx = 0; idx != total_strings; ++idx) {
597 mirror::String* s = strings->GetWithoutChecks(idx);
598 uint16_t* s_data = s->GetCharArray()->GetData() + s->GetOffset();
599 int32_t s_length = s->GetLength();
600 int32_t prefix_length = 0u;
601 if (idx != 0u && IsPrefix(prev_s, s)) {
602 prefix_length = prev_s->GetLength();
603 }
604 memcpy(array_data + pos, s_data + prefix_length, (s_length - prefix_length) * sizeof(*s_data));
605 s->SetOffset(pos - prefix_length);
606 s->SetArray(array);
607 pos += s_length - prefix_length;
608 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800609 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000610 CHECK_EQ(pos, num_chars);
611
Andreas Gampedc843012015-01-20 16:17:19 -0800612 if (kIsDebugBuild || VLOG_IS_ON(compiler)) {
613 LOG(INFO) << "Total # image strings=" << total_strings << " combined length="
614 << num_chars << " prefix saved chars=" << prefix_saved_chars;
615 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800616 ComputeEagerResolvedStrings();
617}
618
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700619void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700620 if (!obj->GetClass()->IsStringClass()) {
621 return;
622 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700623 mirror::String* string = obj->AsString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700624 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
Vladimir Markoa48aef42014-12-03 17:53:53 +0000625 size_t utf16_length = static_cast<size_t>(string->GetLength());
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700626 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
627 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
628 size_t dex_cache_count = class_linker->GetDexCacheCount();
629 for (size_t i = 0; i < dex_cache_count; ++i) {
630 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700631 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800632 const DexFile::StringId* string_id;
Vladimir Markoa48aef42014-12-03 17:53:53 +0000633 if (UNLIKELY(utf16_length == 0)) {
Ian Rogers24c534d2013-11-14 00:15:00 -0800634 string_id = dex_file.FindStringId("");
635 } else {
Vladimir Markoa48aef42014-12-03 17:53:53 +0000636 string_id = dex_file.FindStringId(utf16_string, utf16_length);
Ian Rogers24c534d2013-11-14 00:15:00 -0800637 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700638 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700639 // This string occurs in this dex file, assign the dex cache entry.
640 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
641 if (dex_cache->GetResolvedString(string_idx) == NULL) {
642 dex_cache->SetResolvedString(string_idx, string);
643 }
644 }
645 }
646}
647
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800648void ImageWriter::ComputeEagerResolvedStrings() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700649 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700650}
651
Ian Rogersef7d42f2014-01-06 12:55:46 -0800652bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700653 std::string temp;
654 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700655}
656
657struct NonImageClasses {
658 ImageWriter* image_writer;
659 std::set<std::string>* non_image_classes;
660};
661
662void ImageWriter::PruneNonImageClasses() {
663 if (compiler_driver_.GetImageClasses() == NULL) {
664 return;
665 }
666 Runtime* runtime = Runtime::Current();
667 ClassLinker* class_linker = runtime->GetClassLinker();
668
669 // Make a list of classes we would like to prune.
670 std::set<std::string> non_image_classes;
671 NonImageClasses context;
672 context.image_writer = this;
673 context.non_image_classes = &non_image_classes;
674 class_linker->VisitClasses(NonImageClassesVisitor, &context);
675
676 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700677 for (const std::string& it : non_image_classes) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800678 bool result = class_linker->RemoveClass(it.c_str(), NULL);
679 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700680 }
681
682 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700683 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700684 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
685 size_t dex_cache_count = class_linker->GetDexCacheCount();
686 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
687 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700688 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
689 Class* klass = dex_cache->GetResolvedType(i);
690 if (klass != NULL && !IsImageClass(klass)) {
691 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700692 }
693 }
694 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700695 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700696 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
697 dex_cache->SetResolvedMethod(i, resolution_method);
698 }
699 }
700 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700701 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700702 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
703 dex_cache->SetResolvedField(i, NULL);
704 }
705 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700706 // Clean the dex field. It might have been populated during the initialization phase, but
707 // contains data only valid during a real run.
708 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700709 }
710}
711
712bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
713 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
714 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700715 std::string temp;
716 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700717 }
718 return true;
719}
720
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800721void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700722 if (compiler_driver_.GetImageClasses() != nullptr) {
723 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700724 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700725 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700726}
727
728void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
729 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700730 if (obj->IsClass()) {
731 Class* klass = obj->AsClass();
732 if (!image_writer->IsImageClass(klass)) {
733 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700734 std::string temp;
735 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700736 << " " << PrettyDescriptor(klass);
737 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700738 }
739}
740
741void ImageWriter::DumpImageClasses() {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700742 const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700743 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700744 for (const std::string& image_class : *image_classes) {
745 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700746 }
747}
748
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800749void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700750 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700751 // if it is a string, we want to intern it if its not interned.
752 if (obj->GetClass()->IsStringClass()) {
753 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800754 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700755 DCHECK_EQ(obj, obj->AsString()->Intern());
756 return;
757 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700758 mirror::String* const interned = obj->AsString()->Intern();
759 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800760 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700761 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800762 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700763 }
764 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800765 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700766 return;
767 }
768 // else (obj == interned), nothing to do but fall through to the normal case
769 }
770
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800771 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700772}
773
774ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
775 Runtime* runtime = Runtime::Current();
776 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700777 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700778 StackHandleScope<3> hs(self);
779 Handle<Class> object_array_class(hs.NewHandle(
780 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700781
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700782 // build an Object[] of all the DexCaches used in the source_space_.
783 // Since we can't hold the dex lock when allocating the dex_caches
784 // ObjectArray, we lock the dex lock twice, first to get the number
785 // of dex caches first and then lock it again to copy the dex
786 // caches. We check that the number of dex caches does not change.
787 size_t dex_cache_count;
788 {
789 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
790 dex_cache_count = class_linker->GetDexCacheCount();
791 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700792 Handle<ObjectArray<Object>> dex_caches(
793 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700794 dex_cache_count)));
795 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
796 {
797 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
798 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
799 << "The number of dex caches changed.";
800 for (size_t i = 0; i < dex_cache_count; ++i) {
801 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
802 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700803 }
804
805 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700806 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700807 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100808 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
809 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700810 image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
811 runtime->GetImtUnimplementedMethod());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100812 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
813 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
814 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
815 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
816 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
817 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
818 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700819 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100820 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700821 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
822 CHECK(image_roots->Get(i) != NULL);
823 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700824 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700825}
826
Mathieu Chartier590fee92013-09-13 13:46:47 -0700827// Walk instance fields of the given Class. Separate function to allow recursion on the super
828// class.
829void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
830 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700831 StackHandleScope<1> hs(Thread::Current());
832 Handle<mirror::Class> h_class(hs.NewHandle(klass));
833 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700834 if (super != nullptr) {
835 WalkInstanceFields(obj, super);
836 }
837 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700838 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000839 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700840 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700841 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700842 if (value != nullptr) {
843 WalkFieldsInOrder(value);
844 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000845 field_offset = MemberOffset(field_offset.Uint32Value() +
846 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700847 }
848}
849
850// For an unvisited object, visit it then all its children found via fields.
851void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800852 // Use our own visitor routine (instead of GC visitor) to get better locality between
853 // an object and its fields
854 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700855 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700856 StackHandleScope<2> hs(Thread::Current());
857 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
858 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700859 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800860 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700861 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700862 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700863 if (h_obj->IsClass()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700864 size_t num_static_fields = klass->NumReferenceStaticFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000865 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700866 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700867 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700868 if (value != nullptr) {
869 WalkFieldsInOrder(value);
870 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000871 field_offset = MemberOffset(field_offset.Uint32Value() +
872 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700873 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700874 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700875 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700876 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700877 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700878 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700879 mirror::Object* value = obj_array->Get(i);
880 if (value != nullptr) {
881 WalkFieldsInOrder(value);
882 }
883 }
884 }
885 }
886}
887
888void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
889 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
890 DCHECK(writer != nullptr);
891 writer->WalkFieldsInOrder(obj);
892}
893
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800894void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
895 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
896 DCHECK(writer != nullptr);
897 writer->UnbinObjectsIntoOffset(obj);
898}
899
900void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
901 CHECK(obj != nullptr);
902
903 // We know the bin slot, and the total bin sizes for all objects by now,
904 // so calculate the object's final image offset.
905
906 DCHECK(IsImageBinSlotAssigned(obj));
907 BinSlot bin_slot = GetImageBinSlot(obj);
908 // Change the lockword from a bin slot into an offset
909 AssignImageOffset(obj, bin_slot);
910}
911
Vladimir Markof4da6752014-08-01 19:04:18 +0100912void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700913 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700914 StackHandleScope<1> hs(self);
915 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700916
917 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700918 DCHECK_EQ(0U, image_end_);
919
Mathieu Chartier31e89252013-08-28 11:29:12 -0700920 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700921 // know where image_roots is going to end up
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800922 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700923
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800924 // TODO: Image spaces only?
925 DCHECK_LT(image_end_, image_->Size());
926 image_objects_offset_begin_ = image_end_;
Vladimir Marko20f85592015-03-19 10:07:02 +0000927 // Prepare bin slots for dex cache arrays.
928 PrepareDexCacheArraySlots();
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800929 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
930 heap->VisitObjects(WalkFieldsCallback, this);
Vladimir Marko20f85592015-03-19 10:07:02 +0000931 // Calculate cumulative bin slot sizes.
932 size_t previous_sizes = 0u;
933 for (size_t i = 0; i != kBinSize; ++i) {
934 bin_slot_previous_sizes_[i] = previous_sizes;
935 previous_sizes += bin_slot_sizes_[i];
936 }
937 DCHECK_EQ(previous_sizes, GetBinSizeSum());
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800938 // Transform each object's bin slot into an offset which will be used to do the final copy.
939 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
940 DCHECK(saved_hashes_map_.empty()); // All binslot hashes should've been put into vector by now.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700941
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800942 DCHECK_GT(image_end_, GetBinSizeSum());
943
Vladimir Markof4da6752014-08-01 19:04:18 +0100944 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
945
946 // Note that image_end_ is left at end of used space
947}
948
949void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
950 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -0700951 const uint8_t* oat_file_begin = GetOatFileBegin();
952 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800953
Brian Carlstrom7940e442013-07-12 13:46:57 -0700954 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -0700955 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700956
Mathieu Chartier31e89252013-08-28 11:29:12 -0700957 // Return to write header at start of image with future location of image_roots. At this point,
958 // image_end_ is the size of the image (excluding bitmaps).
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700959 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800960 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
961 heap_bytes_per_bitmap_byte;
Vladimir Markof4da6752014-08-01 19:04:18 +0100962 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
963 static_cast<uint32_t>(image_end_),
964 RoundUp(image_end_, kPageSize),
965 RoundUp(bitmap_bytes, kPageSize),
966 image_roots_address_,
967 oat_file_->GetOatHeader().GetChecksum(),
968 PointerToLowMemUInt32(oat_file_begin),
969 PointerToLowMemUInt32(oat_data_begin_),
970 PointerToLowMemUInt32(oat_data_end),
Igor Murashkin46774762014-10-22 11:37:02 -0700971 PointerToLowMemUInt32(oat_file_end),
972 compile_pic_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700973}
974
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800975void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700976 gc::Heap* heap = Runtime::Current()->GetHeap();
977 // TODO: heap validation can't handle this fix up pass
978 heap->DisableObjectValidation();
979 // TODO: Image spaces only?
Mathieu Chartier590fee92013-09-13 13:46:47 -0700980 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
981 // Fix up the object previously had hash codes.
982 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800983 Object* obj = hash_pair.first;
984 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0U);
985 obj->SetLockWord(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700986 }
987 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700988}
989
Mathieu Chartier590fee92013-09-13 13:46:47 -0700990void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700991 DCHECK(obj != nullptr);
992 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700993 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700994 // see GetLocalAddress for similar computation
995 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers13735952014-10-08 12:43:28 -0700996 uint8_t* dst = image_writer->image_->Begin() + offset;
997 const uint8_t* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800998 size_t n;
999 if (obj->IsArtMethod()) {
1000 // Size without pointer fields since we don't want to overrun the buffer if target art method
1001 // is 32 bits but source is 64 bits.
Jeff Haoc7d11882015-02-03 15:08:39 -08001002 n = mirror::ArtMethod::SizeWithoutPointerFields(image_writer->target_ptr_size_);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001003 } else {
1004 n = obj->SizeOf();
1005 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001006 DCHECK_LT(offset + n, image_writer->image_->Size());
1007 memcpy(dst, src, n);
1008 Object* copy = reinterpret_cast<Object*>(dst);
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001009 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1010 // word.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001011 copy->SetLockWord(LockWord::Default(), false);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001012 image_writer->FixupObject(obj, copy);
1013}
1014
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001015// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001016class FixupVisitor {
1017 public:
1018 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1019 }
1020
1021 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
1022 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001023 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001024 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1025 // image.
1026 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001027 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001028 }
1029
1030 // java.lang.ref.Reference visitor.
1031 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
1032 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1033 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1034 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001035 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001036 }
1037
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001038 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001039 ImageWriter* const image_writer_;
1040 mirror::Object* const copy_;
1041};
1042
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001043class FixupClassVisitor FINAL : public FixupVisitor {
1044 public:
1045 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1046 }
1047
1048 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
1049 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1050 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001051 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001052
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001053 // TODO: Remove dead code
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001054 if (offset.Uint32Value() < mirror::Class::EmbeddedVTableOffset().Uint32Value()) {
1055 return;
1056 }
1057 }
1058
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001059 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1060 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001061 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1062 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1063 LOG(FATAL) << "Reference not expected here.";
1064 }
1065};
1066
Ian Rogersef7d42f2014-01-06 12:55:46 -08001067void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001068 DCHECK(orig != nullptr);
1069 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001070 if (kUseBakerOrBrooksReadBarrier) {
1071 orig->AssertReadBarrierPointer();
1072 if (kUseBrooksReadBarrier) {
1073 // Note the address 'copy' isn't the same as the image address of 'orig'.
1074 copy->SetReadBarrierPointer(GetImageAddress(orig));
1075 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1076 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001077 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001078 if (orig->IsClass() && orig->AsClass()->ShouldHaveEmbeddedImtAndVTable()) {
1079 FixupClassVisitor visitor(this, copy);
1080 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
1081 } else {
1082 FixupVisitor visitor(this, copy);
1083 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
1084 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001085 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001086 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001087 }
1088}
1089
Ian Rogers13735952014-10-08 12:43:28 -07001090const uint8_t* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001091 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001092 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001093
1094 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1095 // trampoline.
1096
1097 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001098 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1099 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
1100 const uint8_t* quick_code = GetOatAddress(quick_oat_code_offset);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001101 *quick_is_interpreted = false;
1102 if (quick_code != nullptr &&
1103 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
1104 // We have code for a non-static or initialized method, just use the code.
1105 } else if (quick_code == nullptr && method->IsNative() &&
1106 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1107 // Non-static or initialized native method missing compiled code, use generic JNI version.
1108 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
1109 } else if (quick_code == nullptr && !method->IsNative()) {
1110 // We don't have code at all for a non-native method, use the interpreter.
1111 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
1112 *quick_is_interpreted = true;
1113 } else {
1114 CHECK(!method->GetDeclaringClass()->IsInitialized());
1115 // We have code for a static method, but need to go through the resolution stub for class
1116 // initialization.
1117 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
1118 }
1119 return quick_code;
1120}
1121
Ian Rogers13735952014-10-08 12:43:28 -07001122const uint8_t* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001123 // Calculate the quick entry point following the same logic as FixupMethod() below.
1124 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001125 Runtime* runtime = Runtime::Current();
1126 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001127 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001128 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
1129 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001130 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
1131 } else {
1132 // We assume all methods have code. If they don't currently then we set them to the use the
1133 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1134 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1135 if (UNLIKELY(method->IsAbstract())) {
1136 return GetOatAddress(quick_to_interpreter_bridge_offset_);
1137 } else {
1138 bool quick_is_interpreted;
1139 return GetQuickCode(method, &quick_is_interpreted);
1140 }
1141 }
1142}
1143
Ian Rogersef7d42f2014-01-06 12:55:46 -08001144void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -07001145 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1146 // oat_begin_
Mathieu Chartier2d721012014-11-10 11:08:06 -08001147 // For 64 bit targets we need to repack the current runtime pointer sized fields to the right
1148 // locations.
1149 // Copy all of the fields from the runtime methods to the target methods first since we did a
1150 // bytewise copy earlier.
Jeff Haoc7d11882015-02-03 15:08:39 -08001151 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1152 orig->GetEntryPointFromInterpreterPtrSize(target_ptr_size_), target_ptr_size_);
1153 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(
1154 orig->GetEntryPointFromJniPtrSize(target_ptr_size_), target_ptr_size_);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001155 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
Jeff Haoc7d11882015-02-03 15:08:39 -08001156 orig->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001157
Ian Rogers848871b2013-08-05 10:56:33 -07001158 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001159 Runtime* runtime = Runtime::Current();
1160 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001161 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1162 GetOatAddress(quick_resolution_trampoline_offset_), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001163 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1164 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001165 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1166 GetOatAddress(quick_imt_conflict_trampoline_offset_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001167 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001168 // We assume all methods have code. If they don't currently then we set them to the use the
1169 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1170 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1171 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001172 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1173 GetOatAddress(quick_to_interpreter_bridge_offset_), target_ptr_size_);
1174 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1175 reinterpret_cast<EntryPointFromInterpreter*>(const_cast<uint8_t*>(
1176 GetOatAddress(interpreter_to_interpreter_bridge_offset_))), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001177 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001178 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -07001179 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001180 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001181
Sebastien Hertze1d07812014-05-21 15:44:09 +02001182 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001183 if (orig->IsNative()) {
1184 // The native method's pointer is set to a stub to lookup via dlsym.
1185 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier2d721012014-11-10 11:08:06 -08001186 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_),
1187 target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001188 }
Sebastien Hertze1d07812014-05-21 15:44:09 +02001189
1190 // Interpreter entrypoint:
1191 // Set the interpreter entrypoint depending on whether there is compiled code or not.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001192 uint32_t interpreter_code = (quick_is_interpreted)
Sebastien Hertze1d07812014-05-21 15:44:09 +02001193 ? interpreter_to_interpreter_bridge_offset_
1194 : interpreter_to_compiled_code_bridge_offset_;
Mathieu Chartier2d721012014-11-10 11:08:06 -08001195 EntryPointFromInterpreter* interpreter_entrypoint =
Sebastien Hertze1d07812014-05-21 15:44:09 +02001196 reinterpret_cast<EntryPointFromInterpreter*>(
Mathieu Chartier2d721012014-11-10 11:08:06 -08001197 const_cast<uint8_t*>(GetOatAddress(interpreter_code)));
1198 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1199 interpreter_entrypoint, target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001200 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001201 }
1202}
1203
Alex Lighta59dd802014-07-02 16:28:08 -07001204static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001205 uint64_t data_sec_offset;
1206 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1207 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001208 return nullptr;
1209 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001210 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001211}
1212
Vladimir Markof4da6752014-08-01 19:04:18 +01001213void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001214 std::string error_msg;
1215 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
1216 MAP_SHARED, &error_msg));
1217 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001218 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001219 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001220 }
Alex Lighta59dd802014-07-02 16:28:08 -07001221 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1222 CHECK(oat_header != nullptr);
1223 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001224
Brian Carlstrom7940e442013-07-12 13:46:57 -07001225 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001226 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001227}
1228
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001229size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1230 DCHECK_LE(up_to, kBinSize);
1231 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1232}
1233
1234ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1235 // These values may need to get updated if more bins are added to the enum Bin
Vladimir Marko20f85592015-03-19 10:07:02 +00001236 static_assert(kBinBits == 4, "wrong number of bin bits");
1237 static_assert(kBinShift == 28, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001238 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1239
1240 DCHECK_LT(GetBin(), kBinSize);
1241 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1242}
1243
1244ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1245 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1246 DCHECK_EQ(index, GetIndex());
1247}
1248
1249ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1250 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1251}
1252
1253uint32_t ImageWriter::BinSlot::GetIndex() const {
1254 return lockword_ & ~kBinMask;
1255}
1256
Andreas Gampe245ee002014-12-04 21:25:04 -08001257void ImageWriter::FreeStringDataArray() {
1258 if (string_data_array_ != nullptr) {
1259 gc::space::LargeObjectSpace* los = Runtime::Current()->GetHeap()->GetLargeObjectsSpace();
1260 if (los != nullptr) {
1261 los->Free(Thread::Current(), reinterpret_cast<mirror::Object*>(string_data_array_));
1262 }
1263 }
1264}
1265
Brian Carlstrom7940e442013-07-12 13:46:57 -07001266} // namespace art