blob: d238b2cb05c31e48ba5f7c9748434fbf460fc930 [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
Andreas Gampedd9d0552015-03-09 12:57:41 -070074static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
75 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
76 Class* klass = obj->GetClass();
77 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
78}
79
80static void CheckNoDexObjects() {
81 ScopedObjectAccess soa(Thread::Current());
82 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
83}
84
Vladimir Markof4da6752014-08-01 19:04:18 +010085bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -080086 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +010087 {
88 Thread::Current()->TransitionFromSuspendedToRunnable();
89 PruneNonImageClasses(); // Remove junk
90 ComputeLazyFieldsForImageClasses(); // Add useful information
Vladimir Marko3389ca72014-12-03 14:35:54 +000091 ProcessStrings();
Vladimir Markof4da6752014-08-01 19:04:18 +010092 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
93 }
94 gc::Heap* heap = Runtime::Current()->GetHeap();
95 heap->CollectGarbage(false); // Remove garbage.
96
Andreas Gampedd9d0552015-03-09 12:57:41 -070097 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
98 // dex files.
99 //
100 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
101 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
102 // true.
103 if (kIsDebugBuild) {
104 CheckNoDexObjects();
105 }
106
Vladimir Markof4da6752014-08-01 19:04:18 +0100107 if (!AllocMemory()) {
108 return false;
109 }
110
111 if (kIsDebugBuild) {
112 ScopedObjectAccess soa(Thread::Current());
113 CheckNonImageClassesRemoved();
114 }
115
116 Thread::Current()->TransitionFromSuspendedToRunnable();
117 CalculateNewObjectOffsets();
118 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
119
120 return true;
121}
122
Brian Carlstrom7940e442013-07-12 13:46:57 -0700123bool ImageWriter::Write(const std::string& image_filename,
Brian Carlstrom7940e442013-07-12 13:46:57 -0700124 const std::string& oat_filename,
125 const std::string& oat_location) {
126 CHECK(!image_filename.empty());
127
Brian Carlstrom7940e442013-07-12 13:46:57 -0700128 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700129
Ian Rogers700a4022014-05-19 16:49:03 -0700130 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700131 if (oat_file.get() == NULL) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800132 PLOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700133 return false;
134 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700135 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -0700136 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, &error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700137 if (oat_file_ == nullptr) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800138 PLOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700139 << ": " << error_msg;
Andreas Gampe0b7fcf92015-03-13 16:54:54 -0700140 oat_file->Erase();
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700141 return false;
142 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700143 CHECK_EQ(class_linker->RegisterOatFile(oat_file_), oat_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700144
Ian Rogers848871b2013-08-05 10:56:33 -0700145 interpreter_to_interpreter_bridge_offset_ =
146 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
147 interpreter_to_compiled_code_bridge_offset_ =
148 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
149
150 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
151
Andreas Gampe2da88232014-02-27 12:26:20 -0800152 quick_generic_jni_trampoline_offset_ =
153 oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
Jeff Hao88474b42013-10-23 16:24:40 -0700154 quick_imt_conflict_trampoline_offset_ =
155 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700156 quick_resolution_trampoline_offset_ =
157 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
158 quick_to_interpreter_bridge_offset_ =
159 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700160
Brian Carlstrom7940e442013-07-12 13:46:57 -0700161 size_t oat_loaded_size = 0;
162 size_t oat_data_offset = 0;
163 ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
Alex Light53cb16b2014-06-12 11:26:29 -0700164
Vladimir Markof4da6752014-08-01 19:04:18 +0100165 Thread::Current()->TransitionFromSuspendedToRunnable();
166 CreateHeader(oat_loaded_size, oat_data_offset);
167 CopyAndFixupObjects();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700168 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
169
Vladimir Markof4da6752014-08-01 19:04:18 +0100170 SetOatChecksumFromElfFile(oat_file.get());
171
Andreas Gampe4303ba92014-11-06 01:00:46 -0800172 if (oat_file->FlushCloseOrErase() != 0) {
173 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename << " for " << oat_location;
174 return false;
175 }
176
Ian Rogers700a4022014-05-19 16:49:03 -0700177 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700178 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 if (image_file.get() == NULL) {
180 LOG(ERROR) << "Failed to open image file " << image_filename;
181 return false;
182 }
183 if (fchmod(image_file->Fd(), 0644) != 0) {
184 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800185 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700186 return EXIT_FAILURE;
187 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700188
189 // Write out the image.
190 CHECK_EQ(image_end_, image_header->GetImageSize());
191 if (!image_file->WriteFully(image_->Begin(), image_end_)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700192 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800193 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700194 return false;
195 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700196
197 // Write out the image bitmap at the page aligned start of the image end.
198 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
199 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
200 image_header->GetImageBitmapSize(),
201 image_header->GetImageBitmapOffset())) {
202 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800203 image_file->Erase();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700204 return false;
205 }
206
Andreas Gampe4303ba92014-11-06 01:00:46 -0800207 if (image_file->FlushCloseOrErase() != 0) {
208 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
209 return false;
210 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700211 return true;
212}
213
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800214void ImageWriter::SetImageOffset(mirror::Object* object,
215 ImageWriter::BinSlot bin_slot,
216 size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700217 DCHECK(object != nullptr);
218 DCHECK_NE(offset, 0U);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700219 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
220 DCHECK_ALIGNED(obj, kObjectAlignment);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800221
222 image_bitmap_->Set(obj); // Mark the obj as mutated, since we will end up changing it.
223 {
224 // Remember the object-inside-of-the-image's hash code so we can restore it after the copy.
225 auto hash_it = saved_hashes_map_.find(bin_slot);
226 if (hash_it != saved_hashes_map_.end()) {
227 std::pair<BinSlot, uint32_t> slot_hash = *hash_it;
228 saved_hashes_.push_back(std::make_pair(obj, slot_hash.second));
229 saved_hashes_map_.erase(hash_it);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700230 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700231 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800232 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700233 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700234 DCHECK(IsImageOffsetAssigned(object));
235}
236
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800237void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700238 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800239 DCHECK_NE(image_objects_offset_begin_, 0u);
240
241 size_t previous_bin_sizes = GetBinSizeSum(bin_slot.GetBin()); // sum sizes in [0..bin#)
242 size_t new_offset = image_objects_offset_begin_ + previous_bin_sizes + bin_slot.GetIndex();
243 DCHECK_ALIGNED(new_offset, kObjectAlignment);
244
245 SetImageOffset(object, bin_slot, new_offset);
246 DCHECK_LT(new_offset, image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700247}
248
Ian Rogersef7d42f2014-01-06 12:55:46 -0800249bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800250 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700251 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700252 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700253}
254
Ian Rogersef7d42f2014-01-06 12:55:46 -0800255size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700256 DCHECK(object != nullptr);
257 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700258 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700259 size_t offset = lock_word.ForwardingAddress();
260 DCHECK_LT(offset, image_end_);
261 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700262}
263
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800264void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
265 DCHECK(object != nullptr);
266 DCHECK(!IsImageOffsetAssigned(object));
267 DCHECK(!IsImageBinSlotAssigned(object));
268
269 // Before we stomp over the lock word, save the hash code for later.
270 Monitor::Deflate(Thread::Current(), object);;
271 LockWord lw(object->GetLockWord(false));
272 switch (lw.GetState()) {
273 case LockWord::kFatLocked: {
274 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
275 break;
276 }
277 case LockWord::kThinLocked: {
278 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
279 break;
280 }
281 case LockWord::kUnlocked:
282 // No hash, don't need to save it.
283 break;
284 case LockWord::kHashCode:
285 saved_hashes_map_[bin_slot] = lw.GetHashCode();
286 break;
287 default:
288 LOG(FATAL) << "Unreachable.";
289 UNREACHABLE();
290 }
291 object->SetLockWord(LockWord::FromForwardingAddress(static_cast<uint32_t>(bin_slot)),
292 false);
293 DCHECK(IsImageBinSlotAssigned(object));
294}
295
296void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
297 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800298 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800299
300 // The magic happens here. We segregate objects into different bins based
301 // on how likely they are to get dirty at runtime.
302 //
303 // Likely-to-dirty objects get packed together into the same bin so that
304 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
305 // maximized.
306 //
307 // This means more pages will stay either clean or shared dirty (with zygote) and
308 // the app will use less of its own (private) memory.
309 Bin bin = kBinRegular;
310
311 if (kBinObjects) {
312 //
313 // Changing the bin of an object is purely a memory-use tuning.
314 // It has no change on runtime correctness.
315 //
316 // Memory analysis has determined that the following types of objects get dirtied
317 // the most:
318 //
319 // * Class'es which are verified [their clinit runs only at runtime]
320 // - classes in general [because their static fields get overwritten]
321 // - initialized classes with all-final statics are unlikely to be ever dirty,
322 // so bin them separately
323 // * Art Methods that are:
324 // - native [their native entry point is not looked up until runtime]
325 // - have declaring classes that aren't initialized
326 // [their interpreter/quick entry points are trampolines until the class
327 // becomes initialized]
328 //
329 // We also assume the following objects get dirtied either never or extremely rarely:
330 // * Strings (they are immutable)
331 // * Art methods that aren't native and have initialized declared classes
332 //
333 // We assume that "regular" bin objects are highly unlikely to become dirtied,
334 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
335 //
336 if (object->IsClass()) {
337 bin = kBinClassVerified;
338 mirror::Class* klass = object->AsClass();
339
340 if (klass->GetStatus() == Class::kStatusInitialized) {
341 bin = kBinClassInitialized;
342
343 // If the class's static fields are all final, put it into a separate bin
344 // since it's very likely it will stay clean.
345 uint32_t num_static_fields = klass->NumStaticFields();
346 if (num_static_fields == 0) {
347 bin = kBinClassInitializedFinalStatics;
348 } else {
349 // Maybe all the statics are final?
350 bool all_final = true;
351 for (uint32_t i = 0; i < num_static_fields; ++i) {
352 ArtField* field = klass->GetStaticField(i);
353 if (!field->IsFinal()) {
354 all_final = false;
355 break;
356 }
357 }
358
359 if (all_final) {
360 bin = kBinClassInitializedFinalStatics;
361 }
362 }
363 }
364 } else if (object->IsArtMethod<kVerifyNone>()) {
365 mirror::ArtMethod* art_method = down_cast<ArtMethod*>(object);
366 if (art_method->IsNative()) {
367 bin = kBinArtMethodNative;
368 } else {
369 mirror::Class* declaring_class = art_method->GetDeclaringClass();
370 if (declaring_class->GetStatus() != Class::kStatusInitialized) {
371 bin = kBinArtMethodNotInitialized;
372 } else {
373 // This is highly unlikely to dirty since there's no entry points to mutate.
374 bin = kBinArtMethodsManagedInitialized;
375 }
376 }
377 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
378 bin = kBinString; // Strings are almost always immutable (except for object header).
379 } // else bin = kBinRegular
380 }
381
382 size_t current_offset = bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
383 // Move the current bin size up to accomodate the object we just assigned a bin slot.
384 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
385 bin_slot_sizes_[bin] += offset_delta;
386
387 BinSlot new_bin_slot(bin, current_offset);
388 SetImageBinSlot(object, new_bin_slot);
389
390 ++bin_slot_count_[bin];
391
392 DCHECK_LT(GetBinSizeSum(), image_->Size());
393
394 // Grow the image closer to the end by the object we just assigned.
395 image_end_ += offset_delta;
396 DCHECK_LT(image_end_, image_->Size());
397}
398
399bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
400 DCHECK(object != nullptr);
401
402 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
403 // If it's in some other state, then we haven't yet assigned an image bin slot.
404 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
405 return false;
406 } else if (kIsDebugBuild) {
407 LockWord lock_word = object->GetLockWord(false);
408 size_t offset = lock_word.ForwardingAddress();
409 BinSlot bin_slot(offset);
410 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()])
411 << "bin slot offset should not exceed the size of that bin";
412 }
413 return true;
414}
415
416ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
417 DCHECK(object != nullptr);
418 DCHECK(IsImageBinSlotAssigned(object));
419
420 LockWord lock_word = object->GetLockWord(false);
421 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
422 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
423
424 BinSlot bin_slot(static_cast<uint32_t>(offset));
425 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()]);
426
427 return bin_slot;
428}
429
Brian Carlstrom7940e442013-07-12 13:46:57 -0700430bool ImageWriter::AllocMemory() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700431 size_t length = RoundUp(Runtime::Current()->GetHeap()->GetTotalMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700432 std::string error_msg;
Vladimir Marko5c42c292015-02-25 12:02:49 +0000433 image_.reset(MemMap::MapAnonymous("image writer image", nullptr, length, PROT_READ | PROT_WRITE,
434 false, false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700435 if (UNLIKELY(image_.get() == nullptr)) {
436 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700437 return false;
438 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700439
440 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700441 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
442 length));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700443 if (image_bitmap_.get() == nullptr) {
444 LOG(ERROR) << "Failed to allocate memory for image bitmap";
445 return false;
446 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700447 return true;
448}
449
450void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700451 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700452 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
453}
454
455bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700456 Thread* self = Thread::Current();
457 StackHandleScope<1> hs(self);
458 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700459 return true;
460}
461
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800462// Count the number of strings in the heap and put the result in arg as a size_t pointer.
463static void CountStringsCallback(Object* obj, void* arg)
464 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
465 if (obj->GetClass()->IsStringClass()) {
466 ++*reinterpret_cast<size_t*>(arg);
467 }
468}
469
470// Collect all the java.lang.String in the heap and put them in the output strings_ array.
471class StringCollector {
472 public:
473 StringCollector(Handle<mirror::ObjectArray<mirror::String>> strings, size_t index)
474 : strings_(strings), index_(index) {
475 }
476 static void Callback(Object* obj, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
477 auto* collector = reinterpret_cast<StringCollector*>(arg);
478 if (obj->GetClass()->IsStringClass()) {
479 collector->strings_->SetWithoutChecks<false>(collector->index_++, obj->AsString());
480 }
481 }
482 size_t GetIndex() const {
483 return index_;
484 }
485
486 private:
487 Handle<mirror::ObjectArray<mirror::String>> strings_;
488 size_t index_;
489};
490
491// Compare strings based on length, used for sorting strings by length / reverse length.
Vladimir Markofaeda182014-12-04 14:52:25 +0000492class LexicographicalStringComparator {
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800493 public:
Vladimir Markofaeda182014-12-04 14:52:25 +0000494 bool operator()(const mirror::HeapReference<mirror::String>& lhs,
495 const mirror::HeapReference<mirror::String>& rhs) const
496 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
497 mirror::String* lhs_s = lhs.AsMirrorPtr();
498 mirror::String* rhs_s = rhs.AsMirrorPtr();
499 uint16_t* lhs_begin = lhs_s->GetCharArray()->GetData() + lhs_s->GetOffset();
500 uint16_t* rhs_begin = rhs_s->GetCharArray()->GetData() + rhs_s->GetOffset();
501 return std::lexicographical_compare(lhs_begin, lhs_begin + lhs_s->GetLength(),
502 rhs_begin, rhs_begin + rhs_s->GetLength());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800503 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800504};
505
Vladimir Markofaeda182014-12-04 14:52:25 +0000506static bool IsPrefix(mirror::String* pref, mirror::String* full)
507 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
508 if (pref->GetLength() > full->GetLength()) {
509 return false;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800510 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000511 uint16_t* pref_begin = pref->GetCharArray()->GetData() + pref->GetOffset();
512 uint16_t* full_begin = full->GetCharArray()->GetData() + full->GetOffset();
513 return std::equal(pref_begin, pref_begin + pref->GetLength(), full_begin);
514}
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800515
516void ImageWriter::ProcessStrings() {
517 size_t total_strings = 0;
518 gc::Heap* heap = Runtime::Current()->GetHeap();
519 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800520 // Count the strings.
521 heap->VisitObjects(CountStringsCallback, &total_strings);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800522 Thread* self = Thread::Current();
523 StackHandleScope<1> hs(self);
524 auto strings = hs.NewHandle(cl->AllocStringArray(self, total_strings));
525 StringCollector string_collector(strings, 0U);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800526 // Read strings into the array.
527 heap->VisitObjects(StringCollector::Callback, &string_collector);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800528 // Some strings could have gotten freed if AllocStringArray caused a GC.
529 CHECK_LE(string_collector.GetIndex(), total_strings);
530 total_strings = string_collector.GetIndex();
Vladimir Markofaeda182014-12-04 14:52:25 +0000531 auto* strings_begin = reinterpret_cast<mirror::HeapReference<mirror::String>*>(
532 strings->GetRawData(sizeof(mirror::HeapReference<mirror::String>), 0));
533 std::sort(strings_begin, strings_begin + total_strings, LexicographicalStringComparator());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800534 // Characters of strings which are non equal prefix of another string (not the same string).
535 // We don't count the savings from equal strings since these would get interned later anyways.
536 size_t prefix_saved_chars = 0;
Vladimir Markofaeda182014-12-04 14:52:25 +0000537 // Count characters needed for the strings.
538 size_t num_chars = 0u;
539 mirror::String* prev_s = nullptr;
540 for (size_t idx = 0; idx != total_strings; ++idx) {
541 mirror::String* s = strings->GetWithoutChecks(idx);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800542 size_t length = s->GetLength();
Vladimir Markofaeda182014-12-04 14:52:25 +0000543 num_chars += length;
544 if (prev_s != nullptr && IsPrefix(prev_s, s)) {
545 size_t prev_length = prev_s->GetLength();
546 num_chars -= prev_length;
547 if (prev_length != length) {
548 prefix_saved_chars += prev_length;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800549 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800550 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000551 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800552 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000553 // Create character array, copy characters and point the strings there.
554 mirror::CharArray* array = mirror::CharArray::Alloc(self, num_chars);
Andreas Gampe245ee002014-12-04 21:25:04 -0800555 string_data_array_ = array;
Vladimir Markofaeda182014-12-04 14:52:25 +0000556 uint16_t* array_data = array->GetData();
557 size_t pos = 0u;
558 prev_s = nullptr;
559 for (size_t idx = 0; idx != total_strings; ++idx) {
560 mirror::String* s = strings->GetWithoutChecks(idx);
561 uint16_t* s_data = s->GetCharArray()->GetData() + s->GetOffset();
562 int32_t s_length = s->GetLength();
563 int32_t prefix_length = 0u;
564 if (idx != 0u && IsPrefix(prev_s, s)) {
565 prefix_length = prev_s->GetLength();
566 }
567 memcpy(array_data + pos, s_data + prefix_length, (s_length - prefix_length) * sizeof(*s_data));
568 s->SetOffset(pos - prefix_length);
569 s->SetArray(array);
570 pos += s_length - prefix_length;
571 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800572 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000573 CHECK_EQ(pos, num_chars);
574
Andreas Gampedc843012015-01-20 16:17:19 -0800575 if (kIsDebugBuild || VLOG_IS_ON(compiler)) {
576 LOG(INFO) << "Total # image strings=" << total_strings << " combined length="
577 << num_chars << " prefix saved chars=" << prefix_saved_chars;
578 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800579 ComputeEagerResolvedStrings();
580}
581
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700582void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700583 if (!obj->GetClass()->IsStringClass()) {
584 return;
585 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700586 mirror::String* string = obj->AsString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700587 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
Vladimir Markoa48aef42014-12-03 17:53:53 +0000588 size_t utf16_length = static_cast<size_t>(string->GetLength());
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700589 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
590 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
591 size_t dex_cache_count = class_linker->GetDexCacheCount();
592 for (size_t i = 0; i < dex_cache_count; ++i) {
593 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700594 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800595 const DexFile::StringId* string_id;
Vladimir Markoa48aef42014-12-03 17:53:53 +0000596 if (UNLIKELY(utf16_length == 0)) {
Ian Rogers24c534d2013-11-14 00:15:00 -0800597 string_id = dex_file.FindStringId("");
598 } else {
Vladimir Markoa48aef42014-12-03 17:53:53 +0000599 string_id = dex_file.FindStringId(utf16_string, utf16_length);
Ian Rogers24c534d2013-11-14 00:15:00 -0800600 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700601 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700602 // This string occurs in this dex file, assign the dex cache entry.
603 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
604 if (dex_cache->GetResolvedString(string_idx) == NULL) {
605 dex_cache->SetResolvedString(string_idx, string);
606 }
607 }
608 }
609}
610
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800611void ImageWriter::ComputeEagerResolvedStrings() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700612 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700613}
614
Ian Rogersef7d42f2014-01-06 12:55:46 -0800615bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700616 std::string temp;
617 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700618}
619
620struct NonImageClasses {
621 ImageWriter* image_writer;
622 std::set<std::string>* non_image_classes;
623};
624
625void ImageWriter::PruneNonImageClasses() {
626 if (compiler_driver_.GetImageClasses() == NULL) {
627 return;
628 }
629 Runtime* runtime = Runtime::Current();
630 ClassLinker* class_linker = runtime->GetClassLinker();
631
632 // Make a list of classes we would like to prune.
633 std::set<std::string> non_image_classes;
634 NonImageClasses context;
635 context.image_writer = this;
636 context.non_image_classes = &non_image_classes;
637 class_linker->VisitClasses(NonImageClassesVisitor, &context);
638
639 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700640 for (const std::string& it : non_image_classes) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800641 bool result = class_linker->RemoveClass(it.c_str(), NULL);
642 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700643 }
644
645 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700646 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700647 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
648 size_t dex_cache_count = class_linker->GetDexCacheCount();
649 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
650 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700651 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
652 Class* klass = dex_cache->GetResolvedType(i);
653 if (klass != NULL && !IsImageClass(klass)) {
654 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700655 }
656 }
657 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700658 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700659 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
660 dex_cache->SetResolvedMethod(i, resolution_method);
661 }
662 }
663 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700664 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700665 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
666 dex_cache->SetResolvedField(i, NULL);
667 }
668 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700669 // Clean the dex field. It might have been populated during the initialization phase, but
670 // contains data only valid during a real run.
671 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700672 }
673}
674
675bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
676 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
677 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700678 std::string temp;
679 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700680 }
681 return true;
682}
683
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800684void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700685 if (compiler_driver_.GetImageClasses() != nullptr) {
686 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700687 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700688 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700689}
690
691void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
692 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700693 if (obj->IsClass()) {
694 Class* klass = obj->AsClass();
695 if (!image_writer->IsImageClass(klass)) {
696 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700697 std::string temp;
698 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700699 << " " << PrettyDescriptor(klass);
700 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700701 }
702}
703
704void ImageWriter::DumpImageClasses() {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700705 const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700706 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700707 for (const std::string& image_class : *image_classes) {
708 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700709 }
710}
711
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800712void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700713 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700714 // if it is a string, we want to intern it if its not interned.
715 if (obj->GetClass()->IsStringClass()) {
716 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800717 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700718 DCHECK_EQ(obj, obj->AsString()->Intern());
719 return;
720 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700721 mirror::String* const interned = obj->AsString()->Intern();
722 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800723 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700724 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800725 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700726 }
727 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800728 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700729 return;
730 }
731 // else (obj == interned), nothing to do but fall through to the normal case
732 }
733
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800734 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700735}
736
737ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
738 Runtime* runtime = Runtime::Current();
739 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700740 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700741 StackHandleScope<3> hs(self);
742 Handle<Class> object_array_class(hs.NewHandle(
743 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700744
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700745 // build an Object[] of all the DexCaches used in the source_space_.
746 // Since we can't hold the dex lock when allocating the dex_caches
747 // ObjectArray, we lock the dex lock twice, first to get the number
748 // of dex caches first and then lock it again to copy the dex
749 // caches. We check that the number of dex caches does not change.
750 size_t dex_cache_count;
751 {
752 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
753 dex_cache_count = class_linker->GetDexCacheCount();
754 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700755 Handle<ObjectArray<Object>> dex_caches(
756 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700757 dex_cache_count)));
758 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
759 {
760 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
761 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
762 << "The number of dex caches changed.";
763 for (size_t i = 0; i < dex_cache_count; ++i) {
764 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
765 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700766 }
767
768 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700769 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700770 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100771 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
772 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700773 image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
774 runtime->GetImtUnimplementedMethod());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100775 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
776 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
777 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
778 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
779 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
780 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
781 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700782 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100783 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700784 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
785 CHECK(image_roots->Get(i) != NULL);
786 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700787 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700788}
789
Mathieu Chartier590fee92013-09-13 13:46:47 -0700790// Walk instance fields of the given Class. Separate function to allow recursion on the super
791// class.
792void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
793 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700794 StackHandleScope<1> hs(Thread::Current());
795 Handle<mirror::Class> h_class(hs.NewHandle(klass));
796 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700797 if (super != nullptr) {
798 WalkInstanceFields(obj, super);
799 }
800 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700801 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000802 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700803 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700804 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700805 if (value != nullptr) {
806 WalkFieldsInOrder(value);
807 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000808 field_offset = MemberOffset(field_offset.Uint32Value() +
809 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700810 }
811}
812
813// For an unvisited object, visit it then all its children found via fields.
814void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800815 // Use our own visitor routine (instead of GC visitor) to get better locality between
816 // an object and its fields
817 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700818 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700819 StackHandleScope<2> hs(Thread::Current());
820 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
821 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700822 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800823 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700824 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700825 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700826 if (h_obj->IsClass()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700827 size_t num_static_fields = klass->NumReferenceStaticFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000828 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700829 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700830 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700831 if (value != nullptr) {
832 WalkFieldsInOrder(value);
833 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000834 field_offset = MemberOffset(field_offset.Uint32Value() +
835 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700836 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700837 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700838 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700839 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700840 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700841 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700842 mirror::Object* value = obj_array->Get(i);
843 if (value != nullptr) {
844 WalkFieldsInOrder(value);
845 }
846 }
847 }
848 }
849}
850
851void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
852 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
853 DCHECK(writer != nullptr);
854 writer->WalkFieldsInOrder(obj);
855}
856
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800857void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
858 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
859 DCHECK(writer != nullptr);
860 writer->UnbinObjectsIntoOffset(obj);
861}
862
863void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
864 CHECK(obj != nullptr);
865
866 // We know the bin slot, and the total bin sizes for all objects by now,
867 // so calculate the object's final image offset.
868
869 DCHECK(IsImageBinSlotAssigned(obj));
870 BinSlot bin_slot = GetImageBinSlot(obj);
871 // Change the lockword from a bin slot into an offset
872 AssignImageOffset(obj, bin_slot);
873}
874
Vladimir Markof4da6752014-08-01 19:04:18 +0100875void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700876 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700877 StackHandleScope<1> hs(self);
878 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700879
880 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700881 DCHECK_EQ(0U, image_end_);
882
Mathieu Chartier31e89252013-08-28 11:29:12 -0700883 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700884 // know where image_roots is going to end up
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800885 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700886
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800887 // TODO: Image spaces only?
888 DCHECK_LT(image_end_, image_->Size());
889 image_objects_offset_begin_ = image_end_;
890 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
891 heap->VisitObjects(WalkFieldsCallback, this);
892 // Transform each object's bin slot into an offset which will be used to do the final copy.
893 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
894 DCHECK(saved_hashes_map_.empty()); // All binslot hashes should've been put into vector by now.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700895
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800896 DCHECK_GT(image_end_, GetBinSizeSum());
897
Vladimir Markof4da6752014-08-01 19:04:18 +0100898 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
899
900 // Note that image_end_ is left at end of used space
901}
902
903void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
904 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -0700905 const uint8_t* oat_file_begin = GetOatFileBegin();
906 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800907
Brian Carlstrom7940e442013-07-12 13:46:57 -0700908 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -0700909 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700910
Mathieu Chartier31e89252013-08-28 11:29:12 -0700911 // Return to write header at start of image with future location of image_roots. At this point,
912 // image_end_ is the size of the image (excluding bitmaps).
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700913 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800914 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
915 heap_bytes_per_bitmap_byte;
Vladimir Markof4da6752014-08-01 19:04:18 +0100916 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
917 static_cast<uint32_t>(image_end_),
918 RoundUp(image_end_, kPageSize),
919 RoundUp(bitmap_bytes, kPageSize),
920 image_roots_address_,
921 oat_file_->GetOatHeader().GetChecksum(),
922 PointerToLowMemUInt32(oat_file_begin),
923 PointerToLowMemUInt32(oat_data_begin_),
924 PointerToLowMemUInt32(oat_data_end),
Igor Murashkin46774762014-10-22 11:37:02 -0700925 PointerToLowMemUInt32(oat_file_end),
926 compile_pic_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700927}
928
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800929void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700930 gc::Heap* heap = Runtime::Current()->GetHeap();
931 // TODO: heap validation can't handle this fix up pass
932 heap->DisableObjectValidation();
933 // TODO: Image spaces only?
Mathieu Chartier590fee92013-09-13 13:46:47 -0700934 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
935 // Fix up the object previously had hash codes.
936 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800937 Object* obj = hash_pair.first;
938 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0U);
939 obj->SetLockWord(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700940 }
941 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700942}
943
Mathieu Chartier590fee92013-09-13 13:46:47 -0700944void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700945 DCHECK(obj != nullptr);
946 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700947 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700948 // see GetLocalAddress for similar computation
949 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers13735952014-10-08 12:43:28 -0700950 uint8_t* dst = image_writer->image_->Begin() + offset;
951 const uint8_t* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800952 size_t n;
953 if (obj->IsArtMethod()) {
954 // Size without pointer fields since we don't want to overrun the buffer if target art method
955 // is 32 bits but source is 64 bits.
Jeff Haoc7d11882015-02-03 15:08:39 -0800956 n = mirror::ArtMethod::SizeWithoutPointerFields(image_writer->target_ptr_size_);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800957 } else {
958 n = obj->SizeOf();
959 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700960 DCHECK_LT(offset + n, image_writer->image_->Size());
961 memcpy(dst, src, n);
962 Object* copy = reinterpret_cast<Object*>(dst);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700963 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
964 // word.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800965 copy->SetLockWord(LockWord::Default(), false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700966 image_writer->FixupObject(obj, copy);
967}
968
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800969// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700970class FixupVisitor {
971 public:
972 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
973 }
974
975 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
976 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -0700977 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700978 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
979 // image.
980 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700981 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700982 }
983
984 // java.lang.ref.Reference visitor.
985 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
986 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
987 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
988 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700989 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700990 }
991
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700992 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700993 ImageWriter* const image_writer_;
994 mirror::Object* const copy_;
995};
996
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700997class FixupClassVisitor FINAL : public FixupVisitor {
998 public:
999 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1000 }
1001
1002 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
1003 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1004 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001005 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001006
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001007 // TODO: Remove dead code
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001008 if (offset.Uint32Value() < mirror::Class::EmbeddedVTableOffset().Uint32Value()) {
1009 return;
1010 }
1011 }
1012
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001013 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1014 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001015 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1016 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1017 LOG(FATAL) << "Reference not expected here.";
1018 }
1019};
1020
Ian Rogersef7d42f2014-01-06 12:55:46 -08001021void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001022 DCHECK(orig != nullptr);
1023 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001024 if (kUseBakerOrBrooksReadBarrier) {
1025 orig->AssertReadBarrierPointer();
1026 if (kUseBrooksReadBarrier) {
1027 // Note the address 'copy' isn't the same as the image address of 'orig'.
1028 copy->SetReadBarrierPointer(GetImageAddress(orig));
1029 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1030 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001031 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001032 if (orig->IsClass() && orig->AsClass()->ShouldHaveEmbeddedImtAndVTable()) {
1033 FixupClassVisitor visitor(this, copy);
1034 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
1035 } else {
1036 FixupVisitor visitor(this, copy);
1037 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
1038 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001039 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001040 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001041 }
1042}
1043
Ian Rogers13735952014-10-08 12:43:28 -07001044const uint8_t* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001045 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001046 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001047
1048 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1049 // trampoline.
1050
1051 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001052 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1053 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
1054 const uint8_t* quick_code = GetOatAddress(quick_oat_code_offset);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001055 *quick_is_interpreted = false;
1056 if (quick_code != nullptr &&
1057 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
1058 // We have code for a non-static or initialized method, just use the code.
1059 } else if (quick_code == nullptr && method->IsNative() &&
1060 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1061 // Non-static or initialized native method missing compiled code, use generic JNI version.
1062 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
1063 } else if (quick_code == nullptr && !method->IsNative()) {
1064 // We don't have code at all for a non-native method, use the interpreter.
1065 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
1066 *quick_is_interpreted = true;
1067 } else {
1068 CHECK(!method->GetDeclaringClass()->IsInitialized());
1069 // We have code for a static method, but need to go through the resolution stub for class
1070 // initialization.
1071 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
1072 }
1073 return quick_code;
1074}
1075
Ian Rogers13735952014-10-08 12:43:28 -07001076const uint8_t* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001077 // Calculate the quick entry point following the same logic as FixupMethod() below.
1078 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001079 Runtime* runtime = Runtime::Current();
1080 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001081 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001082 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
1083 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001084 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
1085 } else {
1086 // We assume all methods have code. If they don't currently then we set them to the use the
1087 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1088 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1089 if (UNLIKELY(method->IsAbstract())) {
1090 return GetOatAddress(quick_to_interpreter_bridge_offset_);
1091 } else {
1092 bool quick_is_interpreted;
1093 return GetQuickCode(method, &quick_is_interpreted);
1094 }
1095 }
1096}
1097
Ian Rogersef7d42f2014-01-06 12:55:46 -08001098void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -07001099 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1100 // oat_begin_
Mathieu Chartier2d721012014-11-10 11:08:06 -08001101 // For 64 bit targets we need to repack the current runtime pointer sized fields to the right
1102 // locations.
1103 // Copy all of the fields from the runtime methods to the target methods first since we did a
1104 // bytewise copy earlier.
Jeff Haoc7d11882015-02-03 15:08:39 -08001105 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1106 orig->GetEntryPointFromInterpreterPtrSize(target_ptr_size_), target_ptr_size_);
1107 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(
1108 orig->GetEntryPointFromJniPtrSize(target_ptr_size_), target_ptr_size_);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001109 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
Jeff Haoc7d11882015-02-03 15:08:39 -08001110 orig->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001111
Ian Rogers848871b2013-08-05 10:56:33 -07001112 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001113 Runtime* runtime = Runtime::Current();
1114 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001115 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1116 GetOatAddress(quick_resolution_trampoline_offset_), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001117 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1118 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001119 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1120 GetOatAddress(quick_imt_conflict_trampoline_offset_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001121 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001122 // We assume all methods have code. If they don't currently then we set them to the use the
1123 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1124 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1125 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001126 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1127 GetOatAddress(quick_to_interpreter_bridge_offset_), target_ptr_size_);
1128 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1129 reinterpret_cast<EntryPointFromInterpreter*>(const_cast<uint8_t*>(
1130 GetOatAddress(interpreter_to_interpreter_bridge_offset_))), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001131 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001132 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -07001133 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001134 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001135
Sebastien Hertze1d07812014-05-21 15:44:09 +02001136 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001137 if (orig->IsNative()) {
1138 // The native method's pointer is set to a stub to lookup via dlsym.
1139 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier2d721012014-11-10 11:08:06 -08001140 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_),
1141 target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001142 }
Sebastien Hertze1d07812014-05-21 15:44:09 +02001143
1144 // Interpreter entrypoint:
1145 // Set the interpreter entrypoint depending on whether there is compiled code or not.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001146 uint32_t interpreter_code = (quick_is_interpreted)
Sebastien Hertze1d07812014-05-21 15:44:09 +02001147 ? interpreter_to_interpreter_bridge_offset_
1148 : interpreter_to_compiled_code_bridge_offset_;
Mathieu Chartier2d721012014-11-10 11:08:06 -08001149 EntryPointFromInterpreter* interpreter_entrypoint =
Sebastien Hertze1d07812014-05-21 15:44:09 +02001150 reinterpret_cast<EntryPointFromInterpreter*>(
Mathieu Chartier2d721012014-11-10 11:08:06 -08001151 const_cast<uint8_t*>(GetOatAddress(interpreter_code)));
1152 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1153 interpreter_entrypoint, target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001154 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001155 }
1156}
1157
Alex Lighta59dd802014-07-02 16:28:08 -07001158static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001159 uint64_t data_sec_offset;
1160 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1161 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001162 return nullptr;
1163 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001164 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001165}
1166
Vladimir Markof4da6752014-08-01 19:04:18 +01001167void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001168 std::string error_msg;
1169 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
1170 MAP_SHARED, &error_msg));
1171 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001172 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001173 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001174 }
Alex Lighta59dd802014-07-02 16:28:08 -07001175 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1176 CHECK(oat_header != nullptr);
1177 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001178
Brian Carlstrom7940e442013-07-12 13:46:57 -07001179 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001180 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001181}
1182
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001183size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1184 DCHECK_LE(up_to, kBinSize);
1185 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1186}
1187
1188ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1189 // These values may need to get updated if more bins are added to the enum Bin
1190 static_assert(kBinBits == 3, "wrong number of bin bits");
1191 static_assert(kBinShift == 29, "wrong number of shift");
1192 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1193
1194 DCHECK_LT(GetBin(), kBinSize);
1195 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1196}
1197
1198ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1199 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1200 DCHECK_EQ(index, GetIndex());
1201}
1202
1203ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1204 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1205}
1206
1207uint32_t ImageWriter::BinSlot::GetIndex() const {
1208 return lockword_ & ~kBinMask;
1209}
1210
Andreas Gampe245ee002014-12-04 21:25:04 -08001211void ImageWriter::FreeStringDataArray() {
1212 if (string_data_array_ != nullptr) {
1213 gc::space::LargeObjectSpace* los = Runtime::Current()->GetHeap()->GetLargeObjectsSpace();
1214 if (los != nullptr) {
1215 los->Free(Thread::Current(), reinterpret_cast<mirror::Object*>(string_data_array_));
1216 }
1217 }
1218}
1219
Brian Carlstrom7940e442013-07-12 13:46:57 -07001220} // namespace art