blob: a45c2d1bab7b75d00bc4cd5712a519ecbbe1ac89 [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
Jeff Hao88474b42013-10-23 16:24:40 -0700130 portable_imt_conflict_trampoline_offset_ =
131 oat_file_->GetOatHeader().GetPortableImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700132 portable_resolution_trampoline_offset_ =
133 oat_file_->GetOatHeader().GetPortableResolutionTrampolineOffset();
134 portable_to_interpreter_bridge_offset_ =
135 oat_file_->GetOatHeader().GetPortableToInterpreterBridgeOffset();
136
Andreas Gampe2da88232014-02-27 12:26:20 -0800137 quick_generic_jni_trampoline_offset_ =
138 oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
Jeff Hao88474b42013-10-23 16:24:40 -0700139 quick_imt_conflict_trampoline_offset_ =
140 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700141 quick_resolution_trampoline_offset_ =
142 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
143 quick_to_interpreter_bridge_offset_ =
144 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700145
Brian Carlstrom7940e442013-07-12 13:46:57 -0700146 size_t oat_loaded_size = 0;
147 size_t oat_data_offset = 0;
148 ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
Alex Light53cb16b2014-06-12 11:26:29 -0700149
Vladimir Markof4da6752014-08-01 19:04:18 +0100150 Thread::Current()->TransitionFromSuspendedToRunnable();
151 CreateHeader(oat_loaded_size, oat_data_offset);
152 CopyAndFixupObjects();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700153 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
154
Vladimir Markof4da6752014-08-01 19:04:18 +0100155 SetOatChecksumFromElfFile(oat_file.get());
156
Andreas Gampe4303ba92014-11-06 01:00:46 -0800157 if (oat_file->FlushCloseOrErase() != 0) {
158 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename << " for " << oat_location;
159 return false;
160 }
161
Ian Rogers700a4022014-05-19 16:49:03 -0700162 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700163 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700164 if (image_file.get() == NULL) {
165 LOG(ERROR) << "Failed to open image file " << image_filename;
166 return false;
167 }
168 if (fchmod(image_file->Fd(), 0644) != 0) {
169 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800170 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700171 return EXIT_FAILURE;
172 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700173
174 // Write out the image.
175 CHECK_EQ(image_end_, image_header->GetImageSize());
176 if (!image_file->WriteFully(image_->Begin(), image_end_)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700177 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800178 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 return false;
180 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700181
182 // Write out the image bitmap at the page aligned start of the image end.
183 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
184 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
185 image_header->GetImageBitmapSize(),
186 image_header->GetImageBitmapOffset())) {
187 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800188 image_file->Erase();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700189 return false;
190 }
191
Andreas Gampe4303ba92014-11-06 01:00:46 -0800192 if (image_file->FlushCloseOrErase() != 0) {
193 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
194 return false;
195 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700196 return true;
197}
198
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800199void ImageWriter::SetImageOffset(mirror::Object* object,
200 ImageWriter::BinSlot bin_slot,
201 size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700202 DCHECK(object != nullptr);
203 DCHECK_NE(offset, 0U);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700204 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
205 DCHECK_ALIGNED(obj, kObjectAlignment);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800206
207 image_bitmap_->Set(obj); // Mark the obj as mutated, since we will end up changing it.
208 {
209 // Remember the object-inside-of-the-image's hash code so we can restore it after the copy.
210 auto hash_it = saved_hashes_map_.find(bin_slot);
211 if (hash_it != saved_hashes_map_.end()) {
212 std::pair<BinSlot, uint32_t> slot_hash = *hash_it;
213 saved_hashes_.push_back(std::make_pair(obj, slot_hash.second));
214 saved_hashes_map_.erase(hash_it);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700215 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700216 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800217 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700218 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700219 DCHECK(IsImageOffsetAssigned(object));
220}
221
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800222void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700223 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800224 DCHECK_NE(image_objects_offset_begin_, 0u);
225
226 size_t previous_bin_sizes = GetBinSizeSum(bin_slot.GetBin()); // sum sizes in [0..bin#)
227 size_t new_offset = image_objects_offset_begin_ + previous_bin_sizes + bin_slot.GetIndex();
228 DCHECK_ALIGNED(new_offset, kObjectAlignment);
229
230 SetImageOffset(object, bin_slot, new_offset);
231 DCHECK_LT(new_offset, image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700232}
233
Ian Rogersef7d42f2014-01-06 12:55:46 -0800234bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800235 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700236 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700237 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700238}
239
Ian Rogersef7d42f2014-01-06 12:55:46 -0800240size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700241 DCHECK(object != nullptr);
242 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700243 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700244 size_t offset = lock_word.ForwardingAddress();
245 DCHECK_LT(offset, image_end_);
246 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700247}
248
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800249void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
250 DCHECK(object != nullptr);
251 DCHECK(!IsImageOffsetAssigned(object));
252 DCHECK(!IsImageBinSlotAssigned(object));
253
254 // Before we stomp over the lock word, save the hash code for later.
255 Monitor::Deflate(Thread::Current(), object);;
256 LockWord lw(object->GetLockWord(false));
257 switch (lw.GetState()) {
258 case LockWord::kFatLocked: {
259 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
260 break;
261 }
262 case LockWord::kThinLocked: {
263 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
264 break;
265 }
266 case LockWord::kUnlocked:
267 // No hash, don't need to save it.
268 break;
269 case LockWord::kHashCode:
270 saved_hashes_map_[bin_slot] = lw.GetHashCode();
271 break;
272 default:
273 LOG(FATAL) << "Unreachable.";
274 UNREACHABLE();
275 }
276 object->SetLockWord(LockWord::FromForwardingAddress(static_cast<uint32_t>(bin_slot)),
277 false);
278 DCHECK(IsImageBinSlotAssigned(object));
279}
280
281void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
282 DCHECK(object != nullptr);
283 size_t object_size;
284 if (object->IsArtMethod()) {
285 // Methods are sized based on the target pointer size.
286 object_size = mirror::ArtMethod::InstanceSize(target_ptr_size_);
287 } else {
288 object_size = object->SizeOf();
289 }
290
291 // The magic happens here. We segregate objects into different bins based
292 // on how likely they are to get dirty at runtime.
293 //
294 // Likely-to-dirty objects get packed together into the same bin so that
295 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
296 // maximized.
297 //
298 // This means more pages will stay either clean or shared dirty (with zygote) and
299 // the app will use less of its own (private) memory.
300 Bin bin = kBinRegular;
301
302 if (kBinObjects) {
303 //
304 // Changing the bin of an object is purely a memory-use tuning.
305 // It has no change on runtime correctness.
306 //
307 // Memory analysis has determined that the following types of objects get dirtied
308 // the most:
309 //
310 // * Class'es which are verified [their clinit runs only at runtime]
311 // - classes in general [because their static fields get overwritten]
312 // - initialized classes with all-final statics are unlikely to be ever dirty,
313 // so bin them separately
314 // * Art Methods that are:
315 // - native [their native entry point is not looked up until runtime]
316 // - have declaring classes that aren't initialized
317 // [their interpreter/quick entry points are trampolines until the class
318 // becomes initialized]
319 //
320 // We also assume the following objects get dirtied either never or extremely rarely:
321 // * Strings (they are immutable)
322 // * Art methods that aren't native and have initialized declared classes
323 //
324 // We assume that "regular" bin objects are highly unlikely to become dirtied,
325 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
326 //
327 if (object->IsClass()) {
328 bin = kBinClassVerified;
329 mirror::Class* klass = object->AsClass();
330
331 if (klass->GetStatus() == Class::kStatusInitialized) {
332 bin = kBinClassInitialized;
333
334 // If the class's static fields are all final, put it into a separate bin
335 // since it's very likely it will stay clean.
336 uint32_t num_static_fields = klass->NumStaticFields();
337 if (num_static_fields == 0) {
338 bin = kBinClassInitializedFinalStatics;
339 } else {
340 // Maybe all the statics are final?
341 bool all_final = true;
342 for (uint32_t i = 0; i < num_static_fields; ++i) {
343 ArtField* field = klass->GetStaticField(i);
344 if (!field->IsFinal()) {
345 all_final = false;
346 break;
347 }
348 }
349
350 if (all_final) {
351 bin = kBinClassInitializedFinalStatics;
352 }
353 }
354 }
355 } else if (object->IsArtMethod<kVerifyNone>()) {
356 mirror::ArtMethod* art_method = down_cast<ArtMethod*>(object);
357 if (art_method->IsNative()) {
358 bin = kBinArtMethodNative;
359 } else {
360 mirror::Class* declaring_class = art_method->GetDeclaringClass();
361 if (declaring_class->GetStatus() != Class::kStatusInitialized) {
362 bin = kBinArtMethodNotInitialized;
363 } else {
364 // This is highly unlikely to dirty since there's no entry points to mutate.
365 bin = kBinArtMethodsManagedInitialized;
366 }
367 }
368 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
369 bin = kBinString; // Strings are almost always immutable (except for object header).
370 } // else bin = kBinRegular
371 }
372
373 size_t current_offset = bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
374 // Move the current bin size up to accomodate the object we just assigned a bin slot.
375 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
376 bin_slot_sizes_[bin] += offset_delta;
377
378 BinSlot new_bin_slot(bin, current_offset);
379 SetImageBinSlot(object, new_bin_slot);
380
381 ++bin_slot_count_[bin];
382
383 DCHECK_LT(GetBinSizeSum(), image_->Size());
384
385 // Grow the image closer to the end by the object we just assigned.
386 image_end_ += offset_delta;
387 DCHECK_LT(image_end_, image_->Size());
388}
389
390bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
391 DCHECK(object != nullptr);
392
393 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
394 // If it's in some other state, then we haven't yet assigned an image bin slot.
395 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
396 return false;
397 } else if (kIsDebugBuild) {
398 LockWord lock_word = object->GetLockWord(false);
399 size_t offset = lock_word.ForwardingAddress();
400 BinSlot bin_slot(offset);
401 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()])
402 << "bin slot offset should not exceed the size of that bin";
403 }
404 return true;
405}
406
407ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
408 DCHECK(object != nullptr);
409 DCHECK(IsImageBinSlotAssigned(object));
410
411 LockWord lock_word = object->GetLockWord(false);
412 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
413 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
414
415 BinSlot bin_slot(static_cast<uint32_t>(offset));
416 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()]);
417
418 return bin_slot;
419}
420
Brian Carlstrom7940e442013-07-12 13:46:57 -0700421bool ImageWriter::AllocMemory() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700422 size_t length = RoundUp(Runtime::Current()->GetHeap()->GetTotalMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700423 std::string error_msg;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700424 image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, PROT_READ | PROT_WRITE,
Ian Rogers3cd86d62014-08-14 08:53:12 -0700425 false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700426 if (UNLIKELY(image_.get() == nullptr)) {
427 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700428 return false;
429 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700430
431 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700432 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
433 length));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700434 if (image_bitmap_.get() == nullptr) {
435 LOG(ERROR) << "Failed to allocate memory for image bitmap";
436 return false;
437 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700438 return true;
439}
440
441void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700442 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700443 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
444}
445
446bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700447 Thread* self = Thread::Current();
448 StackHandleScope<1> hs(self);
449 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700450 return true;
451}
452
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800453// Count the number of strings in the heap and put the result in arg as a size_t pointer.
454static void CountStringsCallback(Object* obj, void* arg)
455 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
456 if (obj->GetClass()->IsStringClass()) {
457 ++*reinterpret_cast<size_t*>(arg);
458 }
459}
460
461// Collect all the java.lang.String in the heap and put them in the output strings_ array.
462class StringCollector {
463 public:
464 StringCollector(Handle<mirror::ObjectArray<mirror::String>> strings, size_t index)
465 : strings_(strings), index_(index) {
466 }
467 static void Callback(Object* obj, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
468 auto* collector = reinterpret_cast<StringCollector*>(arg);
469 if (obj->GetClass()->IsStringClass()) {
470 collector->strings_->SetWithoutChecks<false>(collector->index_++, obj->AsString());
471 }
472 }
473 size_t GetIndex() const {
474 return index_;
475 }
476
477 private:
478 Handle<mirror::ObjectArray<mirror::String>> strings_;
479 size_t index_;
480};
481
482// Compare strings based on length, used for sorting strings by length / reverse length.
Vladimir Markofaeda182014-12-04 14:52:25 +0000483class LexicographicalStringComparator {
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800484 public:
Vladimir Markofaeda182014-12-04 14:52:25 +0000485 bool operator()(const mirror::HeapReference<mirror::String>& lhs,
486 const mirror::HeapReference<mirror::String>& rhs) const
487 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
488 mirror::String* lhs_s = lhs.AsMirrorPtr();
489 mirror::String* rhs_s = rhs.AsMirrorPtr();
490 uint16_t* lhs_begin = lhs_s->GetCharArray()->GetData() + lhs_s->GetOffset();
491 uint16_t* rhs_begin = rhs_s->GetCharArray()->GetData() + rhs_s->GetOffset();
492 return std::lexicographical_compare(lhs_begin, lhs_begin + lhs_s->GetLength(),
493 rhs_begin, rhs_begin + rhs_s->GetLength());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800494 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800495};
496
Vladimir Markofaeda182014-12-04 14:52:25 +0000497static bool IsPrefix(mirror::String* pref, mirror::String* full)
498 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
499 if (pref->GetLength() > full->GetLength()) {
500 return false;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800501 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000502 uint16_t* pref_begin = pref->GetCharArray()->GetData() + pref->GetOffset();
503 uint16_t* full_begin = full->GetCharArray()->GetData() + full->GetOffset();
504 return std::equal(pref_begin, pref_begin + pref->GetLength(), full_begin);
505}
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800506
507void ImageWriter::ProcessStrings() {
508 size_t total_strings = 0;
509 gc::Heap* heap = Runtime::Current()->GetHeap();
510 ClassLinker* cl = Runtime::Current()->GetClassLinker();
511 {
512 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
513 heap->VisitObjects(CountStringsCallback, &total_strings); // Count the strings.
514 }
515 Thread* self = Thread::Current();
516 StackHandleScope<1> hs(self);
517 auto strings = hs.NewHandle(cl->AllocStringArray(self, total_strings));
518 StringCollector string_collector(strings, 0U);
519 {
520 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
521 // Read strings into the array.
522 heap->VisitObjects(StringCollector::Callback, &string_collector);
523 }
524 // Some strings could have gotten freed if AllocStringArray caused a GC.
525 CHECK_LE(string_collector.GetIndex(), total_strings);
526 total_strings = string_collector.GetIndex();
Vladimir Markofaeda182014-12-04 14:52:25 +0000527 auto* strings_begin = reinterpret_cast<mirror::HeapReference<mirror::String>*>(
528 strings->GetRawData(sizeof(mirror::HeapReference<mirror::String>), 0));
529 std::sort(strings_begin, strings_begin + total_strings, LexicographicalStringComparator());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800530 // Characters of strings which are non equal prefix of another string (not the same string).
531 // We don't count the savings from equal strings since these would get interned later anyways.
532 size_t prefix_saved_chars = 0;
Vladimir Markofaeda182014-12-04 14:52:25 +0000533 // Count characters needed for the strings.
534 size_t num_chars = 0u;
535 mirror::String* prev_s = nullptr;
536 for (size_t idx = 0; idx != total_strings; ++idx) {
537 mirror::String* s = strings->GetWithoutChecks(idx);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800538 size_t length = s->GetLength();
Vladimir Markofaeda182014-12-04 14:52:25 +0000539 num_chars += length;
540 if (prev_s != nullptr && IsPrefix(prev_s, s)) {
541 size_t prev_length = prev_s->GetLength();
542 num_chars -= prev_length;
543 if (prev_length != length) {
544 prefix_saved_chars += prev_length;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800545 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800546 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000547 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800548 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000549 // Create character array, copy characters and point the strings there.
550 mirror::CharArray* array = mirror::CharArray::Alloc(self, num_chars);
551 uint16_t* array_data = array->GetData();
552 size_t pos = 0u;
553 prev_s = nullptr;
554 for (size_t idx = 0; idx != total_strings; ++idx) {
555 mirror::String* s = strings->GetWithoutChecks(idx);
556 uint16_t* s_data = s->GetCharArray()->GetData() + s->GetOffset();
557 int32_t s_length = s->GetLength();
558 int32_t prefix_length = 0u;
559 if (idx != 0u && IsPrefix(prev_s, s)) {
560 prefix_length = prev_s->GetLength();
561 }
562 memcpy(array_data + pos, s_data + prefix_length, (s_length - prefix_length) * sizeof(*s_data));
563 s->SetOffset(pos - prefix_length);
564 s->SetArray(array);
565 pos += s_length - prefix_length;
566 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800567 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000568 CHECK_EQ(pos, num_chars);
569
Mathieu Chartier88f21ca2014-11-18 14:13:58 -0800570 LOG(INFO) << "Total # image strings=" << total_strings << " combined length="
Vladimir Markofaeda182014-12-04 14:52:25 +0000571 << num_chars << " prefix saved chars=" << prefix_saved_chars;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800572 ComputeEagerResolvedStrings();
573}
574
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700575void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700576 if (!obj->GetClass()->IsStringClass()) {
577 return;
578 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700579 mirror::String* string = obj->AsString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700580 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700581 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
582 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
583 size_t dex_cache_count = class_linker->GetDexCacheCount();
584 for (size_t i = 0; i < dex_cache_count; ++i) {
585 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700586 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800587 const DexFile::StringId* string_id;
588 if (UNLIKELY(string->GetLength() == 0)) {
589 string_id = dex_file.FindStringId("");
590 } else {
591 string_id = dex_file.FindStringId(utf16_string);
592 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700593 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700594 // This string occurs in this dex file, assign the dex cache entry.
595 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
596 if (dex_cache->GetResolvedString(string_idx) == NULL) {
597 dex_cache->SetResolvedString(string_idx, string);
598 }
599 }
600 }
601}
602
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800603void ImageWriter::ComputeEagerResolvedStrings() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700604 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
605 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700606}
607
Ian Rogersef7d42f2014-01-06 12:55:46 -0800608bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700609 std::string temp;
610 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700611}
612
613struct NonImageClasses {
614 ImageWriter* image_writer;
615 std::set<std::string>* non_image_classes;
616};
617
618void ImageWriter::PruneNonImageClasses() {
619 if (compiler_driver_.GetImageClasses() == NULL) {
620 return;
621 }
622 Runtime* runtime = Runtime::Current();
623 ClassLinker* class_linker = runtime->GetClassLinker();
624
625 // Make a list of classes we would like to prune.
626 std::set<std::string> non_image_classes;
627 NonImageClasses context;
628 context.image_writer = this;
629 context.non_image_classes = &non_image_classes;
630 class_linker->VisitClasses(NonImageClassesVisitor, &context);
631
632 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700633 for (const std::string& it : non_image_classes) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800634 bool result = class_linker->RemoveClass(it.c_str(), NULL);
635 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700636 }
637
638 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700639 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700640 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
641 size_t dex_cache_count = class_linker->GetDexCacheCount();
642 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
643 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700644 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
645 Class* klass = dex_cache->GetResolvedType(i);
646 if (klass != NULL && !IsImageClass(klass)) {
647 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700648 }
649 }
650 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700651 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700652 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
653 dex_cache->SetResolvedMethod(i, resolution_method);
654 }
655 }
656 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700657 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700658 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
659 dex_cache->SetResolvedField(i, NULL);
660 }
661 }
662 }
663}
664
665bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
666 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
667 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700668 std::string temp;
669 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700670 }
671 return true;
672}
673
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800674void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700675 if (compiler_driver_.GetImageClasses() != nullptr) {
676 gc::Heap* heap = Runtime::Current()->GetHeap();
677 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
678 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700679 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700680}
681
682void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
683 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700684 if (obj->IsClass()) {
685 Class* klass = obj->AsClass();
686 if (!image_writer->IsImageClass(klass)) {
687 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700688 std::string temp;
689 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700690 << " " << PrettyDescriptor(klass);
691 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700692 }
693}
694
695void ImageWriter::DumpImageClasses() {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700696 const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700697 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700698 for (const std::string& image_class : *image_classes) {
699 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700700 }
701}
702
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800703void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700704 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700705 // if it is a string, we want to intern it if its not interned.
706 if (obj->GetClass()->IsStringClass()) {
707 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800708 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700709 DCHECK_EQ(obj, obj->AsString()->Intern());
710 return;
711 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700712 mirror::String* const interned = obj->AsString()->Intern();
713 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800714 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700715 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800716 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700717 }
718 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800719 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700720 return;
721 }
722 // else (obj == interned), nothing to do but fall through to the normal case
723 }
724
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800725 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700726}
727
728ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
729 Runtime* runtime = Runtime::Current();
730 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700731 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700732 StackHandleScope<3> hs(self);
733 Handle<Class> object_array_class(hs.NewHandle(
734 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700735
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700736 // build an Object[] of all the DexCaches used in the source_space_.
737 // Since we can't hold the dex lock when allocating the dex_caches
738 // ObjectArray, we lock the dex lock twice, first to get the number
739 // of dex caches first and then lock it again to copy the dex
740 // caches. We check that the number of dex caches does not change.
741 size_t dex_cache_count;
742 {
743 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
744 dex_cache_count = class_linker->GetDexCacheCount();
745 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700746 Handle<ObjectArray<Object>> dex_caches(
747 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700748 dex_cache_count)));
749 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
750 {
751 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
752 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
753 << "The number of dex caches changed.";
754 for (size_t i = 0; i < dex_cache_count; ++i) {
755 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
756 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700757 }
758
759 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700760 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700761 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100762 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
763 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700764 image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
765 runtime->GetImtUnimplementedMethod());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100766 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
767 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
768 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
769 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
770 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
771 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
772 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700773 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100774 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700775 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
776 CHECK(image_roots->Get(i) != NULL);
777 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700778 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700779}
780
Mathieu Chartier590fee92013-09-13 13:46:47 -0700781// Walk instance fields of the given Class. Separate function to allow recursion on the super
782// class.
783void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
784 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700785 StackHandleScope<1> hs(Thread::Current());
786 Handle<mirror::Class> h_class(hs.NewHandle(klass));
787 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700788 if (super != nullptr) {
789 WalkInstanceFields(obj, super);
790 }
791 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700792 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000793 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700794 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700795 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700796 if (value != nullptr) {
797 WalkFieldsInOrder(value);
798 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000799 field_offset = MemberOffset(field_offset.Uint32Value() +
800 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700801 }
802}
803
804// For an unvisited object, visit it then all its children found via fields.
805void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800806 // Use our own visitor routine (instead of GC visitor) to get better locality between
807 // an object and its fields
808 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700809 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700810 StackHandleScope<2> hs(Thread::Current());
811 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
812 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700813 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800814 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700815 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700816 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700817 if (h_obj->IsClass()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700818 size_t num_static_fields = klass->NumReferenceStaticFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000819 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700820 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700821 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700822 if (value != nullptr) {
823 WalkFieldsInOrder(value);
824 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000825 field_offset = MemberOffset(field_offset.Uint32Value() +
826 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700827 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700828 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700829 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700830 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700831 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700832 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700833 mirror::Object* value = obj_array->Get(i);
834 if (value != nullptr) {
835 WalkFieldsInOrder(value);
836 }
837 }
838 }
839 }
840}
841
842void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
843 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
844 DCHECK(writer != nullptr);
845 writer->WalkFieldsInOrder(obj);
846}
847
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800848void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
849 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
850 DCHECK(writer != nullptr);
851 writer->UnbinObjectsIntoOffset(obj);
852}
853
854void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
855 CHECK(obj != nullptr);
856
857 // We know the bin slot, and the total bin sizes for all objects by now,
858 // so calculate the object's final image offset.
859
860 DCHECK(IsImageBinSlotAssigned(obj));
861 BinSlot bin_slot = GetImageBinSlot(obj);
862 // Change the lockword from a bin slot into an offset
863 AssignImageOffset(obj, bin_slot);
864}
865
Vladimir Markof4da6752014-08-01 19:04:18 +0100866void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700867 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700868 StackHandleScope<1> hs(self);
869 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700870
871 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700872 DCHECK_EQ(0U, image_end_);
873
Mathieu Chartier31e89252013-08-28 11:29:12 -0700874 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700875 // know where image_roots is going to end up
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800876 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700877
878 {
879 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700880 // TODO: Image spaces only?
Mathieu Chartier590fee92013-09-13 13:46:47 -0700881 DCHECK_LT(image_end_, image_->Size());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800882 image_objects_offset_begin_ = image_end_;
883 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700884 heap->VisitObjects(WalkFieldsCallback, this);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800885 // Transform each object's bin slot into an offset which will be used to do the final copy.
886 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
887 DCHECK(saved_hashes_map_.empty()); // All binslot hashes should've been put into vector by now.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700888 }
889
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800890 DCHECK_GT(image_end_, GetBinSizeSum());
891
Vladimir Markof4da6752014-08-01 19:04:18 +0100892 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
893
894 // Note that image_end_ is left at end of used space
895}
896
897void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
898 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -0700899 const uint8_t* oat_file_begin = GetOatFileBegin();
900 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800901
Brian Carlstrom7940e442013-07-12 13:46:57 -0700902 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -0700903 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700904
Mathieu Chartier31e89252013-08-28 11:29:12 -0700905 // Return to write header at start of image with future location of image_roots. At this point,
906 // image_end_ is the size of the image (excluding bitmaps).
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700907 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800908 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
909 heap_bytes_per_bitmap_byte;
Vladimir Markof4da6752014-08-01 19:04:18 +0100910 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
911 static_cast<uint32_t>(image_end_),
912 RoundUp(image_end_, kPageSize),
913 RoundUp(bitmap_bytes, kPageSize),
914 image_roots_address_,
915 oat_file_->GetOatHeader().GetChecksum(),
916 PointerToLowMemUInt32(oat_file_begin),
917 PointerToLowMemUInt32(oat_data_begin_),
918 PointerToLowMemUInt32(oat_data_end),
Igor Murashkin46774762014-10-22 11:37:02 -0700919 PointerToLowMemUInt32(oat_file_end),
920 compile_pic_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700921}
922
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800923void ImageWriter::CopyAndFixupObjects() {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -0700924 ScopedAssertNoThreadSuspension ants(Thread::Current(), "ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700925 gc::Heap* heap = Runtime::Current()->GetHeap();
926 // TODO: heap validation can't handle this fix up pass
927 heap->DisableObjectValidation();
928 // TODO: Image spaces only?
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -0700929 WriterMutexLock mu(ants.Self(), *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700930 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
931 // Fix up the object previously had hash codes.
932 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700933 hash_pair.first->SetLockWord(LockWord::FromHashCode(hash_pair.second), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700934 }
935 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700936}
937
Mathieu Chartier590fee92013-09-13 13:46:47 -0700938void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700939 DCHECK(obj != nullptr);
940 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700941 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700942 // see GetLocalAddress for similar computation
943 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers13735952014-10-08 12:43:28 -0700944 uint8_t* dst = image_writer->image_->Begin() + offset;
945 const uint8_t* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800946 size_t n;
947 if (obj->IsArtMethod()) {
948 // Size without pointer fields since we don't want to overrun the buffer if target art method
949 // is 32 bits but source is 64 bits.
Mathieu Chartiereace4582014-11-24 18:29:54 -0800950 n = mirror::ArtMethod::SizeWithoutPointerFields(sizeof(void*));
Mathieu Chartier2d721012014-11-10 11:08:06 -0800951 } else {
952 n = obj->SizeOf();
953 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700954 DCHECK_LT(offset + n, image_writer->image_->Size());
955 memcpy(dst, src, n);
956 Object* copy = reinterpret_cast<Object*>(dst);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700957 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
958 // word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700959 copy->SetLockWord(LockWord(), false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700960 image_writer->FixupObject(obj, copy);
961}
962
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800963// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700964class FixupVisitor {
965 public:
966 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
967 }
968
969 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
970 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -0700971 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700972 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
973 // image.
974 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700975 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700976 }
977
978 // java.lang.ref.Reference visitor.
979 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
980 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
981 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
982 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700983 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700984 }
985
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700986 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700987 ImageWriter* const image_writer_;
988 mirror::Object* const copy_;
989};
990
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700991class FixupClassVisitor FINAL : public FixupVisitor {
992 public:
993 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
994 }
995
996 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
997 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
998 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800999 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001000
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001001 // TODO: Remove dead code
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001002 if (offset.Uint32Value() < mirror::Class::EmbeddedVTableOffset().Uint32Value()) {
1003 return;
1004 }
1005 }
1006
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001007 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1008 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001009 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1010 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1011 LOG(FATAL) << "Reference not expected here.";
1012 }
1013};
1014
Ian Rogersef7d42f2014-01-06 12:55:46 -08001015void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001016 DCHECK(orig != nullptr);
1017 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001018 if (kUseBakerOrBrooksReadBarrier) {
1019 orig->AssertReadBarrierPointer();
1020 if (kUseBrooksReadBarrier) {
1021 // Note the address 'copy' isn't the same as the image address of 'orig'.
1022 copy->SetReadBarrierPointer(GetImageAddress(orig));
1023 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1024 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001025 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001026 if (orig->IsClass() && orig->AsClass()->ShouldHaveEmbeddedImtAndVTable()) {
1027 FixupClassVisitor visitor(this, copy);
1028 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
1029 } else {
1030 FixupVisitor visitor(this, copy);
1031 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
1032 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001033 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001034 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001035 } else if (orig->IsClass() && orig->AsClass()->IsArtMethodClass()) {
1036 // Set the right size for the target.
1037 size_t size = mirror::ArtMethod::InstanceSize(target_ptr_size_);
1038 down_cast<mirror::Class*>(copy)->SetObjectSizeWithoutChecks(size);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001039 }
1040}
1041
Ian Rogers13735952014-10-08 12:43:28 -07001042const uint8_t* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001043 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001044 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001045
1046 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1047 // trampoline.
1048
1049 // Quick entrypoint:
Ian Rogers13735952014-10-08 12:43:28 -07001050 const uint8_t* quick_code = GetOatAddress(method->GetQuickOatCodeOffset());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001051 *quick_is_interpreted = false;
1052 if (quick_code != nullptr &&
1053 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
1054 // We have code for a non-static or initialized method, just use the code.
1055 } else if (quick_code == nullptr && method->IsNative() &&
1056 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1057 // Non-static or initialized native method missing compiled code, use generic JNI version.
1058 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
1059 } else if (quick_code == nullptr && !method->IsNative()) {
1060 // We don't have code at all for a non-native method, use the interpreter.
1061 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
1062 *quick_is_interpreted = true;
1063 } else {
1064 CHECK(!method->GetDeclaringClass()->IsInitialized());
1065 // We have code for a static method, but need to go through the resolution stub for class
1066 // initialization.
1067 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
1068 }
1069 return quick_code;
1070}
1071
Ian Rogers13735952014-10-08 12:43:28 -07001072const uint8_t* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001073 // Calculate the quick entry point following the same logic as FixupMethod() below.
1074 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001075 Runtime* runtime = Runtime::Current();
1076 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001077 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001078 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
1079 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001080 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
1081 } else {
1082 // We assume all methods have code. If they don't currently then we set them to the use the
1083 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1084 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1085 if (UNLIKELY(method->IsAbstract())) {
1086 return GetOatAddress(quick_to_interpreter_bridge_offset_);
1087 } else {
1088 bool quick_is_interpreted;
1089 return GetQuickCode(method, &quick_is_interpreted);
1090 }
1091 }
1092}
1093
Ian Rogersef7d42f2014-01-06 12:55:46 -08001094void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -07001095 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1096 // oat_begin_
Mathieu Chartier2d721012014-11-10 11:08:06 -08001097 // For 64 bit targets we need to repack the current runtime pointer sized fields to the right
1098 // locations.
1099 // Copy all of the fields from the runtime methods to the target methods first since we did a
1100 // bytewise copy earlier.
1101 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
1102 orig->GetEntryPointFromPortableCompiledCode(), target_ptr_size_);
1103 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(orig->GetEntryPointFromInterpreter(),
1104 target_ptr_size_);
1105 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(orig->GetEntryPointFromJni(), target_ptr_size_);
1106 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1107 orig->GetEntryPointFromQuickCompiledCode(), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001108
Ian Rogers848871b2013-08-05 10:56:33 -07001109 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001110 Runtime* runtime = Runtime::Current();
1111 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001112 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
1113 GetOatAddress(portable_resolution_trampoline_offset_), target_ptr_size_);
1114 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1115 GetOatAddress(quick_resolution_trampoline_offset_), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001116 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1117 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001118 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
1119 GetOatAddress(portable_imt_conflict_trampoline_offset_), target_ptr_size_);
1120 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1121 GetOatAddress(quick_imt_conflict_trampoline_offset_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001122 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001123 // We assume all methods have code. If they don't currently then we set them to the use the
1124 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1125 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1126 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001127 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
1128 GetOatAddress(portable_to_interpreter_bridge_offset_), target_ptr_size_);
1129 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1130 GetOatAddress(quick_to_interpreter_bridge_offset_), target_ptr_size_);
1131 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1132 reinterpret_cast<EntryPointFromInterpreter*>(const_cast<uint8_t*>(
1133 GetOatAddress(interpreter_to_interpreter_bridge_offset_))), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001134 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001135 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -07001136 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001137 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001138
1139 // Portable entrypoint:
Ian Rogers13735952014-10-08 12:43:28 -07001140 const uint8_t* portable_code = GetOatAddress(orig->GetPortableOatCodeOffset());
Sebastien Hertze1d07812014-05-21 15:44:09 +02001141 bool portable_is_interpreted = false;
1142 if (portable_code != nullptr &&
1143 (!orig->IsStatic() || orig->IsConstructor() || orig->GetDeclaringClass()->IsInitialized())) {
1144 // We have code for a non-static or initialized method, just use the code.
1145 } else if (portable_code == nullptr && orig->IsNative() &&
1146 (!orig->IsStatic() || orig->GetDeclaringClass()->IsInitialized())) {
1147 // Non-static or initialized native method missing compiled code, use generic JNI version.
1148 // TODO: generic JNI support for LLVM.
1149 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
1150 } else if (portable_code == nullptr && !orig->IsNative()) {
1151 // We don't have code at all for a non-native method, use the interpreter.
1152 portable_code = GetOatAddress(portable_to_interpreter_bridge_offset_);
1153 portable_is_interpreted = true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001154 } else {
Sebastien Hertze1d07812014-05-21 15:44:09 +02001155 CHECK(!orig->GetDeclaringClass()->IsInitialized());
1156 // We have code for a static method, but need to go through the resolution stub for class
1157 // initialization.
1158 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
Ian Rogers848871b2013-08-05 10:56:33 -07001159 }
Mathieu Chartier2d721012014-11-10 11:08:06 -08001160 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
1161 portable_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001162 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001163 if (orig->IsNative()) {
1164 // The native method's pointer is set to a stub to lookup via dlsym.
1165 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier2d721012014-11-10 11:08:06 -08001166 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_),
1167 target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001168 }
Sebastien Hertze1d07812014-05-21 15:44:09 +02001169
1170 // Interpreter entrypoint:
1171 // Set the interpreter entrypoint depending on whether there is compiled code or not.
1172 uint32_t interpreter_code = (quick_is_interpreted && portable_is_interpreted)
1173 ? interpreter_to_interpreter_bridge_offset_
1174 : interpreter_to_compiled_code_bridge_offset_;
Mathieu Chartier2d721012014-11-10 11:08:06 -08001175 EntryPointFromInterpreter* interpreter_entrypoint =
Sebastien Hertze1d07812014-05-21 15:44:09 +02001176 reinterpret_cast<EntryPointFromInterpreter*>(
Mathieu Chartier2d721012014-11-10 11:08:06 -08001177 const_cast<uint8_t*>(GetOatAddress(interpreter_code)));
1178 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1179 interpreter_entrypoint, target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001180 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001181 }
1182}
1183
Alex Lighta59dd802014-07-02 16:28:08 -07001184static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001185 uint64_t data_sec_offset;
1186 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1187 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001188 return nullptr;
1189 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001190 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001191}
1192
Vladimir Markof4da6752014-08-01 19:04:18 +01001193void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001194 std::string error_msg;
1195 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
1196 MAP_SHARED, &error_msg));
1197 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001198 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001199 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001200 }
Alex Lighta59dd802014-07-02 16:28:08 -07001201 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1202 CHECK(oat_header != nullptr);
1203 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001204
Brian Carlstrom7940e442013-07-12 13:46:57 -07001205 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001206 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001207}
1208
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001209size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1210 DCHECK_LE(up_to, kBinSize);
1211 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1212}
1213
1214ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1215 // These values may need to get updated if more bins are added to the enum Bin
1216 static_assert(kBinBits == 3, "wrong number of bin bits");
1217 static_assert(kBinShift == 29, "wrong number of shift");
1218 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1219
1220 DCHECK_LT(GetBin(), kBinSize);
1221 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1222}
1223
1224ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1225 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1226 DCHECK_EQ(index, GetIndex());
1227}
1228
1229ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1230 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1231}
1232
1233uint32_t ImageWriter::BinSlot::GetIndex() const {
1234 return lockword_ & ~kBinMask;
1235}
1236
Brian Carlstrom7940e442013-07-12 13:46:57 -07001237} // namespace art