blob: 8c7d611d85c7f4cfa7aa9573be0ffe9e828099cb [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>
Brian Carlstrom7940e442013-07-12 13:46:57 -070022#include <vector>
23
24#include "base/logging.h"
25#include "base/unix_file/fd_file.h"
26#include "class_linker.h"
27#include "compiled_method.h"
28#include "dex_file-inl.h"
29#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070030#include "elf_file.h"
31#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "elf_writer.h"
33#include "gc/accounting/card_table-inl.h"
34#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070035#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070036#include "gc/heap.h"
37#include "gc/space/large_object_space.h"
38#include "gc/space/space-inl.h"
39#include "globals.h"
40#include "image.h"
41#include "intern_table.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070042#include "lock_word.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070043#include "mirror/art_field-inl.h"
44#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070045#include "mirror/array-inl.h"
46#include "mirror/class-inl.h"
47#include "mirror/class_loader.h"
48#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "mirror/object-inl.h"
50#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070051#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070052#include "oat.h"
53#include "oat_file.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "runtime.h"
55#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070056#include "handle_scope-inl.h"
Igor Murashkinf5b4c502014-11-14 15:01:59 -080057
58#include <numeric>
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
Vladimir Markof4da6752014-08-01 19:04:18 +010074bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -080075 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +010076 {
77 Thread::Current()->TransitionFromSuspendedToRunnable();
78 PruneNonImageClasses(); // Remove junk
79 ComputeLazyFieldsForImageClasses(); // Add useful information
Vladimir Marko3389ca72014-12-03 14:35:54 +000080 ProcessStrings();
Vladimir Markof4da6752014-08-01 19:04:18 +010081 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
82 }
83 gc::Heap* heap = Runtime::Current()->GetHeap();
84 heap->CollectGarbage(false); // Remove garbage.
85
86 if (!AllocMemory()) {
87 return false;
88 }
89
90 if (kIsDebugBuild) {
91 ScopedObjectAccess soa(Thread::Current());
92 CheckNonImageClassesRemoved();
93 }
94
95 Thread::Current()->TransitionFromSuspendedToRunnable();
96 CalculateNewObjectOffsets();
97 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
98
99 return true;
100}
101
Brian Carlstrom7940e442013-07-12 13:46:57 -0700102bool ImageWriter::Write(const std::string& image_filename,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700103 const std::string& oat_filename,
104 const std::string& oat_location) {
105 CHECK(!image_filename.empty());
106
Brian Carlstrom7940e442013-07-12 13:46:57 -0700107 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700108
Ian Rogers700a4022014-05-19 16:49:03 -0700109 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700110 if (oat_file.get() == NULL) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800111 PLOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700112 return false;
113 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700114 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -0700115 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, &error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700116 if (oat_file_ == nullptr) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800117 PLOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700118 << ": " << error_msg;
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700119 return false;
120 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700121 CHECK_EQ(class_linker->RegisterOatFile(oat_file_), oat_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700122
Ian Rogers848871b2013-08-05 10:56:33 -0700123 interpreter_to_interpreter_bridge_offset_ =
124 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
125 interpreter_to_compiled_code_bridge_offset_ =
126 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
127
128 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
129
Andreas Gampe2da88232014-02-27 12:26:20 -0800130 quick_generic_jni_trampoline_offset_ =
131 oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
Jeff Hao88474b42013-10-23 16:24:40 -0700132 quick_imt_conflict_trampoline_offset_ =
133 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700134 quick_resolution_trampoline_offset_ =
135 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
136 quick_to_interpreter_bridge_offset_ =
137 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700138
Brian Carlstrom7940e442013-07-12 13:46:57 -0700139 size_t oat_loaded_size = 0;
140 size_t oat_data_offset = 0;
141 ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
Alex Light53cb16b2014-06-12 11:26:29 -0700142
Vladimir Markof4da6752014-08-01 19:04:18 +0100143 Thread::Current()->TransitionFromSuspendedToRunnable();
144 CreateHeader(oat_loaded_size, oat_data_offset);
145 CopyAndFixupObjects();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700146 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
147
Vladimir Markof4da6752014-08-01 19:04:18 +0100148 SetOatChecksumFromElfFile(oat_file.get());
149
Andreas Gampe4303ba92014-11-06 01:00:46 -0800150 if (oat_file->FlushCloseOrErase() != 0) {
151 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename << " for " << oat_location;
152 return false;
153 }
154
Ian Rogers700a4022014-05-19 16:49:03 -0700155 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700156 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700157 if (image_file.get() == NULL) {
158 LOG(ERROR) << "Failed to open image file " << image_filename;
159 return false;
160 }
161 if (fchmod(image_file->Fd(), 0644) != 0) {
162 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800163 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700164 return EXIT_FAILURE;
165 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700166
167 // Write out the image.
168 CHECK_EQ(image_end_, image_header->GetImageSize());
169 if (!image_file->WriteFully(image_->Begin(), image_end_)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700170 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800171 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700172 return false;
173 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700174
175 // Write out the image bitmap at the page aligned start of the image end.
176 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
177 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
178 image_header->GetImageBitmapSize(),
179 image_header->GetImageBitmapOffset())) {
180 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800181 image_file->Erase();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700182 return false;
183 }
184
Andreas Gampe4303ba92014-11-06 01:00:46 -0800185 if (image_file->FlushCloseOrErase() != 0) {
186 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
187 return false;
188 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700189 return true;
190}
191
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800192void ImageWriter::SetImageOffset(mirror::Object* object,
193 ImageWriter::BinSlot bin_slot,
194 size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700195 DCHECK(object != nullptr);
196 DCHECK_NE(offset, 0U);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700197 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
198 DCHECK_ALIGNED(obj, kObjectAlignment);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800199
200 image_bitmap_->Set(obj); // Mark the obj as mutated, since we will end up changing it.
201 {
202 // Remember the object-inside-of-the-image's hash code so we can restore it after the copy.
203 auto hash_it = saved_hashes_map_.find(bin_slot);
204 if (hash_it != saved_hashes_map_.end()) {
205 std::pair<BinSlot, uint32_t> slot_hash = *hash_it;
206 saved_hashes_.push_back(std::make_pair(obj, slot_hash.second));
207 saved_hashes_map_.erase(hash_it);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700208 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700209 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800210 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700211 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700212 DCHECK(IsImageOffsetAssigned(object));
213}
214
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800215void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700216 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800217 DCHECK_NE(image_objects_offset_begin_, 0u);
218
219 size_t previous_bin_sizes = GetBinSizeSum(bin_slot.GetBin()); // sum sizes in [0..bin#)
220 size_t new_offset = image_objects_offset_begin_ + previous_bin_sizes + bin_slot.GetIndex();
221 DCHECK_ALIGNED(new_offset, kObjectAlignment);
222
223 SetImageOffset(object, bin_slot, new_offset);
224 DCHECK_LT(new_offset, image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700225}
226
Ian Rogersef7d42f2014-01-06 12:55:46 -0800227bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800228 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700229 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700230 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700231}
232
Ian Rogersef7d42f2014-01-06 12:55:46 -0800233size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700234 DCHECK(object != nullptr);
235 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700236 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700237 size_t offset = lock_word.ForwardingAddress();
238 DCHECK_LT(offset, image_end_);
239 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700240}
241
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800242void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
243 DCHECK(object != nullptr);
244 DCHECK(!IsImageOffsetAssigned(object));
245 DCHECK(!IsImageBinSlotAssigned(object));
246
247 // Before we stomp over the lock word, save the hash code for later.
248 Monitor::Deflate(Thread::Current(), object);;
249 LockWord lw(object->GetLockWord(false));
250 switch (lw.GetState()) {
251 case LockWord::kFatLocked: {
252 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
253 break;
254 }
255 case LockWord::kThinLocked: {
256 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
257 break;
258 }
259 case LockWord::kUnlocked:
260 // No hash, don't need to save it.
261 break;
262 case LockWord::kHashCode:
263 saved_hashes_map_[bin_slot] = lw.GetHashCode();
264 break;
265 default:
266 LOG(FATAL) << "Unreachable.";
267 UNREACHABLE();
268 }
269 object->SetLockWord(LockWord::FromForwardingAddress(static_cast<uint32_t>(bin_slot)),
270 false);
271 DCHECK(IsImageBinSlotAssigned(object));
272}
273
274void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
275 DCHECK(object != nullptr);
276 size_t object_size;
277 if (object->IsArtMethod()) {
278 // Methods are sized based on the target pointer size.
279 object_size = mirror::ArtMethod::InstanceSize(target_ptr_size_);
280 } else {
281 object_size = object->SizeOf();
282 }
283
284 // The magic happens here. We segregate objects into different bins based
285 // on how likely they are to get dirty at runtime.
286 //
287 // Likely-to-dirty objects get packed together into the same bin so that
288 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
289 // maximized.
290 //
291 // This means more pages will stay either clean or shared dirty (with zygote) and
292 // the app will use less of its own (private) memory.
293 Bin bin = kBinRegular;
294
295 if (kBinObjects) {
296 //
297 // Changing the bin of an object is purely a memory-use tuning.
298 // It has no change on runtime correctness.
299 //
300 // Memory analysis has determined that the following types of objects get dirtied
301 // the most:
302 //
303 // * Class'es which are verified [their clinit runs only at runtime]
304 // - classes in general [because their static fields get overwritten]
305 // - initialized classes with all-final statics are unlikely to be ever dirty,
306 // so bin them separately
307 // * Art Methods that are:
308 // - native [their native entry point is not looked up until runtime]
309 // - have declaring classes that aren't initialized
310 // [their interpreter/quick entry points are trampolines until the class
311 // becomes initialized]
312 //
313 // We also assume the following objects get dirtied either never or extremely rarely:
314 // * Strings (they are immutable)
315 // * Art methods that aren't native and have initialized declared classes
316 //
317 // We assume that "regular" bin objects are highly unlikely to become dirtied,
318 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
319 //
320 if (object->IsClass()) {
321 bin = kBinClassVerified;
322 mirror::Class* klass = object->AsClass();
323
324 if (klass->GetStatus() == Class::kStatusInitialized) {
325 bin = kBinClassInitialized;
326
327 // If the class's static fields are all final, put it into a separate bin
328 // since it's very likely it will stay clean.
329 uint32_t num_static_fields = klass->NumStaticFields();
330 if (num_static_fields == 0) {
331 bin = kBinClassInitializedFinalStatics;
332 } else {
333 // Maybe all the statics are final?
334 bool all_final = true;
335 for (uint32_t i = 0; i < num_static_fields; ++i) {
336 ArtField* field = klass->GetStaticField(i);
337 if (!field->IsFinal()) {
338 all_final = false;
339 break;
340 }
341 }
342
343 if (all_final) {
344 bin = kBinClassInitializedFinalStatics;
345 }
346 }
347 }
348 } else if (object->IsArtMethod<kVerifyNone>()) {
349 mirror::ArtMethod* art_method = down_cast<ArtMethod*>(object);
350 if (art_method->IsNative()) {
351 bin = kBinArtMethodNative;
352 } else {
353 mirror::Class* declaring_class = art_method->GetDeclaringClass();
354 if (declaring_class->GetStatus() != Class::kStatusInitialized) {
355 bin = kBinArtMethodNotInitialized;
356 } else {
357 // This is highly unlikely to dirty since there's no entry points to mutate.
358 bin = kBinArtMethodsManagedInitialized;
359 }
360 }
361 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
362 bin = kBinString; // Strings are almost always immutable (except for object header).
363 } // else bin = kBinRegular
364 }
365
366 size_t current_offset = bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
367 // Move the current bin size up to accomodate the object we just assigned a bin slot.
368 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
369 bin_slot_sizes_[bin] += offset_delta;
370
371 BinSlot new_bin_slot(bin, current_offset);
372 SetImageBinSlot(object, new_bin_slot);
373
374 ++bin_slot_count_[bin];
375
376 DCHECK_LT(GetBinSizeSum(), image_->Size());
377
378 // Grow the image closer to the end by the object we just assigned.
379 image_end_ += offset_delta;
380 DCHECK_LT(image_end_, image_->Size());
381}
382
383bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
384 DCHECK(object != nullptr);
385
386 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
387 // If it's in some other state, then we haven't yet assigned an image bin slot.
388 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
389 return false;
390 } else if (kIsDebugBuild) {
391 LockWord lock_word = object->GetLockWord(false);
392 size_t offset = lock_word.ForwardingAddress();
393 BinSlot bin_slot(offset);
394 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()])
395 << "bin slot offset should not exceed the size of that bin";
396 }
397 return true;
398}
399
400ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
401 DCHECK(object != nullptr);
402 DCHECK(IsImageBinSlotAssigned(object));
403
404 LockWord lock_word = object->GetLockWord(false);
405 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
406 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
407
408 BinSlot bin_slot(static_cast<uint32_t>(offset));
409 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()]);
410
411 return bin_slot;
412}
413
Brian Carlstrom7940e442013-07-12 13:46:57 -0700414bool ImageWriter::AllocMemory() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700415 size_t length = RoundUp(Runtime::Current()->GetHeap()->GetTotalMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700416 std::string error_msg;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700417 image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, PROT_READ | PROT_WRITE,
Ian Rogers3cd86d62014-08-14 08:53:12 -0700418 false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700419 if (UNLIKELY(image_.get() == nullptr)) {
420 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700421 return false;
422 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700423
424 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700425 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
426 length));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700427 if (image_bitmap_.get() == nullptr) {
428 LOG(ERROR) << "Failed to allocate memory for image bitmap";
429 return false;
430 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700431 return true;
432}
433
434void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700435 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700436 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
437}
438
439bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700440 Thread* self = Thread::Current();
441 StackHandleScope<1> hs(self);
442 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700443 return true;
444}
445
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800446// Count the number of strings in the heap and put the result in arg as a size_t pointer.
447static void CountStringsCallback(Object* obj, void* arg)
448 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
449 if (obj->GetClass()->IsStringClass()) {
450 ++*reinterpret_cast<size_t*>(arg);
451 }
452}
453
454// Collect all the java.lang.String in the heap and put them in the output strings_ array.
455class StringCollector {
456 public:
457 StringCollector(Handle<mirror::ObjectArray<mirror::String>> strings, size_t index)
458 : strings_(strings), index_(index) {
459 }
460 static void Callback(Object* obj, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
461 auto* collector = reinterpret_cast<StringCollector*>(arg);
462 if (obj->GetClass()->IsStringClass()) {
463 collector->strings_->SetWithoutChecks<false>(collector->index_++, obj->AsString());
464 }
465 }
466 size_t GetIndex() const {
467 return index_;
468 }
469
470 private:
471 Handle<mirror::ObjectArray<mirror::String>> strings_;
472 size_t index_;
473};
474
475// Compare strings based on length, used for sorting strings by length / reverse length.
Vladimir Markofaeda182014-12-04 14:52:25 +0000476class LexicographicalStringComparator {
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800477 public:
Vladimir Markofaeda182014-12-04 14:52:25 +0000478 bool operator()(const mirror::HeapReference<mirror::String>& lhs,
479 const mirror::HeapReference<mirror::String>& rhs) const
480 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
481 mirror::String* lhs_s = lhs.AsMirrorPtr();
482 mirror::String* rhs_s = rhs.AsMirrorPtr();
483 uint16_t* lhs_begin = lhs_s->GetCharArray()->GetData() + lhs_s->GetOffset();
484 uint16_t* rhs_begin = rhs_s->GetCharArray()->GetData() + rhs_s->GetOffset();
485 return std::lexicographical_compare(lhs_begin, lhs_begin + lhs_s->GetLength(),
486 rhs_begin, rhs_begin + rhs_s->GetLength());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800487 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800488};
489
Vladimir Markofaeda182014-12-04 14:52:25 +0000490static bool IsPrefix(mirror::String* pref, mirror::String* full)
491 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
492 if (pref->GetLength() > full->GetLength()) {
493 return false;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800494 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000495 uint16_t* pref_begin = pref->GetCharArray()->GetData() + pref->GetOffset();
496 uint16_t* full_begin = full->GetCharArray()->GetData() + full->GetOffset();
497 return std::equal(pref_begin, pref_begin + pref->GetLength(), full_begin);
498}
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800499
500void ImageWriter::ProcessStrings() {
501 size_t total_strings = 0;
502 gc::Heap* heap = Runtime::Current()->GetHeap();
503 ClassLinker* cl = Runtime::Current()->GetClassLinker();
504 {
505 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
506 heap->VisitObjects(CountStringsCallback, &total_strings); // Count the strings.
507 }
508 Thread* self = Thread::Current();
509 StackHandleScope<1> hs(self);
510 auto strings = hs.NewHandle(cl->AllocStringArray(self, total_strings));
511 StringCollector string_collector(strings, 0U);
512 {
513 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
514 // Read strings into the array.
515 heap->VisitObjects(StringCollector::Callback, &string_collector);
516 }
517 // Some strings could have gotten freed if AllocStringArray caused a GC.
518 CHECK_LE(string_collector.GetIndex(), total_strings);
519 total_strings = string_collector.GetIndex();
Vladimir Markofaeda182014-12-04 14:52:25 +0000520 auto* strings_begin = reinterpret_cast<mirror::HeapReference<mirror::String>*>(
521 strings->GetRawData(sizeof(mirror::HeapReference<mirror::String>), 0));
522 std::sort(strings_begin, strings_begin + total_strings, LexicographicalStringComparator());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800523 // Characters of strings which are non equal prefix of another string (not the same string).
524 // We don't count the savings from equal strings since these would get interned later anyways.
525 size_t prefix_saved_chars = 0;
Vladimir Markofaeda182014-12-04 14:52:25 +0000526 // Count characters needed for the strings.
527 size_t num_chars = 0u;
528 mirror::String* prev_s = nullptr;
529 for (size_t idx = 0; idx != total_strings; ++idx) {
530 mirror::String* s = strings->GetWithoutChecks(idx);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800531 size_t length = s->GetLength();
Vladimir Markofaeda182014-12-04 14:52:25 +0000532 num_chars += length;
533 if (prev_s != nullptr && IsPrefix(prev_s, s)) {
534 size_t prev_length = prev_s->GetLength();
535 num_chars -= prev_length;
536 if (prev_length != length) {
537 prefix_saved_chars += prev_length;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800538 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800539 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000540 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800541 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000542 // Create character array, copy characters and point the strings there.
543 mirror::CharArray* array = mirror::CharArray::Alloc(self, num_chars);
Andreas Gampe245ee002014-12-04 21:25:04 -0800544 string_data_array_ = array;
Vladimir Markofaeda182014-12-04 14:52:25 +0000545 uint16_t* array_data = array->GetData();
546 size_t pos = 0u;
547 prev_s = nullptr;
548 for (size_t idx = 0; idx != total_strings; ++idx) {
549 mirror::String* s = strings->GetWithoutChecks(idx);
550 uint16_t* s_data = s->GetCharArray()->GetData() + s->GetOffset();
551 int32_t s_length = s->GetLength();
552 int32_t prefix_length = 0u;
553 if (idx != 0u && IsPrefix(prev_s, s)) {
554 prefix_length = prev_s->GetLength();
555 }
556 memcpy(array_data + pos, s_data + prefix_length, (s_length - prefix_length) * sizeof(*s_data));
557 s->SetOffset(pos - prefix_length);
558 s->SetArray(array);
559 pos += s_length - prefix_length;
560 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800561 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000562 CHECK_EQ(pos, num_chars);
563
Mathieu Chartier88f21ca2014-11-18 14:13:58 -0800564 LOG(INFO) << "Total # image strings=" << total_strings << " combined length="
Vladimir Markofaeda182014-12-04 14:52:25 +0000565 << num_chars << " prefix saved chars=" << prefix_saved_chars;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800566 ComputeEagerResolvedStrings();
567}
568
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700569void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700570 if (!obj->GetClass()->IsStringClass()) {
571 return;
572 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700573 mirror::String* string = obj->AsString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700574 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700575 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
576 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
577 size_t dex_cache_count = class_linker->GetDexCacheCount();
578 for (size_t i = 0; i < dex_cache_count; ++i) {
579 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700580 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800581 const DexFile::StringId* string_id;
582 if (UNLIKELY(string->GetLength() == 0)) {
583 string_id = dex_file.FindStringId("");
584 } else {
585 string_id = dex_file.FindStringId(utf16_string);
586 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700587 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700588 // This string occurs in this dex file, assign the dex cache entry.
589 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
590 if (dex_cache->GetResolvedString(string_idx) == NULL) {
591 dex_cache->SetResolvedString(string_idx, string);
592 }
593 }
594 }
595}
596
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800597void ImageWriter::ComputeEagerResolvedStrings() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700598 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
599 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700600}
601
Ian Rogersef7d42f2014-01-06 12:55:46 -0800602bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700603 std::string temp;
604 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700605}
606
607struct NonImageClasses {
608 ImageWriter* image_writer;
609 std::set<std::string>* non_image_classes;
610};
611
612void ImageWriter::PruneNonImageClasses() {
613 if (compiler_driver_.GetImageClasses() == NULL) {
614 return;
615 }
616 Runtime* runtime = Runtime::Current();
617 ClassLinker* class_linker = runtime->GetClassLinker();
618
619 // Make a list of classes we would like to prune.
620 std::set<std::string> non_image_classes;
621 NonImageClasses context;
622 context.image_writer = this;
623 context.non_image_classes = &non_image_classes;
624 class_linker->VisitClasses(NonImageClassesVisitor, &context);
625
626 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700627 for (const std::string& it : non_image_classes) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800628 bool result = class_linker->RemoveClass(it.c_str(), NULL);
629 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700630 }
631
632 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700633 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700634 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
635 size_t dex_cache_count = class_linker->GetDexCacheCount();
636 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
637 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700638 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
639 Class* klass = dex_cache->GetResolvedType(i);
640 if (klass != NULL && !IsImageClass(klass)) {
641 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700642 }
643 }
644 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700645 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700646 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
647 dex_cache->SetResolvedMethod(i, resolution_method);
648 }
649 }
650 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700651 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700652 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
653 dex_cache->SetResolvedField(i, NULL);
654 }
655 }
656 }
657}
658
659bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
660 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
661 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700662 std::string temp;
663 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700664 }
665 return true;
666}
667
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800668void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700669 if (compiler_driver_.GetImageClasses() != nullptr) {
670 gc::Heap* heap = Runtime::Current()->GetHeap();
671 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
672 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700673 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700674}
675
676void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
677 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700678 if (obj->IsClass()) {
679 Class* klass = obj->AsClass();
680 if (!image_writer->IsImageClass(klass)) {
681 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700682 std::string temp;
683 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700684 << " " << PrettyDescriptor(klass);
685 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700686 }
687}
688
689void ImageWriter::DumpImageClasses() {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700690 const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700691 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700692 for (const std::string& image_class : *image_classes) {
693 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700694 }
695}
696
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800697void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700698 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700699 // if it is a string, we want to intern it if its not interned.
700 if (obj->GetClass()->IsStringClass()) {
701 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800702 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700703 DCHECK_EQ(obj, obj->AsString()->Intern());
704 return;
705 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700706 mirror::String* const interned = obj->AsString()->Intern();
707 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800708 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700709 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800710 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700711 }
712 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800713 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700714 return;
715 }
716 // else (obj == interned), nothing to do but fall through to the normal case
717 }
718
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800719 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700720}
721
722ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
723 Runtime* runtime = Runtime::Current();
724 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700725 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700726 StackHandleScope<3> hs(self);
727 Handle<Class> object_array_class(hs.NewHandle(
728 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700729
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700730 // build an Object[] of all the DexCaches used in the source_space_.
731 // Since we can't hold the dex lock when allocating the dex_caches
732 // ObjectArray, we lock the dex lock twice, first to get the number
733 // of dex caches first and then lock it again to copy the dex
734 // caches. We check that the number of dex caches does not change.
735 size_t dex_cache_count;
736 {
737 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
738 dex_cache_count = class_linker->GetDexCacheCount();
739 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700740 Handle<ObjectArray<Object>> dex_caches(
741 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700742 dex_cache_count)));
743 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
744 {
745 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
746 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
747 << "The number of dex caches changed.";
748 for (size_t i = 0; i < dex_cache_count; ++i) {
749 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
750 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700751 }
752
753 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700754 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700755 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100756 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
757 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700758 image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
759 runtime->GetImtUnimplementedMethod());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100760 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
761 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
762 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
763 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
764 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
765 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
766 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700767 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100768 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700769 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
770 CHECK(image_roots->Get(i) != NULL);
771 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700772 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700773}
774
Mathieu Chartier590fee92013-09-13 13:46:47 -0700775// Walk instance fields of the given Class. Separate function to allow recursion on the super
776// class.
777void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
778 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700779 StackHandleScope<1> hs(Thread::Current());
780 Handle<mirror::Class> h_class(hs.NewHandle(klass));
781 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700782 if (super != nullptr) {
783 WalkInstanceFields(obj, super);
784 }
785 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700786 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000787 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700788 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700789 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700790 if (value != nullptr) {
791 WalkFieldsInOrder(value);
792 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000793 field_offset = MemberOffset(field_offset.Uint32Value() +
794 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700795 }
796}
797
798// For an unvisited object, visit it then all its children found via fields.
799void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800800 // Use our own visitor routine (instead of GC visitor) to get better locality between
801 // an object and its fields
802 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700803 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700804 StackHandleScope<2> hs(Thread::Current());
805 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
806 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700807 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800808 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700809 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700810 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700811 if (h_obj->IsClass()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700812 size_t num_static_fields = klass->NumReferenceStaticFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000813 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700814 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700815 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700816 if (value != nullptr) {
817 WalkFieldsInOrder(value);
818 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000819 field_offset = MemberOffset(field_offset.Uint32Value() +
820 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700821 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700822 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700823 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700824 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700825 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700826 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700827 mirror::Object* value = obj_array->Get(i);
828 if (value != nullptr) {
829 WalkFieldsInOrder(value);
830 }
831 }
832 }
833 }
834}
835
836void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
837 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
838 DCHECK(writer != nullptr);
839 writer->WalkFieldsInOrder(obj);
840}
841
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800842void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
843 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
844 DCHECK(writer != nullptr);
845 writer->UnbinObjectsIntoOffset(obj);
846}
847
848void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
849 CHECK(obj != nullptr);
850
851 // We know the bin slot, and the total bin sizes for all objects by now,
852 // so calculate the object's final image offset.
853
854 DCHECK(IsImageBinSlotAssigned(obj));
855 BinSlot bin_slot = GetImageBinSlot(obj);
856 // Change the lockword from a bin slot into an offset
857 AssignImageOffset(obj, bin_slot);
858}
859
Vladimir Markof4da6752014-08-01 19:04:18 +0100860void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700861 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700862 StackHandleScope<1> hs(self);
863 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700864
865 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700866 DCHECK_EQ(0U, image_end_);
867
Mathieu Chartier31e89252013-08-28 11:29:12 -0700868 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700869 // know where image_roots is going to end up
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800870 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700871
872 {
873 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700874 // TODO: Image spaces only?
Mathieu Chartier590fee92013-09-13 13:46:47 -0700875 DCHECK_LT(image_end_, image_->Size());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800876 image_objects_offset_begin_ = image_end_;
877 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700878 heap->VisitObjects(WalkFieldsCallback, this);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800879 // Transform each object's bin slot into an offset which will be used to do the final copy.
880 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
881 DCHECK(saved_hashes_map_.empty()); // All binslot hashes should've been put into vector by now.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700882 }
883
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800884 DCHECK_GT(image_end_, GetBinSizeSum());
885
Vladimir Markof4da6752014-08-01 19:04:18 +0100886 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
887
888 // Note that image_end_ is left at end of used space
889}
890
891void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
892 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -0700893 const uint8_t* oat_file_begin = GetOatFileBegin();
894 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800895
Brian Carlstrom7940e442013-07-12 13:46:57 -0700896 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -0700897 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700898
Mathieu Chartier31e89252013-08-28 11:29:12 -0700899 // Return to write header at start of image with future location of image_roots. At this point,
900 // image_end_ is the size of the image (excluding bitmaps).
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700901 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800902 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
903 heap_bytes_per_bitmap_byte;
Vladimir Markof4da6752014-08-01 19:04:18 +0100904 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
905 static_cast<uint32_t>(image_end_),
906 RoundUp(image_end_, kPageSize),
907 RoundUp(bitmap_bytes, kPageSize),
908 image_roots_address_,
909 oat_file_->GetOatHeader().GetChecksum(),
910 PointerToLowMemUInt32(oat_file_begin),
911 PointerToLowMemUInt32(oat_data_begin_),
912 PointerToLowMemUInt32(oat_data_end),
Igor Murashkin46774762014-10-22 11:37:02 -0700913 PointerToLowMemUInt32(oat_file_end),
914 compile_pic_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700915}
916
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800917void ImageWriter::CopyAndFixupObjects() {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -0700918 ScopedAssertNoThreadSuspension ants(Thread::Current(), "ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700919 gc::Heap* heap = Runtime::Current()->GetHeap();
920 // TODO: heap validation can't handle this fix up pass
921 heap->DisableObjectValidation();
922 // TODO: Image spaces only?
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -0700923 WriterMutexLock mu(ants.Self(), *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700924 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
925 // Fix up the object previously had hash codes.
926 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700927 hash_pair.first->SetLockWord(LockWord::FromHashCode(hash_pair.second), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700928 }
929 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700930}
931
Mathieu Chartier590fee92013-09-13 13:46:47 -0700932void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700933 DCHECK(obj != nullptr);
934 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700935 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700936 // see GetLocalAddress for similar computation
937 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers13735952014-10-08 12:43:28 -0700938 uint8_t* dst = image_writer->image_->Begin() + offset;
939 const uint8_t* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800940 size_t n;
941 if (obj->IsArtMethod()) {
942 // Size without pointer fields since we don't want to overrun the buffer if target art method
943 // is 32 bits but source is 64 bits.
Mathieu Chartiereace4582014-11-24 18:29:54 -0800944 n = mirror::ArtMethod::SizeWithoutPointerFields(sizeof(void*));
Mathieu Chartier2d721012014-11-10 11:08:06 -0800945 } else {
946 n = obj->SizeOf();
947 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700948 DCHECK_LT(offset + n, image_writer->image_->Size());
949 memcpy(dst, src, n);
950 Object* copy = reinterpret_cast<Object*>(dst);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700951 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
952 // word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700953 copy->SetLockWord(LockWord(), false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700954 image_writer->FixupObject(obj, copy);
955}
956
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800957// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700958class FixupVisitor {
959 public:
960 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
961 }
962
963 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
964 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -0700965 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700966 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
967 // image.
968 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700969 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700970 }
971
972 // java.lang.ref.Reference visitor.
973 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
974 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
975 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
976 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700977 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700978 }
979
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700980 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700981 ImageWriter* const image_writer_;
982 mirror::Object* const copy_;
983};
984
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700985class FixupClassVisitor FINAL : public FixupVisitor {
986 public:
987 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
988 }
989
990 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
991 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
992 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800993 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700994
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800995 // TODO: Remove dead code
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700996 if (offset.Uint32Value() < mirror::Class::EmbeddedVTableOffset().Uint32Value()) {
997 return;
998 }
999 }
1000
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001001 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1002 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001003 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1004 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1005 LOG(FATAL) << "Reference not expected here.";
1006 }
1007};
1008
Ian Rogersef7d42f2014-01-06 12:55:46 -08001009void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001010 DCHECK(orig != nullptr);
1011 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001012 if (kUseBakerOrBrooksReadBarrier) {
1013 orig->AssertReadBarrierPointer();
1014 if (kUseBrooksReadBarrier) {
1015 // Note the address 'copy' isn't the same as the image address of 'orig'.
1016 copy->SetReadBarrierPointer(GetImageAddress(orig));
1017 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1018 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001019 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001020 if (orig->IsClass() && orig->AsClass()->ShouldHaveEmbeddedImtAndVTable()) {
1021 FixupClassVisitor visitor(this, copy);
1022 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
1023 } else {
1024 FixupVisitor visitor(this, copy);
1025 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
1026 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001027 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001028 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001029 } else if (orig->IsClass() && orig->AsClass()->IsArtMethodClass()) {
1030 // Set the right size for the target.
1031 size_t size = mirror::ArtMethod::InstanceSize(target_ptr_size_);
1032 down_cast<mirror::Class*>(copy)->SetObjectSizeWithoutChecks(size);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001033 }
1034}
1035
Ian Rogers13735952014-10-08 12:43:28 -07001036const uint8_t* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001037 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001038 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001039
1040 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1041 // trampoline.
1042
1043 // Quick entrypoint:
Ian Rogers13735952014-10-08 12:43:28 -07001044 const uint8_t* quick_code = GetOatAddress(method->GetQuickOatCodeOffset());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001045 *quick_is_interpreted = false;
1046 if (quick_code != nullptr &&
1047 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
1048 // We have code for a non-static or initialized method, just use the code.
1049 } else if (quick_code == nullptr && method->IsNative() &&
1050 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1051 // Non-static or initialized native method missing compiled code, use generic JNI version.
1052 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
1053 } else if (quick_code == nullptr && !method->IsNative()) {
1054 // We don't have code at all for a non-native method, use the interpreter.
1055 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
1056 *quick_is_interpreted = true;
1057 } else {
1058 CHECK(!method->GetDeclaringClass()->IsInitialized());
1059 // We have code for a static method, but need to go through the resolution stub for class
1060 // initialization.
1061 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
1062 }
1063 return quick_code;
1064}
1065
Ian Rogers13735952014-10-08 12:43:28 -07001066const uint8_t* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001067 // Calculate the quick entry point following the same logic as FixupMethod() below.
1068 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001069 Runtime* runtime = Runtime::Current();
1070 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001071 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001072 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
1073 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001074 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
1075 } else {
1076 // We assume all methods have code. If they don't currently then we set them to the use the
1077 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1078 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1079 if (UNLIKELY(method->IsAbstract())) {
1080 return GetOatAddress(quick_to_interpreter_bridge_offset_);
1081 } else {
1082 bool quick_is_interpreted;
1083 return GetQuickCode(method, &quick_is_interpreted);
1084 }
1085 }
1086}
1087
Ian Rogersef7d42f2014-01-06 12:55:46 -08001088void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -07001089 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1090 // oat_begin_
Mathieu Chartier2d721012014-11-10 11:08:06 -08001091 // For 64 bit targets we need to repack the current runtime pointer sized fields to the right
1092 // locations.
1093 // Copy all of the fields from the runtime methods to the target methods first since we did a
1094 // bytewise copy earlier.
Mathieu Chartier2d721012014-11-10 11:08:06 -08001095 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(orig->GetEntryPointFromInterpreter(),
1096 target_ptr_size_);
1097 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(orig->GetEntryPointFromJni(), target_ptr_size_);
1098 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1099 orig->GetEntryPointFromQuickCompiledCode(), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001100
Ian Rogers848871b2013-08-05 10:56:33 -07001101 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001102 Runtime* runtime = Runtime::Current();
1103 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001104 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1105 GetOatAddress(quick_resolution_trampoline_offset_), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001106 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1107 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001108 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1109 GetOatAddress(quick_imt_conflict_trampoline_offset_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001110 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001111 // We assume all methods have code. If they don't currently then we set them to the use the
1112 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1113 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1114 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001115 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1116 GetOatAddress(quick_to_interpreter_bridge_offset_), target_ptr_size_);
1117 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1118 reinterpret_cast<EntryPointFromInterpreter*>(const_cast<uint8_t*>(
1119 GetOatAddress(interpreter_to_interpreter_bridge_offset_))), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001120 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001121 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -07001122 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001123 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001124
Sebastien Hertze1d07812014-05-21 15:44:09 +02001125 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001126 if (orig->IsNative()) {
1127 // The native method's pointer is set to a stub to lookup via dlsym.
1128 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier2d721012014-11-10 11:08:06 -08001129 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_),
1130 target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001131 }
Sebastien Hertze1d07812014-05-21 15:44:09 +02001132
1133 // Interpreter entrypoint:
1134 // Set the interpreter entrypoint depending on whether there is compiled code or not.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001135 uint32_t interpreter_code = (quick_is_interpreted)
Sebastien Hertze1d07812014-05-21 15:44:09 +02001136 ? interpreter_to_interpreter_bridge_offset_
1137 : interpreter_to_compiled_code_bridge_offset_;
Mathieu Chartier2d721012014-11-10 11:08:06 -08001138 EntryPointFromInterpreter* interpreter_entrypoint =
Sebastien Hertze1d07812014-05-21 15:44:09 +02001139 reinterpret_cast<EntryPointFromInterpreter*>(
Mathieu Chartier2d721012014-11-10 11:08:06 -08001140 const_cast<uint8_t*>(GetOatAddress(interpreter_code)));
1141 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1142 interpreter_entrypoint, target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001143 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001144 }
1145}
1146
Alex Lighta59dd802014-07-02 16:28:08 -07001147static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001148 uint64_t data_sec_offset;
1149 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1150 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001151 return nullptr;
1152 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001153 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001154}
1155
Vladimir Markof4da6752014-08-01 19:04:18 +01001156void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001157 std::string error_msg;
1158 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
1159 MAP_SHARED, &error_msg));
1160 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001161 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001162 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001163 }
Alex Lighta59dd802014-07-02 16:28:08 -07001164 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1165 CHECK(oat_header != nullptr);
1166 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001167
Brian Carlstrom7940e442013-07-12 13:46:57 -07001168 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001169 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001170}
1171
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001172size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1173 DCHECK_LE(up_to, kBinSize);
1174 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1175}
1176
1177ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1178 // These values may need to get updated if more bins are added to the enum Bin
1179 static_assert(kBinBits == 3, "wrong number of bin bits");
1180 static_assert(kBinShift == 29, "wrong number of shift");
1181 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1182
1183 DCHECK_LT(GetBin(), kBinSize);
1184 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1185}
1186
1187ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1188 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1189 DCHECK_EQ(index, GetIndex());
1190}
1191
1192ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1193 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1194}
1195
1196uint32_t ImageWriter::BinSlot::GetIndex() const {
1197 return lockword_ & ~kBinMask;
1198}
1199
Andreas Gampe245ee002014-12-04 21:25:04 -08001200void ImageWriter::FreeStringDataArray() {
1201 if (string_data_array_ != nullptr) {
1202 gc::space::LargeObjectSpace* los = Runtime::Current()->GetHeap()->GetLargeObjectsSpace();
1203 if (los != nullptr) {
1204 los->Free(Thread::Current(), reinterpret_cast<mirror::Object*>(string_data_array_));
1205 }
1206 }
1207}
1208
Brian Carlstrom7940e442013-07-12 13:46:57 -07001209} // namespace art