blob: 5cb81ffd62417a189724caa1acee6711fcb99f4c [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"
Alex Lighta59dd802014-07-02 16:28:08 -070032#include "elf_patcher.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070033#include "elf_writer.h"
34#include "gc/accounting/card_table-inl.h"
35#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070036#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070037#include "gc/heap.h"
38#include "gc/space/large_object_space.h"
39#include "gc/space/space-inl.h"
40#include "globals.h"
41#include "image.h"
42#include "intern_table.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070043#include "lock_word.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070044#include "mirror/art_field-inl.h"
45#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "mirror/array-inl.h"
47#include "mirror/class-inl.h"
48#include "mirror/class_loader.h"
49#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "mirror/object-inl.h"
51#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070052#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070053#include "oat.h"
54#include "oat_file.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "runtime.h"
56#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070057#include "handle_scope-inl.h"
Igor Murashkin3f735bd2014-11-14 15:01:59 -080058
59#include <numeric>
Brian Carlstrom7940e442013-07-12 13:46:57 -070060
Brian Carlstromea46f952013-07-30 01:26:50 -070061using ::art::mirror::ArtField;
62using ::art::mirror::ArtMethod;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070063using ::art::mirror::Class;
64using ::art::mirror::DexCache;
65using ::art::mirror::EntryPointFromInterpreter;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070066using ::art::mirror::Object;
67using ::art::mirror::ObjectArray;
68using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070069
70namespace art {
71
Igor Murashkin3f735bd2014-11-14 15:01:59 -080072// Separate objects into multiple bins to optimize dirty memory use.
73static constexpr bool kBinObjects = true;
74
Brian Carlstrom7940e442013-07-12 13:46:57 -070075bool ImageWriter::Write(const std::string& image_filename,
76 uintptr_t image_begin,
77 const std::string& oat_filename,
Igor Murashkin90ca5c02014-10-22 11:37:02 -070078 const std::string& oat_location,
79 bool compile_pic) {
Brian Carlstrom7940e442013-07-12 13:46:57 -070080 CHECK(!image_filename.empty());
81
82 CHECK_NE(image_begin, 0U);
83 image_begin_ = reinterpret_cast<byte*>(image_begin);
Igor Murashkin90ca5c02014-10-22 11:37:02 -070084 compile_pic_ = compile_pic;
Brian Carlstrom7940e442013-07-12 13:46:57 -070085
86 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -070087
Mathieu Chartiere832e642014-11-10 11:08:06 -080088 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Ian Rogers700a4022014-05-19 16:49:03 -070089 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -070090 if (oat_file.get() == NULL) {
91 LOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
92 return false;
93 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -070094 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -070095 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, &error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -070096 if (oat_file_ == nullptr) {
97 LOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
98 << ": " << error_msg;
Brian Carlstromc50d8e12013-07-23 22:35:16 -070099 return false;
100 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700101 CHECK_EQ(class_linker->RegisterOatFile(oat_file_), oat_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700102
Ian Rogers848871b2013-08-05 10:56:33 -0700103 interpreter_to_interpreter_bridge_offset_ =
104 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
105 interpreter_to_compiled_code_bridge_offset_ =
106 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
107
108 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
109
Jeff Hao88474b42013-10-23 16:24:40 -0700110 portable_imt_conflict_trampoline_offset_ =
111 oat_file_->GetOatHeader().GetPortableImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700112 portable_resolution_trampoline_offset_ =
113 oat_file_->GetOatHeader().GetPortableResolutionTrampolineOffset();
114 portable_to_interpreter_bridge_offset_ =
115 oat_file_->GetOatHeader().GetPortableToInterpreterBridgeOffset();
116
Andreas Gampe2da88232014-02-27 12:26:20 -0800117 quick_generic_jni_trampoline_offset_ =
118 oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
Jeff Hao88474b42013-10-23 16:24:40 -0700119 quick_imt_conflict_trampoline_offset_ =
120 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700121 quick_resolution_trampoline_offset_ =
122 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
123 quick_to_interpreter_bridge_offset_ =
124 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700125 {
126 Thread::Current()->TransitionFromSuspendedToRunnable();
127 PruneNonImageClasses(); // Remove junk
128 ComputeLazyFieldsForImageClasses(); // Add useful information
Piotr Jastrzebski3a7cf8e2015-05-07 09:44:22 +0100129 ComputeEagerResolvedStrings();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700130 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
131 }
132 gc::Heap* heap = Runtime::Current()->GetHeap();
133 heap->CollectGarbage(false); // Remove garbage.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700134
135 if (!AllocMemory()) {
136 return false;
137 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700138
139 if (kIsDebugBuild) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700140 ScopedObjectAccess soa(Thread::Current());
141 CheckNonImageClassesRemoved();
142 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700143
Brian Carlstrom7940e442013-07-12 13:46:57 -0700144 Thread::Current()->TransitionFromSuspendedToRunnable();
145 size_t oat_loaded_size = 0;
146 size_t oat_data_offset = 0;
147 ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
148 CalculateNewObjectOffsets(oat_loaded_size, oat_data_offset);
149 CopyAndFixupObjects();
Alex Light53cb16b2014-06-12 11:26:29 -0700150
151 PatchOatCodeAndMethods(oat_file.get());
Andreas Gampe9433ec62014-11-06 01:00:46 -0800152
153 // Before flushing, which might fail, release the mutator lock.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700154 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
155
Andreas Gampe9433ec62014-11-06 01:00:46 -0800156 if (oat_file->FlushCloseOrErase() != 0) {
157 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename << " for " << oat_location;
158 return false;
159 }
160
Ian Rogers700a4022014-05-19 16:49:03 -0700161 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700162 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700163 if (image_file.get() == NULL) {
164 LOG(ERROR) << "Failed to open image file " << image_filename;
165 return false;
166 }
167 if (fchmod(image_file->Fd(), 0644) != 0) {
168 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
Andreas Gampe9433ec62014-11-06 01:00:46 -0800169 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700170 return EXIT_FAILURE;
171 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700172
173 // Write out the image.
174 CHECK_EQ(image_end_, image_header->GetImageSize());
175 if (!image_file->WriteFully(image_->Begin(), image_end_)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700176 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe9433ec62014-11-06 01:00:46 -0800177 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 return false;
179 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700180
181 // Write out the image bitmap at the page aligned start of the image end.
182 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
183 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
184 image_header->GetImageBitmapSize(),
185 image_header->GetImageBitmapOffset())) {
186 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe9433ec62014-11-06 01:00:46 -0800187 image_file->Erase();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700188 return false;
189 }
190
Andreas Gampe9433ec62014-11-06 01:00:46 -0800191 if (image_file->FlushCloseOrErase() != 0) {
192 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
193 return false;
194 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700195 return true;
196}
197
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800198void ImageWriter::SetImageOffset(mirror::Object* object,
199 ImageWriter::BinSlot bin_slot,
200 size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700201 DCHECK(object != nullptr);
202 DCHECK_NE(offset, 0U);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700203 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
204 DCHECK_ALIGNED(obj, kObjectAlignment);
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800205
206 image_bitmap_->Set(obj); // Mark the obj as mutated, since we will end up changing it.
207 {
208 // Remember the object-inside-of-the-image's hash code so we can restore it after the copy.
209 auto hash_it = saved_hashes_map_.find(bin_slot);
210 if (hash_it != saved_hashes_map_.end()) {
211 std::pair<BinSlot, uint32_t> slot_hash = *hash_it;
212 saved_hashes_.push_back(std::make_pair(obj, slot_hash.second));
213 saved_hashes_map_.erase(hash_it);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700214 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700215 }
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800216 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700217 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700218 DCHECK(IsImageOffsetAssigned(object));
219}
220
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800221void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700222 DCHECK(object != nullptr);
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800223 DCHECK_NE(image_objects_offset_begin_, 0u);
224
225 size_t previous_bin_sizes = GetBinSizeSum(bin_slot.GetBin()); // sum sizes in [0..bin#)
226 size_t new_offset = image_objects_offset_begin_ + previous_bin_sizes + bin_slot.GetIndex();
227 DCHECK_ALIGNED(new_offset, kObjectAlignment);
228
229 SetImageOffset(object, bin_slot, new_offset);
230 DCHECK_LT(new_offset, image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700231}
232
Ian Rogersef7d42f2014-01-06 12:55:46 -0800233bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800234 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700235 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700236 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700237}
238
Ian Rogersef7d42f2014-01-06 12:55:46 -0800239size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700240 DCHECK(object != nullptr);
241 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700242 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700243 size_t offset = lock_word.ForwardingAddress();
244 DCHECK_LT(offset, image_end_);
245 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700246}
247
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800248void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
249 DCHECK(object != nullptr);
250 DCHECK(!IsImageOffsetAssigned(object));
251 DCHECK(!IsImageBinSlotAssigned(object));
252
253 // Before we stomp over the lock word, save the hash code for later.
254 Monitor::Deflate(Thread::Current(), object);;
255 LockWord lw(object->GetLockWord(false));
256 switch (lw.GetState()) {
257 case LockWord::kFatLocked: {
258 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
259 break;
260 }
261 case LockWord::kThinLocked: {
262 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
263 break;
264 }
265 case LockWord::kUnlocked:
266 // No hash, don't need to save it.
267 break;
268 case LockWord::kHashCode:
269 saved_hashes_map_[bin_slot] = lw.GetHashCode();
270 break;
271 default:
272 LOG(FATAL) << "Unreachable.";
273 break;
274 }
275 object->SetLockWord(LockWord::FromForwardingAddress(static_cast<uint32_t>(bin_slot)),
276 false);
277 DCHECK(IsImageBinSlotAssigned(object));
278}
279
280void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
281 DCHECK(object != nullptr);
282 size_t object_size;
283 if (object->IsArtMethod()) {
284 // Methods are sized based on the target pointer size.
285 object_size = mirror::ArtMethod::InstanceSize(target_ptr_size_);
286 } else {
287 object_size = object->SizeOf();
288 }
289
290 // The magic happens here. We segregate objects into different bins based
291 // on how likely they are to get dirty at runtime.
292 //
293 // Likely-to-dirty objects get packed together into the same bin so that
294 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
295 // maximized.
296 //
297 // This means more pages will stay either clean or shared dirty (with zygote) and
298 // the app will use less of its own (private) memory.
299 Bin bin = kBinRegular;
300
301 if (kBinObjects) {
302 //
303 // Changing the bin of an object is purely a memory-use tuning.
304 // It has no change on runtime correctness.
305 //
306 // Memory analysis has determined that the following types of objects get dirtied
307 // the most:
308 //
309 // * Class'es which are verified [their clinit runs only at runtime]
310 // - classes in general [because their static fields get overwritten]
311 // - initialized classes with all-final statics are unlikely to be ever dirty,
312 // so bin them separately
313 // * Art Methods that are:
314 // - native [their native entry point is not looked up until runtime]
315 // - have declaring classes that aren't initialized
316 // [their interpreter/quick entry points are trampolines until the class
317 // becomes initialized]
318 //
319 // We also assume the following objects get dirtied either never or extremely rarely:
320 // * Strings (they are immutable)
321 // * Art methods that aren't native and have initialized declared classes
322 //
323 // We assume that "regular" bin objects are highly unlikely to become dirtied,
324 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
325 //
326 if (object->IsClass()) {
327 bin = kBinClassVerified;
328 mirror::Class* klass = object->AsClass();
329
330 if (klass->GetStatus() == Class::kStatusInitialized) {
331 bin = kBinClassInitialized;
332
333 // If the class's static fields are all final, put it into a separate bin
334 // since it's very likely it will stay clean.
335 uint32_t num_static_fields = klass->NumStaticFields();
336 if (num_static_fields == 0) {
337 bin = kBinClassInitializedFinalStatics;
338 } else {
339 // Maybe all the statics are final?
340 bool all_final = true;
341 for (uint32_t i = 0; i < num_static_fields; ++i) {
342 ArtField* field = klass->GetStaticField(i);
343 if (!field->IsFinal()) {
344 all_final = false;
345 break;
346 }
347 }
348
349 if (all_final) {
350 bin = kBinClassInitializedFinalStatics;
351 }
352 }
353 }
354 } else if (object->IsArtMethod<kVerifyNone>()) {
355 mirror::ArtMethod* art_method = down_cast<ArtMethod*>(object);
356 if (art_method->IsNative()) {
357 bin = kBinArtMethodNative;
358 } else {
359 mirror::Class* declaring_class = art_method->GetDeclaringClass();
360 if (declaring_class->GetStatus() != Class::kStatusInitialized) {
361 bin = kBinArtMethodNotInitialized;
362 } else {
363 // This is highly unlikely to dirty since there's no entry points to mutate.
364 bin = kBinArtMethodsManagedInitialized;
365 }
366 }
367 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
368 bin = kBinString; // Strings are almost always immutable (except for object header).
369 } // else bin = kBinRegular
370 }
371
372 size_t current_offset = bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
373 // Move the current bin size up to accomodate the object we just assigned a bin slot.
374 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
375 bin_slot_sizes_[bin] += offset_delta;
376
377 BinSlot new_bin_slot(bin, current_offset);
378 SetImageBinSlot(object, new_bin_slot);
379
380 ++bin_slot_count_[bin];
381
382 DCHECK_LT(GetBinSizeSum(), image_->Size());
383
384 // Grow the image closer to the end by the object we just assigned.
385 image_end_ += offset_delta;
386 DCHECK_LT(image_end_, image_->Size());
387}
388
389bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
390 DCHECK(object != nullptr);
391
392 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
393 // If it's in some other state, then we haven't yet assigned an image bin slot.
394 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
395 return false;
396 } else if (kIsDebugBuild) {
397 LockWord lock_word = object->GetLockWord(false);
398 size_t offset = lock_word.ForwardingAddress();
399 BinSlot bin_slot(offset);
400 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()])
401 << "bin slot offset should not exceed the size of that bin";
402 }
403 return true;
404}
405
406ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
407 DCHECK(object != nullptr);
408 DCHECK(IsImageBinSlotAssigned(object));
409
410 LockWord lock_word = object->GetLockWord(false);
411 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
412 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
413
414 BinSlot bin_slot(static_cast<uint32_t>(offset));
415 DCHECK_LT(bin_slot.GetIndex(), bin_slot_sizes_[bin_slot.GetBin()]);
416
417 return bin_slot;
418}
419
Brian Carlstrom7940e442013-07-12 13:46:57 -0700420bool ImageWriter::AllocMemory() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700421 size_t length = RoundUp(Runtime::Current()->GetHeap()->GetTotalMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700422 std::string error_msg;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700423 image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, PROT_READ | PROT_WRITE,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800424 true, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700425 if (UNLIKELY(image_.get() == nullptr)) {
426 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427 return false;
428 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700429
430 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700431 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
432 length));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700433 if (image_bitmap_.get() == nullptr) {
434 LOG(ERROR) << "Failed to allocate memory for image bitmap";
435 return false;
436 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700437 return true;
438}
439
440void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700441 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700442 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
443}
444
445bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700446 Thread* self = Thread::Current();
447 StackHandleScope<1> hs(self);
448 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700449 return true;
450}
451
452void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg) {
453 if (!obj->GetClass()->IsStringClass()) {
454 return;
455 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700456 mirror::String* string = obj->AsString();
Piotr Jastrzebski8a894332015-05-07 09:41:00 +0100457 const uint16_t* utf16_string = string->GetCharArray()->GetData();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700458 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
459 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
460 size_t dex_cache_count = class_linker->GetDexCacheCount();
461 for (size_t i = 0; i < dex_cache_count; ++i) {
462 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700463 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800464 const DexFile::StringId* string_id;
465 if (UNLIKELY(string->GetLength() == 0)) {
466 string_id = dex_file.FindStringId("");
467 } else {
468 string_id = dex_file.FindStringId(utf16_string);
469 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700470 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700471 // This string occurs in this dex file, assign the dex cache entry.
472 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
473 if (dex_cache->GetResolvedString(string_idx) == NULL) {
474 dex_cache->SetResolvedString(string_idx, string);
475 }
476 }
477 }
478}
479
Piotr Jastrzebski3a7cf8e2015-05-07 09:44:22 +0100480void ImageWriter::ComputeEagerResolvedStrings() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700481 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
482 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700483}
484
Ian Rogersef7d42f2014-01-06 12:55:46 -0800485bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700486 std::string temp;
487 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700488}
489
490struct NonImageClasses {
491 ImageWriter* image_writer;
492 std::set<std::string>* non_image_classes;
493};
494
495void ImageWriter::PruneNonImageClasses() {
496 if (compiler_driver_.GetImageClasses() == NULL) {
497 return;
498 }
499 Runtime* runtime = Runtime::Current();
500 ClassLinker* class_linker = runtime->GetClassLinker();
501
502 // Make a list of classes we would like to prune.
503 std::set<std::string> non_image_classes;
504 NonImageClasses context;
505 context.image_writer = this;
506 context.non_image_classes = &non_image_classes;
507 class_linker->VisitClasses(NonImageClassesVisitor, &context);
508
509 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700510 for (const std::string& it : non_image_classes) {
Mathieu Chartiere05d1d52014-11-03 11:41:47 -0800511 bool result = class_linker->RemoveClass(it.c_str(), NULL);
512 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700513 }
514
515 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700516 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700517 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
518 size_t dex_cache_count = class_linker->GetDexCacheCount();
519 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
520 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700521 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
522 Class* klass = dex_cache->GetResolvedType(i);
523 if (klass != NULL && !IsImageClass(klass)) {
524 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700525 }
526 }
527 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700528 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700529 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
530 dex_cache->SetResolvedMethod(i, resolution_method);
531 }
532 }
533 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700534 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700535 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
536 dex_cache->SetResolvedField(i, NULL);
537 }
538 }
539 }
540}
541
542bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
543 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
544 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700545 std::string temp;
546 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700547 }
548 return true;
549}
550
Piotr Jastrzebski3a7cf8e2015-05-07 09:44:22 +0100551void ImageWriter::CheckNonImageClassesRemoved()
552 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700553 if (compiler_driver_.GetImageClasses() != nullptr) {
554 gc::Heap* heap = Runtime::Current()->GetHeap();
555 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
556 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700557 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700558}
559
560void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
561 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700562 if (obj->IsClass()) {
563 Class* klass = obj->AsClass();
564 if (!image_writer->IsImageClass(klass)) {
565 image_writer->DumpImageClasses();
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700566 std::string temp;
567 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700568 << " " << PrettyDescriptor(klass);
569 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700570 }
571}
572
573void ImageWriter::DumpImageClasses() {
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700574 const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700575 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700576 for (const std::string& image_class : *image_classes) {
577 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700578 }
579}
580
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800581void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700582 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700583 // if it is a string, we want to intern it if its not interned.
584 if (obj->GetClass()->IsStringClass()) {
585 // we must be an interned string that was forward referenced and already assigned
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800586 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700587 DCHECK_EQ(obj, obj->AsString()->Intern());
588 return;
589 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700590 mirror::String* const interned = obj->AsString()->Intern();
591 if (obj != interned) {
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800592 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700593 // interned obj is after us, allocate its location early
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800594 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700595 }
596 // point those looking for this object to the interned version.
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800597 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700598 return;
599 }
600 // else (obj == interned), nothing to do but fall through to the normal case
601 }
602
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800603 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700604}
605
606ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
607 Runtime* runtime = Runtime::Current();
608 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700609 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700610 StackHandleScope<3> hs(self);
611 Handle<Class> object_array_class(hs.NewHandle(
612 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700613
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700614 // build an Object[] of all the DexCaches used in the source_space_.
615 // Since we can't hold the dex lock when allocating the dex_caches
616 // ObjectArray, we lock the dex lock twice, first to get the number
617 // of dex caches first and then lock it again to copy the dex
618 // caches. We check that the number of dex caches does not change.
619 size_t dex_cache_count;
620 {
621 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
622 dex_cache_count = class_linker->GetDexCacheCount();
623 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700624 Handle<ObjectArray<Object>> dex_caches(
625 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700626 dex_cache_count)));
627 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
628 {
629 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
630 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
631 << "The number of dex caches changed.";
632 for (size_t i = 0; i < dex_cache_count; ++i) {
633 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
634 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700635 }
636
637 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700638 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700639 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100640 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
641 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
Mathieu Chartier1fb463e2014-10-23 16:48:06 -0700642 image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
643 runtime->GetImtUnimplementedMethod());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100644 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
645 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
646 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
647 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
648 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
649 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
650 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700651 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100652 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700653 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
654 CHECK(image_roots->Get(i) != NULL);
655 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700656 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700657}
658
Mathieu Chartier590fee92013-09-13 13:46:47 -0700659// Walk instance fields of the given Class. Separate function to allow recursion on the super
660// class.
661void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
662 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700663 StackHandleScope<1> hs(Thread::Current());
664 Handle<mirror::Class> h_class(hs.NewHandle(klass));
665 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700666 if (super != nullptr) {
667 WalkInstanceFields(obj, super);
668 }
669 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700670 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Markobfa3ed02014-11-10 18:32:59 +0000671 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700672 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700673 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700674 if (value != nullptr) {
675 WalkFieldsInOrder(value);
676 }
Vladimir Markobfa3ed02014-11-10 18:32:59 +0000677 field_offset = MemberOffset(field_offset.Uint32Value() +
678 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700679 }
680}
681
682// For an unvisited object, visit it then all its children found via fields.
683void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800684 // Use our own visitor routine (instead of GC visitor) to get better locality between
685 // an object and its fields
686 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700687 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700688 StackHandleScope<2> hs(Thread::Current());
689 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
690 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700691 // visit the object itself.
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800692 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700693 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700694 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700695 if (h_obj->IsClass()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700696 size_t num_static_fields = klass->NumReferenceStaticFields();
Vladimir Markobfa3ed02014-11-10 18:32:59 +0000697 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700698 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700699 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700700 if (value != nullptr) {
701 WalkFieldsInOrder(value);
702 }
Vladimir Markobfa3ed02014-11-10 18:32:59 +0000703 field_offset = MemberOffset(field_offset.Uint32Value() +
704 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700705 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700706 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700707 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700708 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700709 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700710 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700711 mirror::Object* value = obj_array->Get(i);
712 if (value != nullptr) {
713 WalkFieldsInOrder(value);
714 }
715 }
716 }
717 }
718}
719
720void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
721 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
722 DCHECK(writer != nullptr);
723 writer->WalkFieldsInOrder(obj);
724}
725
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800726void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
727 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
728 DCHECK(writer != nullptr);
729 writer->UnbinObjectsIntoOffset(obj);
730}
731
732void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
733 CHECK(obj != nullptr);
734
735 // We know the bin slot, and the total bin sizes for all objects by now,
736 // so calculate the object's final image offset.
737
738 DCHECK(IsImageBinSlotAssigned(obj));
739 BinSlot bin_slot = GetImageBinSlot(obj);
740 // Change the lockword from a bin slot into an offset
741 AssignImageOffset(obj, bin_slot);
742}
743
Brian Carlstrom7940e442013-07-12 13:46:57 -0700744void ImageWriter::CalculateNewObjectOffsets(size_t oat_loaded_size, size_t oat_data_offset) {
745 CHECK_NE(0U, oat_loaded_size);
746 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700747 StackHandleScope<1> hs(self);
748 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700749
750 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700751 DCHECK_EQ(0U, image_end_);
752
Mathieu Chartier31e89252013-08-28 11:29:12 -0700753 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700754 // know where image_roots is going to end up
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800755 image_end_ += RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700756
757 {
758 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700759 // TODO: Image spaces only?
Brian Carlstrom7940e442013-07-12 13:46:57 -0700760 const char* old = self->StartAssertNoThreadSuspension("ImageWriter");
Mathieu Chartier590fee92013-09-13 13:46:47 -0700761 DCHECK_LT(image_end_, image_->Size());
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800762 image_objects_offset_begin_ = image_end_;
763 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700764 heap->VisitObjects(WalkFieldsCallback, this);
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800765 // Transform each object's bin slot into an offset which will be used to do the final copy.
766 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
767 DCHECK(saved_hashes_map_.empty()); // All binslot hashes should've been put into vector by now.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700768 self->EndAssertNoThreadSuspension(old);
769 }
770
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800771 DCHECK_GT(image_end_, GetBinSizeSum());
772
773 if (kIsDebugBuild) {
774 LOG(INFO) << "Bin summary (total size: " << GetBinSizeSum() << "): ";
775 for (size_t bin = 0; bin < kBinSize; ++bin) {
776 LOG(INFO) << " bin# " << bin << ", number objects: " << bin_slot_count_[bin] << ", "
777 << " total byte size: " << bin_slot_sizes_[bin];
778 }
779 }
780
Brian Carlstrom7940e442013-07-12 13:46:57 -0700781 const byte* oat_file_begin = image_begin_ + RoundUp(image_end_, kPageSize);
782 const byte* oat_file_end = oat_file_begin + oat_loaded_size;
783 oat_data_begin_ = oat_file_begin + oat_data_offset;
784 const byte* oat_data_end = oat_data_begin_ + oat_file_->Size();
785
Mathieu Chartier31e89252013-08-28 11:29:12 -0700786 // Return to write header at start of image with future location of image_roots. At this point,
787 // image_end_ is the size of the image (excluding bitmaps).
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700788 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800789 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
790 heap_bytes_per_bitmap_byte;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800791 ImageHeader image_header(PointerToLowMemUInt32(image_begin_),
Mathieu Chartier31e89252013-08-28 11:29:12 -0700792 static_cast<uint32_t>(image_end_),
793 RoundUp(image_end_, kPageSize),
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800794 RoundUp(bitmap_bytes, kPageSize),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700795 PointerToLowMemUInt32(GetImageAddress(image_roots.Get())),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700796 oat_file_->GetOatHeader().GetChecksum(),
Ian Rogersef7d42f2014-01-06 12:55:46 -0800797 PointerToLowMemUInt32(oat_file_begin),
798 PointerToLowMemUInt32(oat_data_begin_),
799 PointerToLowMemUInt32(oat_data_end),
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700800 PointerToLowMemUInt32(oat_file_end),
801 compile_pic_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700802 memcpy(image_->Begin(), &image_header, sizeof(image_header));
803
804 // Note that image_end_ is left at end of used space
805}
806
Piotr Jastrzebski3a7cf8e2015-05-07 09:44:22 +0100807void ImageWriter::CopyAndFixupObjects()
808 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700809 Thread* self = Thread::Current();
810 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
811 gc::Heap* heap = Runtime::Current()->GetHeap();
812 // TODO: heap validation can't handle this fix up pass
813 heap->DisableObjectValidation();
814 // TODO: Image spaces only?
815 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700816 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
817 // Fix up the object previously had hash codes.
818 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700819 hash_pair.first->SetLockWord(LockWord::FromHashCode(hash_pair.second), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700820 }
821 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700822 self->EndAssertNoThreadSuspension(old_cause);
823}
824
Mathieu Chartier590fee92013-09-13 13:46:47 -0700825void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700826 DCHECK(obj != nullptr);
827 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700828 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700829 // see GetLocalAddress for similar computation
830 size_t offset = image_writer->GetImageOffset(obj);
831 byte* dst = image_writer->image_->Begin() + offset;
832 const byte* src = reinterpret_cast<const byte*>(obj);
Mathieu Chartiere832e642014-11-10 11:08:06 -0800833 size_t n;
834 if (obj->IsArtMethod()) {
835 // Size without pointer fields since we don't want to overrun the buffer if target art method
836 // is 32 bits but source is 64 bits.
Mathieu Chartierf521f422014-11-24 18:29:54 -0800837 n = mirror::ArtMethod::SizeWithoutPointerFields(sizeof(void*));
Mathieu Chartiere832e642014-11-10 11:08:06 -0800838 } else {
839 n = obj->SizeOf();
840 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700841 DCHECK_LT(offset + n, image_writer->image_->Size());
842 memcpy(dst, src, n);
843 Object* copy = reinterpret_cast<Object*>(dst);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700844 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
845 // word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700846 copy->SetLockWord(LockWord(), false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700847 image_writer->FixupObject(obj, copy);
848}
849
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800850// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700851class FixupVisitor {
852 public:
853 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
854 }
855
856 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
857 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -0700858 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700859 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
860 // image.
861 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700862 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700863 }
864
865 // java.lang.ref.Reference visitor.
866 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
867 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
868 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
869 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700870 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700871 }
872
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700873 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700874 ImageWriter* const image_writer_;
875 mirror::Object* const copy_;
876};
877
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700878class FixupClassVisitor FINAL : public FixupVisitor {
879 public:
880 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
881 }
882
883 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
884 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
885 DCHECK(obj->IsClass());
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800886 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700887
Igor Murashkin3f735bd2014-11-14 15:01:59 -0800888 // TODO: Remove dead code
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700889 if (offset.Uint32Value() < mirror::Class::EmbeddedVTableOffset().Uint32Value()) {
890 return;
891 }
892 }
893
894 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
895 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
896 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
897 LOG(FATAL) << "Reference not expected here.";
898 }
899};
900
Ian Rogersef7d42f2014-01-06 12:55:46 -0800901void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700902 DCHECK(orig != nullptr);
903 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700904 if (kUseBakerOrBrooksReadBarrier) {
905 orig->AssertReadBarrierPointer();
906 if (kUseBrooksReadBarrier) {
907 // Note the address 'copy' isn't the same as the image address of 'orig'.
908 copy->SetReadBarrierPointer(GetImageAddress(orig));
909 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
910 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800911 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700912 if (orig->IsClass() && orig->AsClass()->ShouldHaveEmbeddedImtAndVTable()) {
913 FixupClassVisitor visitor(this, copy);
914 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
915 } else {
916 FixupVisitor visitor(this, copy);
917 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
918 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700919 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800920 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Mathieu Chartiere832e642014-11-10 11:08:06 -0800921 } else if (orig->IsClass() && orig->AsClass()->IsArtMethodClass()) {
922 // Set the right size for the target.
923 size_t size = mirror::ArtMethod::InstanceSize(target_ptr_size_);
924 down_cast<mirror::Class*>(copy)->SetObjectSizeWithoutChecks(size);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700925 }
926}
927
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700928const byte* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
929 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier1fb463e2014-10-23 16:48:06 -0700930 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700931
932 // Use original code if it exists. Otherwise, set the code pointer to the resolution
933 // trampoline.
934
935 // Quick entrypoint:
936 const byte* quick_code = GetOatAddress(method->GetQuickOatCodeOffset());
937 *quick_is_interpreted = false;
938 if (quick_code != nullptr &&
939 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
940 // We have code for a non-static or initialized method, just use the code.
941 } else if (quick_code == nullptr && method->IsNative() &&
942 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
943 // Non-static or initialized native method missing compiled code, use generic JNI version.
944 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
945 } else if (quick_code == nullptr && !method->IsNative()) {
946 // We don't have code at all for a non-native method, use the interpreter.
947 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
948 *quick_is_interpreted = true;
949 } else {
950 CHECK(!method->GetDeclaringClass()->IsInitialized());
951 // We have code for a static method, but need to go through the resolution stub for class
952 // initialization.
953 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
954 }
955 return quick_code;
956}
957
958const byte* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
959 // Calculate the quick entry point following the same logic as FixupMethod() below.
960 // The resolution method has a special trampoline to call.
Mathieu Chartier1fb463e2014-10-23 16:48:06 -0700961 Runtime* runtime = Runtime::Current();
962 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700963 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier1fb463e2014-10-23 16:48:06 -0700964 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
965 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700966 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
967 } else {
968 // We assume all methods have code. If they don't currently then we set them to the use the
969 // resolution trampoline. Abstract methods never have code and so we need to make sure their
970 // use results in an AbstractMethodError. We use the interpreter to achieve this.
971 if (UNLIKELY(method->IsAbstract())) {
972 return GetOatAddress(quick_to_interpreter_bridge_offset_);
973 } else {
974 bool quick_is_interpreted;
975 return GetQuickCode(method, &quick_is_interpreted);
976 }
977 }
978}
979
Ian Rogersef7d42f2014-01-06 12:55:46 -0800980void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -0700981 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
982 // oat_begin_
Mathieu Chartiere832e642014-11-10 11:08:06 -0800983 // For 64 bit targets we need to repack the current runtime pointer sized fields to the right
984 // locations.
985 // Copy all of the fields from the runtime methods to the target methods first since we did a
986 // bytewise copy earlier.
987#if defined(ART_USE_PORTABLE_COMPILER)
988 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
989 orig->GetEntryPointFromPortableCompiledCode(), target_ptr_size_);
990#endif
991 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(orig->GetEntryPointFromInterpreter(),
992 target_ptr_size_);
993 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(orig->GetEntryPointFromJni(), target_ptr_size_);
994 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
995 orig->GetEntryPointFromQuickCompiledCode(), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700996
Ian Rogers848871b2013-08-05 10:56:33 -0700997 // The resolution method has a special trampoline to call.
Mathieu Chartier1fb463e2014-10-23 16:48:06 -0700998 Runtime* runtime = Runtime::Current();
999 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Ian Rogers63bc11e2014-09-18 08:56:45 -07001000#if defined(ART_USE_PORTABLE_COMPILER)
Mathieu Chartiere832e642014-11-10 11:08:06 -08001001 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
1002 GetOatAddress(portable_resolution_trampoline_offset_), target_ptr_size_);
Ian Rogers63bc11e2014-09-18 08:56:45 -07001003#endif
Mathieu Chartiere832e642014-11-10 11:08:06 -08001004 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1005 GetOatAddress(quick_resolution_trampoline_offset_), target_ptr_size_);
Mathieu Chartier1fb463e2014-10-23 16:48:06 -07001006 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1007 orig == runtime->GetImtUnimplementedMethod())) {
Ian Rogers63bc11e2014-09-18 08:56:45 -07001008#if defined(ART_USE_PORTABLE_COMPILER)
Mathieu Chartiere832e642014-11-10 11:08:06 -08001009 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(
1010 GetOatAddress(portable_imt_conflict_trampoline_offset_), target_ptr_size_);
Ian Rogers63bc11e2014-09-18 08:56:45 -07001011#endif
Mathieu Chartiere832e642014-11-10 11:08:06 -08001012 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1013 GetOatAddress(quick_imt_conflict_trampoline_offset_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001014 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001015 // We assume all methods have code. If they don't currently then we set them to the use the
1016 // resolution trampoline. Abstract methods never have code and so we need to make sure their
1017 // use results in an AbstractMethodError. We use the interpreter to achieve this.
1018 if (UNLIKELY(orig->IsAbstract())) {
Ian Rogers63bc11e2014-09-18 08:56:45 -07001019#if defined(ART_USE_PORTABLE_COMPILER)
Mathieu Chartiere832e642014-11-10 11:08:06 -08001020 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(
1021 GetOatAddress(portable_to_interpreter_bridge_offset_), target_ptr_size_);
Ian Rogers63bc11e2014-09-18 08:56:45 -07001022#endif
Mathieu Chartiere832e642014-11-10 11:08:06 -08001023 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
1024 GetOatAddress(quick_to_interpreter_bridge_offset_), target_ptr_size_);
1025 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1026 reinterpret_cast<EntryPointFromInterpreter*>(const_cast<byte*>(
1027 GetOatAddress(interpreter_to_interpreter_bridge_offset_))), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001028 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001029 bool quick_is_interpreted;
1030 const byte* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartiere832e642014-11-10 11:08:06 -08001031 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02001032
1033 // Portable entrypoint:
Sebastien Hertze1d07812014-05-21 15:44:09 +02001034 bool portable_is_interpreted = false;
Ian Rogers63bc11e2014-09-18 08:56:45 -07001035#if defined(ART_USE_PORTABLE_COMPILER)
1036 const byte* portable_code = GetOatAddress(orig->GetPortableOatCodeOffset());
Mathieu Chartiere832e642014-11-10 11:08:06 -08001037 if (portable_code != nullptr && (!orig->IsStatic() || orig->IsConstructor() ||
1038 orig->GetDeclaringClass()->IsInitialized())) {
Sebastien Hertze1d07812014-05-21 15:44:09 +02001039 // We have code for a non-static or initialized method, just use the code.
1040 } else if (portable_code == nullptr && orig->IsNative() &&
1041 (!orig->IsStatic() || orig->GetDeclaringClass()->IsInitialized())) {
1042 // Non-static or initialized native method missing compiled code, use generic JNI version.
1043 // TODO: generic JNI support for LLVM.
1044 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
1045 } else if (portable_code == nullptr && !orig->IsNative()) {
1046 // We don't have code at all for a non-native method, use the interpreter.
1047 portable_code = GetOatAddress(portable_to_interpreter_bridge_offset_);
1048 portable_is_interpreted = true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08001049 } else {
Sebastien Hertze1d07812014-05-21 15:44:09 +02001050 CHECK(!orig->GetDeclaringClass()->IsInitialized());
1051 // We have code for a static method, but need to go through the resolution stub for class
1052 // initialization.
1053 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
Ian Rogers848871b2013-08-05 10:56:33 -07001054 }
Mathieu Chartiere832e642014-11-10 11:08:06 -08001055 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
1056 portable_code, target_ptr_size_);
Ian Rogers63bc11e2014-09-18 08:56:45 -07001057#endif
Sebastien Hertze1d07812014-05-21 15:44:09 +02001058 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07001059 if (orig->IsNative()) {
1060 // The native method's pointer is set to a stub to lookup via dlsym.
1061 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere832e642014-11-10 11:08:06 -08001062 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_),
1063 target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001064 }
Sebastien Hertze1d07812014-05-21 15:44:09 +02001065
1066 // Interpreter entrypoint:
1067 // Set the interpreter entrypoint depending on whether there is compiled code or not.
1068 uint32_t interpreter_code = (quick_is_interpreted && portable_is_interpreted)
1069 ? interpreter_to_interpreter_bridge_offset_
1070 : interpreter_to_compiled_code_bridge_offset_;
Mathieu Chartiere832e642014-11-10 11:08:06 -08001071 EntryPointFromInterpreter* interpreter_entrypoint =
Sebastien Hertze1d07812014-05-21 15:44:09 +02001072 reinterpret_cast<EntryPointFromInterpreter*>(
Mathieu Chartiere832e642014-11-10 11:08:06 -08001073 const_cast<byte*>(GetOatAddress(interpreter_code)));
1074 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1075 interpreter_entrypoint, target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001076 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001077 }
1078}
1079
Alex Lighta59dd802014-07-02 16:28:08 -07001080static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
1081 Elf32_Shdr* data_sec = elf->FindSectionByName(".rodata");
1082 if (data_sec == nullptr) {
1083 return nullptr;
1084 }
1085 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec->sh_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001086}
1087
Alex Light53cb16b2014-06-12 11:26:29 -07001088void ImageWriter::PatchOatCodeAndMethods(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001089 std::string error_msg;
1090 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
1091 MAP_SHARED, &error_msg));
1092 if (elf.get() == nullptr) {
1093 LOG(FATAL) << "Unable patch oat file: " << error_msg;
1094 return;
Alex Light53cb16b2014-06-12 11:26:29 -07001095 }
Alex Lighta59dd802014-07-02 16:28:08 -07001096 if (!ElfPatcher::Patch(&compiler_driver_, elf.get(), oat_file_,
1097 reinterpret_cast<uintptr_t>(oat_data_begin_),
1098 GetImageAddressCallback, reinterpret_cast<void*>(this),
1099 &error_msg)) {
1100 LOG(FATAL) << "unable to patch oat file: " << error_msg;
1101 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001102 }
Alex Lighta59dd802014-07-02 16:28:08 -07001103 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1104 CHECK(oat_header != nullptr);
1105 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001106
Brian Carlstrom7940e442013-07-12 13:46:57 -07001107 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001108 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001109}
1110
Igor Murashkin3f735bd2014-11-14 15:01:59 -08001111size_t ImageWriter::GetBinSizeSum(ImageWriter::Bin up_to) const {
1112 DCHECK_LE(up_to, kBinSize);
1113 return std::accumulate(&bin_slot_sizes_[0], &bin_slot_sizes_[up_to], /*init*/0);
1114}
1115
1116ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
1117 // These values may need to get updated if more bins are added to the enum Bin
1118 static_assert(kBinBits == 3, "wrong number of bin bits");
1119 static_assert(kBinShift == 29, "wrong number of shift");
1120 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
1121
1122 DCHECK_LT(GetBin(), kBinSize);
1123 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
1124}
1125
1126ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
1127 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
1128 DCHECK_EQ(index, GetIndex());
1129}
1130
1131ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
1132 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
1133}
1134
1135uint32_t ImageWriter::BinSlot::GetIndex() const {
1136 return lockword_ & ~kBinMask;
1137}
1138
Brian Carlstrom7940e442013-07-12 13:46:57 -07001139} // namespace art