blob: 6b4eff1df5a59547080a7b441bbef5c2bf068b07 [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;
Richard Uhlere5fed032015-03-18 08:21:11 -0700136 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, nullptr, &error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700137 if (oat_file_ == nullptr) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800138 PLOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700139 << ": " << error_msg;
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700140 return false;
141 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700142 CHECK_EQ(class_linker->RegisterOatFile(oat_file_), oat_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700143
Ian Rogers848871b2013-08-05 10:56:33 -0700144 interpreter_to_interpreter_bridge_offset_ =
145 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
146 interpreter_to_compiled_code_bridge_offset_ =
147 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
148
149 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
150
Andreas Gampe2da88232014-02-27 12:26:20 -0800151 quick_generic_jni_trampoline_offset_ =
152 oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
Jeff Hao88474b42013-10-23 16:24:40 -0700153 quick_imt_conflict_trampoline_offset_ =
154 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700155 quick_resolution_trampoline_offset_ =
156 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
157 quick_to_interpreter_bridge_offset_ =
158 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700159
Brian Carlstrom7940e442013-07-12 13:46:57 -0700160 size_t oat_loaded_size = 0;
161 size_t oat_data_offset = 0;
162 ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
Alex Light53cb16b2014-06-12 11:26:29 -0700163
Vladimir Markof4da6752014-08-01 19:04:18 +0100164 Thread::Current()->TransitionFromSuspendedToRunnable();
165 CreateHeader(oat_loaded_size, oat_data_offset);
166 CopyAndFixupObjects();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700167 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
168
Vladimir Markof4da6752014-08-01 19:04:18 +0100169 SetOatChecksumFromElfFile(oat_file.get());
170
Andreas Gampe4303ba92014-11-06 01:00:46 -0800171 if (oat_file->FlushCloseOrErase() != 0) {
172 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename << " for " << oat_location;
173 return false;
174 }
175
Ian Rogers700a4022014-05-19 16:49:03 -0700176 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700177 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 if (image_file.get() == NULL) {
179 LOG(ERROR) << "Failed to open image file " << image_filename;
180 return false;
181 }
182 if (fchmod(image_file->Fd(), 0644) != 0) {
183 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800184 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700185 return EXIT_FAILURE;
186 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700187
188 // Write out the image.
189 CHECK_EQ(image_end_, image_header->GetImageSize());
190 if (!image_file->WriteFully(image_->Begin(), image_end_)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700191 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800192 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700193 return false;
194 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700195
196 // Write out the image bitmap at the page aligned start of the image end.
197 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
198 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
199 image_header->GetImageBitmapSize(),
200 image_header->GetImageBitmapOffset())) {
201 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800202 image_file->Erase();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700203 return false;
204 }
205
Andreas Gampe4303ba92014-11-06 01:00:46 -0800206 if (image_file->FlushCloseOrErase() != 0) {
207 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
208 return false;
209 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700210 return true;
211}
212
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800213void ImageWriter::SetImageOffset(mirror::Object* object,
214 ImageWriter::BinSlot bin_slot,
215 size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700216 DCHECK(object != nullptr);
217 DCHECK_NE(offset, 0U);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700218 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
219 DCHECK_ALIGNED(obj, kObjectAlignment);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800220
221 image_bitmap_->Set(obj); // Mark the obj as mutated, since we will end up changing it.
222 {
223 // Remember the object-inside-of-the-image's hash code so we can restore it after the copy.
224 auto hash_it = saved_hashes_map_.find(bin_slot);
225 if (hash_it != saved_hashes_map_.end()) {
226 std::pair<BinSlot, uint32_t> slot_hash = *hash_it;
227 saved_hashes_.push_back(std::make_pair(obj, slot_hash.second));
228 saved_hashes_map_.erase(hash_it);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700229 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700230 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800231 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700232 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700233 DCHECK(IsImageOffsetAssigned(object));
234}
235
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800236void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700237 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800238 DCHECK_NE(image_objects_offset_begin_, 0u);
239
240 size_t previous_bin_sizes = GetBinSizeSum(bin_slot.GetBin()); // sum sizes in [0..bin#)
241 size_t new_offset = image_objects_offset_begin_ + previous_bin_sizes + bin_slot.GetIndex();
242 DCHECK_ALIGNED(new_offset, kObjectAlignment);
243
244 SetImageOffset(object, bin_slot, new_offset);
245 DCHECK_LT(new_offset, image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700246}
247
Ian Rogersef7d42f2014-01-06 12:55:46 -0800248bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800249 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700250 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700251 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700252}
253
Ian Rogersef7d42f2014-01-06 12:55:46 -0800254size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700255 DCHECK(object != nullptr);
256 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700257 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700258 size_t offset = lock_word.ForwardingAddress();
259 DCHECK_LT(offset, image_end_);
260 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700261}
262
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800263void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
264 DCHECK(object != nullptr);
265 DCHECK(!IsImageOffsetAssigned(object));
266 DCHECK(!IsImageBinSlotAssigned(object));
267
268 // Before we stomp over the lock word, save the hash code for later.
269 Monitor::Deflate(Thread::Current(), object);;
270 LockWord lw(object->GetLockWord(false));
271 switch (lw.GetState()) {
272 case LockWord::kFatLocked: {
273 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
274 break;
275 }
276 case LockWord::kThinLocked: {
277 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
278 break;
279 }
280 case LockWord::kUnlocked:
281 // No hash, don't need to save it.
282 break;
283 case LockWord::kHashCode:
284 saved_hashes_map_[bin_slot] = lw.GetHashCode();
285 break;
286 default:
287 LOG(FATAL) << "Unreachable.";
288 UNREACHABLE();
289 }
290 object->SetLockWord(LockWord::FromForwardingAddress(static_cast<uint32_t>(bin_slot)),
291 false);
292 DCHECK(IsImageBinSlotAssigned(object));
293}
294
295void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
296 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800297 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800298
299 // The magic happens here. We segregate objects into different bins based
300 // on how likely they are to get dirty at runtime.
301 //
302 // Likely-to-dirty objects get packed together into the same bin so that
303 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
304 // maximized.
305 //
306 // This means more pages will stay either clean or shared dirty (with zygote) and
307 // the app will use less of its own (private) memory.
308 Bin bin = kBinRegular;
309
310 if (kBinObjects) {
311 //
312 // Changing the bin of an object is purely a memory-use tuning.
313 // It has no change on runtime correctness.
314 //
315 // Memory analysis has determined that the following types of objects get dirtied
316 // the most:
317 //
318 // * Class'es which are verified [their clinit runs only at runtime]
319 // - classes in general [because their static fields get overwritten]
320 // - initialized classes with all-final statics are unlikely to be ever dirty,
321 // so bin them separately
322 // * Art Methods that are:
323 // - native [their native entry point is not looked up until runtime]
324 // - have declaring classes that aren't initialized
325 // [their interpreter/quick entry points are trampolines until the class
326 // becomes initialized]
327 //
328 // We also assume the following objects get dirtied either never or extremely rarely:
329 // * Strings (they are immutable)
330 // * Art methods that aren't native and have initialized declared classes
331 //
332 // We assume that "regular" bin objects are highly unlikely to become dirtied,
333 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
334 //
335 if (object->IsClass()) {
336 bin = kBinClassVerified;
337 mirror::Class* klass = object->AsClass();
338
339 if (klass->GetStatus() == Class::kStatusInitialized) {
340 bin = kBinClassInitialized;
341
342 // If the class's static fields are all final, put it into a separate bin
343 // since it's very likely it will stay clean.
344 uint32_t num_static_fields = klass->NumStaticFields();
345 if (num_static_fields == 0) {
346 bin = kBinClassInitializedFinalStatics;
347 } else {
348 // Maybe all the statics are final?
349 bool all_final = true;
350 for (uint32_t i = 0; i < num_static_fields; ++i) {
351 ArtField* field = klass->GetStaticField(i);
352 if (!field->IsFinal()) {
353 all_final = false;
354 break;
355 }
356 }
357
358 if (all_final) {
359 bin = kBinClassInitializedFinalStatics;
360 }
361 }
362 }
363 } else if (object->IsArtMethod<kVerifyNone>()) {
364 mirror::ArtMethod* art_method = down_cast<ArtMethod*>(object);
365 if (art_method->IsNative()) {
366 bin = kBinArtMethodNative;
367 } else {
368 mirror::Class* declaring_class = art_method->GetDeclaringClass();
369 if (declaring_class->GetStatus() != Class::kStatusInitialized) {
370 bin = kBinArtMethodNotInitialized;
371 } else {
372 // This is highly unlikely to dirty since there's no entry points to mutate.
373 bin = kBinArtMethodsManagedInitialized;
374 }
375 }
376 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
377 bin = kBinString; // Strings are almost always immutable (except for object header).
378 } // else bin = kBinRegular
379 }
380
381 size_t current_offset = bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
382 // Move the current bin size up to accomodate the object we just assigned a bin slot.
383 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
384 bin_slot_sizes_[bin] += offset_delta;
385
386 BinSlot new_bin_slot(bin, current_offset);
387 SetImageBinSlot(object, new_bin_slot);
388
389 ++bin_slot_count_[bin];
390
391 DCHECK_LT(GetBinSizeSum(), image_->Size());
392
393 // Grow the image closer to the end by the object we just assigned.
394 image_end_ += offset_delta;
395 DCHECK_LT(image_end_, image_->Size());
396}
397
398bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
399 DCHECK(object != nullptr);
400
401 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
402 // If it's in some other state, then we haven't yet assigned an image bin slot.
403 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
404 return false;
405 } else if (kIsDebugBuild) {
406 LockWord lock_word = object->GetLockWord(false);
407 size_t offset = lock_word.ForwardingAddress();
408 BinSlot bin_slot(offset);
409 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()])
410 << "bin slot offset should not exceed the size of that bin";
411 }
412 return true;
413}
414
415ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
416 DCHECK(object != nullptr);
417 DCHECK(IsImageBinSlotAssigned(object));
418
419 LockWord lock_word = object->GetLockWord(false);
420 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
421 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
422
423 BinSlot bin_slot(static_cast<uint32_t>(offset));
424 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()]);
425
426 return bin_slot;
427}
428
Brian Carlstrom7940e442013-07-12 13:46:57 -0700429bool ImageWriter::AllocMemory() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700430 size_t length = RoundUp(Runtime::Current()->GetHeap()->GetTotalMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700431 std::string error_msg;
Vladimir Marko5c42c292015-02-25 12:02:49 +0000432 image_.reset(MemMap::MapAnonymous("image writer image", nullptr, length, PROT_READ | PROT_WRITE,
433 false, false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700434 if (UNLIKELY(image_.get() == nullptr)) {
435 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700436 return false;
437 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700438
439 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700440 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
441 length));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700442 if (image_bitmap_.get() == nullptr) {
443 LOG(ERROR) << "Failed to allocate memory for image bitmap";
444 return false;
445 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700446 return true;
447}
448
449void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700450 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700451 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
452}
453
454bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700455 Thread* self = Thread::Current();
456 StackHandleScope<1> hs(self);
457 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700458 return true;
459}
460
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800461// Count the number of strings in the heap and put the result in arg as a size_t pointer.
462static void CountStringsCallback(Object* obj, void* arg)
463 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
464 if (obj->GetClass()->IsStringClass()) {
465 ++*reinterpret_cast<size_t*>(arg);
466 }
467}
468
469// Collect all the java.lang.String in the heap and put them in the output strings_ array.
470class StringCollector {
471 public:
472 StringCollector(Handle<mirror::ObjectArray<mirror::String>> strings, size_t index)
473 : strings_(strings), index_(index) {
474 }
475 static void Callback(Object* obj, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
476 auto* collector = reinterpret_cast<StringCollector*>(arg);
477 if (obj->GetClass()->IsStringClass()) {
478 collector->strings_->SetWithoutChecks<false>(collector->index_++, obj->AsString());
479 }
480 }
481 size_t GetIndex() const {
482 return index_;
483 }
484
485 private:
486 Handle<mirror::ObjectArray<mirror::String>> strings_;
487 size_t index_;
488};
489
490// Compare strings based on length, used for sorting strings by length / reverse length.
Vladimir Markofaeda182014-12-04 14:52:25 +0000491class LexicographicalStringComparator {
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800492 public:
Vladimir Markofaeda182014-12-04 14:52:25 +0000493 bool operator()(const mirror::HeapReference<mirror::String>& lhs,
494 const mirror::HeapReference<mirror::String>& rhs) const
495 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
496 mirror::String* lhs_s = lhs.AsMirrorPtr();
497 mirror::String* rhs_s = rhs.AsMirrorPtr();
498 uint16_t* lhs_begin = lhs_s->GetCharArray()->GetData() + lhs_s->GetOffset();
499 uint16_t* rhs_begin = rhs_s->GetCharArray()->GetData() + rhs_s->GetOffset();
500 return std::lexicographical_compare(lhs_begin, lhs_begin + lhs_s->GetLength(),
501 rhs_begin, rhs_begin + rhs_s->GetLength());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800502 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800503};
504
Vladimir Markofaeda182014-12-04 14:52:25 +0000505static bool IsPrefix(mirror::String* pref, mirror::String* full)
506 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
507 if (pref->GetLength() > full->GetLength()) {
508 return false;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800509 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000510 uint16_t* pref_begin = pref->GetCharArray()->GetData() + pref->GetOffset();
511 uint16_t* full_begin = full->GetCharArray()->GetData() + full->GetOffset();
512 return std::equal(pref_begin, pref_begin + pref->GetLength(), full_begin);
513}
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800514
515void ImageWriter::ProcessStrings() {
516 size_t total_strings = 0;
517 gc::Heap* heap = Runtime::Current()->GetHeap();
518 ClassLinker* cl = Runtime::Current()->GetClassLinker();
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800519 // Count the strings.
520 heap->VisitObjects(CountStringsCallback, &total_strings);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800521 Thread* self = Thread::Current();
522 StackHandleScope<1> hs(self);
523 auto strings = hs.NewHandle(cl->AllocStringArray(self, total_strings));
524 StringCollector string_collector(strings, 0U);
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800525 // Read strings into the array.
526 heap->VisitObjects(StringCollector::Callback, &string_collector);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800527 // Some strings could have gotten freed if AllocStringArray caused a GC.
528 CHECK_LE(string_collector.GetIndex(), total_strings);
529 total_strings = string_collector.GetIndex();
Vladimir Markofaeda182014-12-04 14:52:25 +0000530 auto* strings_begin = reinterpret_cast<mirror::HeapReference<mirror::String>*>(
531 strings->GetRawData(sizeof(mirror::HeapReference<mirror::String>), 0));
532 std::sort(strings_begin, strings_begin + total_strings, LexicographicalStringComparator());
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800533 // Characters of strings which are non equal prefix of another string (not the same string).
534 // We don't count the savings from equal strings since these would get interned later anyways.
535 size_t prefix_saved_chars = 0;
Vladimir Markofaeda182014-12-04 14:52:25 +0000536 // Count characters needed for the strings.
537 size_t num_chars = 0u;
538 mirror::String* prev_s = nullptr;
539 for (size_t idx = 0; idx != total_strings; ++idx) {
540 mirror::String* s = strings->GetWithoutChecks(idx);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800541 size_t length = s->GetLength();
Vladimir Markofaeda182014-12-04 14:52:25 +0000542 num_chars += length;
543 if (prev_s != nullptr && IsPrefix(prev_s, s)) {
544 size_t prev_length = prev_s->GetLength();
545 num_chars -= prev_length;
546 if (prev_length != length) {
547 prefix_saved_chars += prev_length;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800548 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800549 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000550 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800551 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000552 // Create character array, copy characters and point the strings there.
553 mirror::CharArray* array = mirror::CharArray::Alloc(self, num_chars);
Andreas Gampe245ee002014-12-04 21:25:04 -0800554 string_data_array_ = array;
Vladimir Markofaeda182014-12-04 14:52:25 +0000555 uint16_t* array_data = array->GetData();
556 size_t pos = 0u;
557 prev_s = nullptr;
558 for (size_t idx = 0; idx != total_strings; ++idx) {
559 mirror::String* s = strings->GetWithoutChecks(idx);
560 uint16_t* s_data = s->GetCharArray()->GetData() + s->GetOffset();
561 int32_t s_length = s->GetLength();
562 int32_t prefix_length = 0u;
563 if (idx != 0u && IsPrefix(prev_s, s)) {
564 prefix_length = prev_s->GetLength();
565 }
566 memcpy(array_data + pos, s_data + prefix_length, (s_length - prefix_length) * sizeof(*s_data));
567 s->SetOffset(pos - prefix_length);
568 s->SetArray(array);
569 pos += s_length - prefix_length;
570 prev_s = s;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800571 }
Vladimir Markofaeda182014-12-04 14:52:25 +0000572 CHECK_EQ(pos, num_chars);
573
Andreas Gampedc843012015-01-20 16:17:19 -0800574 if (kIsDebugBuild || VLOG_IS_ON(compiler)) {
575 LOG(INFO) << "Total # image strings=" << total_strings << " combined length="
576 << num_chars << " prefix saved chars=" << prefix_saved_chars;
577 }
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800578 ComputeEagerResolvedStrings();
579}
580
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700581void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700582 if (!obj->GetClass()->IsStringClass()) {
583 return;
584 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700585 mirror::String* string = obj->AsString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700586 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
Vladimir Markoa48aef42014-12-03 17:53:53 +0000587 size_t utf16_length = static_cast<size_t>(string->GetLength());
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700588 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
589 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
590 size_t dex_cache_count = class_linker->GetDexCacheCount();
591 for (size_t i = 0; i < dex_cache_count; ++i) {
592 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700593 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800594 const DexFile::StringId* string_id;
Vladimir Markoa48aef42014-12-03 17:53:53 +0000595 if (UNLIKELY(utf16_length == 0)) {
Ian Rogers24c534d2013-11-14 00:15:00 -0800596 string_id = dex_file.FindStringId("");
597 } else {
Vladimir Markoa48aef42014-12-03 17:53:53 +0000598 string_id = dex_file.FindStringId(utf16_string, utf16_length);
Ian Rogers24c534d2013-11-14 00:15:00 -0800599 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700600 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700601 // This string occurs in this dex file, assign the dex cache entry.
602 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
603 if (dex_cache->GetResolvedString(string_idx) == NULL) {
604 dex_cache->SetResolvedString(string_idx, string);
605 }
606 }
607 }
608}
609
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800610void ImageWriter::ComputeEagerResolvedStrings() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700611 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700612}
613
Ian Rogersef7d42f2014-01-06 12:55:46 -0800614bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700615 std::string temp;
616 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700617}
618
619struct NonImageClasses {
620 ImageWriter* image_writer;
621 std::set<std::string>* non_image_classes;
622};
623
624void ImageWriter::PruneNonImageClasses() {
625 if (compiler_driver_.GetImageClasses() == NULL) {
626 return;
627 }
628 Runtime* runtime = Runtime::Current();
629 ClassLinker* class_linker = runtime->GetClassLinker();
630
631 // Make a list of classes we would like to prune.
632 std::set<std::string> non_image_classes;
633 NonImageClasses context;
634 context.image_writer = this;
635 context.non_image_classes = &non_image_classes;
636 class_linker->VisitClasses(NonImageClassesVisitor, &context);
637
638 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700639 for (const std::string& it : non_image_classes) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800640 bool result = class_linker->RemoveClass(it.c_str(), NULL);
641 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700642 }
643
644 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700645 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700646 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
647 size_t dex_cache_count = class_linker->GetDexCacheCount();
648 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
649 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700650 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
651 Class* klass = dex_cache->GetResolvedType(i);
652 if (klass != NULL && !IsImageClass(klass)) {
653 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700654 }
655 }
656 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700657 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700658 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
659 dex_cache->SetResolvedMethod(i, resolution_method);
660 }
661 }
662 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700663 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700664 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
665 dex_cache->SetResolvedField(i, NULL);
666 }
667 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700668 // Clean the dex field. It might have been populated during the initialization phase, but
669 // contains data only valid during a real run.
670 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700671 }
672}
673
674bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
675 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
676 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700677 std::string temp;
678 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700679 }
680 return true;
681}
682
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800683void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700684 if (compiler_driver_.GetImageClasses() != nullptr) {
685 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700686 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700687 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700688}
689
690void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
691 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700692 if (obj->IsClass()) {
693 Class* klass = obj->AsClass();
694 if (!image_writer->IsImageClass(klass)) {
695 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700696 std::string temp;
697 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700698 << " " << PrettyDescriptor(klass);
699 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700700 }
701}
702
703void ImageWriter::DumpImageClasses() {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700704 const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700705 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700706 for (const std::string& image_class : *image_classes) {
707 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700708 }
709}
710
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800711void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700712 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700713 // if it is a string, we want to intern it if its not interned.
714 if (obj->GetClass()->IsStringClass()) {
715 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800716 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700717 DCHECK_EQ(obj, obj->AsString()->Intern());
718 return;
719 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700720 mirror::String* const interned = obj->AsString()->Intern();
721 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800722 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700723 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800724 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700725 }
726 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800727 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700728 return;
729 }
730 // else (obj == interned), nothing to do but fall through to the normal case
731 }
732
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800733 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700734}
735
736ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
737 Runtime* runtime = Runtime::Current();
738 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700739 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700740 StackHandleScope<3> hs(self);
741 Handle<Class> object_array_class(hs.NewHandle(
742 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700743
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700744 // build an Object[] of all the DexCaches used in the source_space_.
745 // Since we can't hold the dex lock when allocating the dex_caches
746 // ObjectArray, we lock the dex lock twice, first to get the number
747 // of dex caches first and then lock it again to copy the dex
748 // caches. We check that the number of dex caches does not change.
749 size_t dex_cache_count;
750 {
751 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
752 dex_cache_count = class_linker->GetDexCacheCount();
753 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700754 Handle<ObjectArray<Object>> dex_caches(
755 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700756 dex_cache_count)));
757 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
758 {
759 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
760 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
761 << "The number of dex caches changed.";
762 for (size_t i = 0; i < dex_cache_count; ++i) {
763 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
764 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700765 }
766
767 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700768 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700769 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100770 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
771 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700772 image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
773 runtime->GetImtUnimplementedMethod());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100774 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
775 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
776 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
777 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
778 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
779 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
780 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700781 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100782 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700783 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
784 CHECK(image_roots->Get(i) != NULL);
785 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700786 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700787}
788
Mathieu Chartier590fee92013-09-13 13:46:47 -0700789// Walk instance fields of the given Class. Separate function to allow recursion on the super
790// class.
791void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
792 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700793 StackHandleScope<1> hs(Thread::Current());
794 Handle<mirror::Class> h_class(hs.NewHandle(klass));
795 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700796 if (super != nullptr) {
797 WalkInstanceFields(obj, super);
798 }
799 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700800 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000801 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700802 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700803 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700804 if (value != nullptr) {
805 WalkFieldsInOrder(value);
806 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000807 field_offset = MemberOffset(field_offset.Uint32Value() +
808 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700809 }
810}
811
812// For an unvisited object, visit it then all its children found via fields.
813void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800814 // Use our own visitor routine (instead of GC visitor) to get better locality between
815 // an object and its fields
816 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700817 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700818 StackHandleScope<2> hs(Thread::Current());
819 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
820 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700821 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800822 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700823 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700824 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700825 if (h_obj->IsClass()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700826 size_t num_static_fields = klass->NumReferenceStaticFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000827 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700828 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700829 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700830 if (value != nullptr) {
831 WalkFieldsInOrder(value);
832 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000833 field_offset = MemberOffset(field_offset.Uint32Value() +
834 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700835 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700836 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700837 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700838 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700839 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700840 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700841 mirror::Object* value = obj_array->Get(i);
842 if (value != nullptr) {
843 WalkFieldsInOrder(value);
844 }
845 }
846 }
847 }
848}
849
850void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
851 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
852 DCHECK(writer != nullptr);
853 writer->WalkFieldsInOrder(obj);
854}
855
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800856void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
857 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
858 DCHECK(writer != nullptr);
859 writer->UnbinObjectsIntoOffset(obj);
860}
861
862void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
863 CHECK(obj != nullptr);
864
865 // We know the bin slot, and the total bin sizes for all objects by now,
866 // so calculate the object's final image offset.
867
868 DCHECK(IsImageBinSlotAssigned(obj));
869 BinSlot bin_slot = GetImageBinSlot(obj);
870 // Change the lockword from a bin slot into an offset
871 AssignImageOffset(obj, bin_slot);
872}
873
Vladimir Markof4da6752014-08-01 19:04:18 +0100874void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700875 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700876 StackHandleScope<1> hs(self);
877 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700878
879 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700880 DCHECK_EQ(0U, image_end_);
881
Mathieu Chartier31e89252013-08-28 11:29:12 -0700882 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700883 // know where image_roots is going to end up
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800884 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700885
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -0800886 // TODO: Image spaces only?
887 DCHECK_LT(image_end_, image_->Size());
888 image_objects_offset_begin_ = image_end_;
889 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
890 heap->VisitObjects(WalkFieldsCallback, this);
891 // Transform each object's bin slot into an offset which will be used to do the final copy.
892 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
893 DCHECK(saved_hashes_map_.empty()); // All binslot hashes should've been put into vector by now.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700894
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800895 DCHECK_GT(image_end_, GetBinSizeSum());
896
Vladimir Markof4da6752014-08-01 19:04:18 +0100897 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
898
899 // Note that image_end_ is left at end of used space
900}
901
902void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
903 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -0700904 const uint8_t* oat_file_begin = GetOatFileBegin();
905 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800906
Brian Carlstrom7940e442013-07-12 13:46:57 -0700907 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -0700908 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700909
Mathieu Chartier31e89252013-08-28 11:29:12 -0700910 // Return to write header at start of image with future location of image_roots. At this point,
911 // image_end_ is the size of the image (excluding bitmaps).
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700912 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800913 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
914 heap_bytes_per_bitmap_byte;
Vladimir Markof4da6752014-08-01 19:04:18 +0100915 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
916 static_cast<uint32_t>(image_end_),
917 RoundUp(image_end_, kPageSize),
918 RoundUp(bitmap_bytes, kPageSize),
919 image_roots_address_,
920 oat_file_->GetOatHeader().GetChecksum(),
921 PointerToLowMemUInt32(oat_file_begin),
922 PointerToLowMemUInt32(oat_data_begin_),
923 PointerToLowMemUInt32(oat_data_end),
Igor Murashkin46774762014-10-22 11:37:02 -0700924 PointerToLowMemUInt32(oat_file_end),
925 compile_pic_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700926}
927
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800928void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700929 gc::Heap* heap = Runtime::Current()->GetHeap();
930 // TODO: heap validation can't handle this fix up pass
931 heap->DisableObjectValidation();
932 // TODO: Image spaces only?
Mathieu Chartier590fee92013-09-13 13:46:47 -0700933 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
934 // Fix up the object previously had hash codes.
935 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800936 Object* obj = hash_pair.first;
937 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0U);
938 obj->SetLockWord(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700939 }
940 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700941}
942
Mathieu Chartier590fee92013-09-13 13:46:47 -0700943void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700944 DCHECK(obj != nullptr);
945 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700946 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700947 // see GetLocalAddress for similar computation
948 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers13735952014-10-08 12:43:28 -0700949 uint8_t* dst = image_writer->image_->Begin() + offset;
950 const uint8_t* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800951 size_t n;
952 if (obj->IsArtMethod()) {
953 // Size without pointer fields since we don't want to overrun the buffer if target art method
954 // is 32 bits but source is 64 bits.
Jeff Haoc7d11882015-02-03 15:08:39 -0800955 n = mirror::ArtMethod::SizeWithoutPointerFields(image_writer->target_ptr_size_);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800956 } else {
957 n = obj->SizeOf();
958 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700959 DCHECK_LT(offset + n, image_writer->image_->Size());
960 memcpy(dst, src, n);
961 Object* copy = reinterpret_cast<Object*>(dst);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700962 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
963 // word.
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -0800964 copy->SetLockWord(LockWord::Default(), false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700965 image_writer->FixupObject(obj, copy);
966}
967
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800968// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700969class FixupVisitor {
970 public:
971 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
972 }
973
974 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
975 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -0700976 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700977 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
978 // image.
979 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700980 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700981 }
982
983 // java.lang.ref.Reference visitor.
984 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
985 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
986 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
987 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700988 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700989 }
990
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700991 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700992 ImageWriter* const image_writer_;
993 mirror::Object* const copy_;
994};
995
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700996class FixupClassVisitor FINAL : public FixupVisitor {
997 public:
998 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
999 }
1000
1001 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
1002 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1003 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001004 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001005
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001006 // TODO: Remove dead code
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001007 if (offset.Uint32Value() < mirror::Class::EmbeddedVTableOffset().Uint32Value()) {
1008 return;
1009 }
1010 }
1011
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001012 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1013 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001014 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
1015 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
1016 LOG(FATAL) << "Reference not expected here.";
1017 }
1018};
1019
Ian Rogersef7d42f2014-01-06 12:55:46 -08001020void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001021 DCHECK(orig != nullptr);
1022 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001023 if (kUseBakerOrBrooksReadBarrier) {
1024 orig->AssertReadBarrierPointer();
1025 if (kUseBrooksReadBarrier) {
1026 // Note the address 'copy' isn't the same as the image address of 'orig'.
1027 copy->SetReadBarrierPointer(GetImageAddress(orig));
1028 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1029 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001030 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001031 if (orig->IsClass() && orig->AsClass()->ShouldHaveEmbeddedImtAndVTable()) {
1032 FixupClassVisitor visitor(this, copy);
1033 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
1034 } else {
1035 FixupVisitor visitor(this, copy);
1036 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
1037 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001038 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -08001039 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001040 }
1041}
1042
Ian Rogers13735952014-10-08 12:43:28 -07001043const uint8_t* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001044 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001045 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001046
1047 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1048 // trampoline.
1049
1050 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001051 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1052 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
1053 const uint8_t* quick_code = GetOatAddress(quick_oat_code_offset);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001054 *quick_is_interpreted = false;
1055 if (quick_code != nullptr &&
1056 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
1057 // We have code for a non-static or initialized method, just use the code.
1058 } else if (quick_code == nullptr && method->IsNative() &&
1059 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1060 // Non-static or initialized native method missing compiled code, use generic JNI version.
1061 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
1062 } else if (quick_code == nullptr && !method->IsNative()) {
1063 // We don't have code at all for a non-native method, use the interpreter.
1064 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
1065 *quick_is_interpreted = true;
1066 } else {
1067 CHECK(!method->GetDeclaringClass()->IsInitialized());
1068 // We have code for a static method, but need to go through the resolution stub for class
1069 // initialization.
1070 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
1071 }
1072 return quick_code;
1073}
1074
Ian Rogers13735952014-10-08 12:43:28 -07001075const uint8_t* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001076 // Calculate the quick entry point following the same logic as FixupMethod() below.
1077 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001078 Runtime* runtime = Runtime::Current();
1079 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001080 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001081 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
1082 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001083 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
1084 } else {
1085 // We assume all methods have code. If they don't currently then we set them to the use the
1086 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1087 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1088 if (UNLIKELY(method->IsAbstract())) {
1089 return GetOatAddress(quick_to_interpreter_bridge_offset_);
1090 } else {
1091 bool quick_is_interpreted;
1092 return GetQuickCode(method, &quick_is_interpreted);
1093 }
1094 }
1095}
1096
Ian Rogersef7d42f2014-01-06 12:55:46 -08001097void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -07001098 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1099 // oat_begin_
Mathieu Chartier2d721012014-11-10 11:08:06 -08001100 // For 64 bit targets we need to repack the current runtime pointer sized fields to the right
1101 // locations.
1102 // Copy all of the fields from the runtime methods to the target methods first since we did a
1103 // bytewise copy earlier.
Jeff Haoc7d11882015-02-03 15:08:39 -08001104 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1105 orig->GetEntryPointFromInterpreterPtrSize(target_ptr_size_), target_ptr_size_);
1106 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(
1107 orig->GetEntryPointFromJniPtrSize(target_ptr_size_), target_ptr_size_);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001108 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
Jeff Haoc7d11882015-02-03 15:08:39 -08001109 orig->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001110
Ian Rogers848871b2013-08-05 10:56:33 -07001111 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001112 Runtime* runtime = Runtime::Current();
1113 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001114 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->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1119 GetOatAddress(quick_imt_conflict_trampoline_offset_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001120 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001121 // We assume all methods have code. If they don't currently then we set them to the use the
1122 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1123 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1124 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08001125 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1126 GetOatAddress(quick_to_interpreter_bridge_offset_), target_ptr_size_);
1127 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1128 reinterpret_cast<EntryPointFromInterpreter*>(const_cast<uint8_t*>(
1129 GetOatAddress(interpreter_to_interpreter_bridge_offset_))), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001130 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001131 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -07001132 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartier2d721012014-11-10 11:08:06 -08001133 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001134
Sebastien Hertze1d07812014-05-21 15:44:09 +02001135 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001136 if (orig->IsNative()) {
1137 // The native method's pointer is set to a stub to lookup via dlsym.
1138 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier2d721012014-11-10 11:08:06 -08001139 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_),
1140 target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001141 }
Sebastien Hertze1d07812014-05-21 15:44:09 +02001142
1143 // Interpreter entrypoint:
1144 // Set the interpreter entrypoint depending on whether there is compiled code or not.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001145 uint32_t interpreter_code = (quick_is_interpreted)
Sebastien Hertze1d07812014-05-21 15:44:09 +02001146 ? interpreter_to_interpreter_bridge_offset_
1147 : interpreter_to_compiled_code_bridge_offset_;
Mathieu Chartier2d721012014-11-10 11:08:06 -08001148 EntryPointFromInterpreter* interpreter_entrypoint =
Sebastien Hertze1d07812014-05-21 15:44:09 +02001149 reinterpret_cast<EntryPointFromInterpreter*>(
Mathieu Chartier2d721012014-11-10 11:08:06 -08001150 const_cast<uint8_t*>(GetOatAddress(interpreter_code)));
1151 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1152 interpreter_entrypoint, target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001153 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001154 }
1155}
1156
Alex Lighta59dd802014-07-02 16:28:08 -07001157static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001158 uint64_t data_sec_offset;
1159 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1160 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001161 return nullptr;
1162 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001163 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001164}
1165
Vladimir Markof4da6752014-08-01 19:04:18 +01001166void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001167 std::string error_msg;
1168 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
1169 MAP_SHARED, &error_msg));
1170 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001171 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001172 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001173 }
Alex Lighta59dd802014-07-02 16:28:08 -07001174 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1175 CHECK(oat_header != nullptr);
1176 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001177
Brian Carlstrom7940e442013-07-12 13:46:57 -07001178 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001179 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001180}
1181
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001182size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1183 DCHECK_LE(up_to, kBinSize);
1184 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1185}
1186
1187ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1188 // These values may need to get updated if more bins are added to the enum Bin
1189 static_assert(kBinBits == 3, "wrong number of bin bits");
1190 static_assert(kBinShift == 29, "wrong number of shift");
1191 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1192
1193 DCHECK_LT(GetBin(), kBinSize);
1194 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1195}
1196
1197ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1198 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1199 DCHECK_EQ(index, GetIndex());
1200}
1201
1202ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1203 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1204}
1205
1206uint32_t ImageWriter::BinSlot::GetIndex() const {
1207 return lockword_ & ~kBinMask;
1208}
1209
Andreas Gampe245ee002014-12-04 21:25:04 -08001210void ImageWriter::FreeStringDataArray() {
1211 if (string_data_array_ != nullptr) {
1212 gc::space::LargeObjectSpace* los = Runtime::Current()->GetHeap()->GetLargeObjectsSpace();
1213 if (los != nullptr) {
1214 los->Free(Thread::Current(), reinterpret_cast<mirror::Object*>(string_data_array_));
1215 }
1216 }
1217}
1218
Brian Carlstrom7940e442013-07-12 13:46:57 -07001219} // namespace art