blob: 64d2de1b45af350e05a6cec193fec0047cf6f72e [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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070057#include "utils.h"
58
Brian Carlstromea46f952013-07-30 01:26:50 -070059using ::art::mirror::ArtField;
60using ::art::mirror::ArtMethod;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070061using ::art::mirror::Class;
62using ::art::mirror::DexCache;
63using ::art::mirror::EntryPointFromInterpreter;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070064using ::art::mirror::Object;
65using ::art::mirror::ObjectArray;
66using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070067
68namespace art {
69
Vladimir Markof4da6752014-08-01 19:04:18 +010070bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -080071 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Vladimir Markof4da6752014-08-01 19:04:18 +010072 {
73 Thread::Current()->TransitionFromSuspendedToRunnable();
74 PruneNonImageClasses(); // Remove junk
75 ComputeLazyFieldsForImageClasses(); // Add useful information
Vladimir Markof4da6752014-08-01 19:04:18 +010076 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
77 }
78 gc::Heap* heap = Runtime::Current()->GetHeap();
79 heap->CollectGarbage(false); // Remove garbage.
80
81 if (!AllocMemory()) {
82 return false;
83 }
84
85 if (kIsDebugBuild) {
86 ScopedObjectAccess soa(Thread::Current());
87 CheckNonImageClassesRemoved();
88 }
89
90 Thread::Current()->TransitionFromSuspendedToRunnable();
91 CalculateNewObjectOffsets();
92 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
93
94 return true;
95}
96
Brian Carlstrom7940e442013-07-12 13:46:57 -070097bool ImageWriter::Write(const std::string& image_filename,
Brian Carlstrom7940e442013-07-12 13:46:57 -070098 const std::string& oat_filename,
99 const std::string& oat_location) {
100 CHECK(!image_filename.empty());
101
Brian Carlstrom7940e442013-07-12 13:46:57 -0700102 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700103
Ian Rogers700a4022014-05-19 16:49:03 -0700104 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700105 if (oat_file.get() == NULL) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800106 PLOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700107 return false;
108 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700109 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -0700110 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, &error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700111 if (oat_file_ == nullptr) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800112 PLOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700113 << ": " << error_msg;
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700114 return false;
115 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700116 CHECK_EQ(class_linker->RegisterOatFile(oat_file_), oat_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700117
Ian Rogers848871b2013-08-05 10:56:33 -0700118 interpreter_to_interpreter_bridge_offset_ =
119 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
120 interpreter_to_compiled_code_bridge_offset_ =
121 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
122
123 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
124
Jeff Hao88474b42013-10-23 16:24:40 -0700125 portable_imt_conflict_trampoline_offset_ =
126 oat_file_->GetOatHeader().GetPortableImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700127 portable_resolution_trampoline_offset_ =
128 oat_file_->GetOatHeader().GetPortableResolutionTrampolineOffset();
129 portable_to_interpreter_bridge_offset_ =
130 oat_file_->GetOatHeader().GetPortableToInterpreterBridgeOffset();
131
Andreas Gampe2da88232014-02-27 12:26:20 -0800132 quick_generic_jni_trampoline_offset_ =
133 oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
Jeff Hao88474b42013-10-23 16:24:40 -0700134 quick_imt_conflict_trampoline_offset_ =
135 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700136 quick_resolution_trampoline_offset_ =
137 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
138 quick_to_interpreter_bridge_offset_ =
139 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700140
Brian Carlstrom7940e442013-07-12 13:46:57 -0700141 size_t oat_loaded_size = 0;
142 size_t oat_data_offset = 0;
143 ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
Alex Light53cb16b2014-06-12 11:26:29 -0700144
Vladimir Markof4da6752014-08-01 19:04:18 +0100145 Thread::Current()->TransitionFromSuspendedToRunnable();
146 CreateHeader(oat_loaded_size, oat_data_offset);
147 CopyAndFixupObjects();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700148 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
149
Vladimir Markof4da6752014-08-01 19:04:18 +0100150 SetOatChecksumFromElfFile(oat_file.get());
151
Ian Rogers700a4022014-05-19 16:49:03 -0700152 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700153 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700154 if (image_file.get() == NULL) {
155 LOG(ERROR) << "Failed to open image file " << image_filename;
156 return false;
157 }
158 if (fchmod(image_file->Fd(), 0644) != 0) {
159 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
160 return EXIT_FAILURE;
161 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700162
163 // Write out the image.
164 CHECK_EQ(image_end_, image_header->GetImageSize());
165 if (!image_file->WriteFully(image_->Begin(), image_end_)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700166 PLOG(ERROR) << "Failed to write image file " << image_filename;
167 return false;
168 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700169
170 // Write out the image bitmap at the page aligned start of the image end.
171 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
172 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
173 image_header->GetImageBitmapSize(),
174 image_header->GetImageBitmapOffset())) {
175 PLOG(ERROR) << "Failed to write image file " << image_filename;
176 return false;
177 }
178
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 return true;
180}
181
Mathieu Chartier590fee92013-09-13 13:46:47 -0700182void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
183 DCHECK(object != nullptr);
184 DCHECK_NE(offset, 0U);
185 DCHECK(!IsImageOffsetAssigned(object));
186 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
187 DCHECK_ALIGNED(obj, kObjectAlignment);
188 image_bitmap_->Set(obj);
189 // Before we stomp over the lock word, save the hash code for later.
190 Monitor::Deflate(Thread::Current(), object);;
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700191 LockWord lw(object->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700192 switch (lw.GetState()) {
193 case LockWord::kFatLocked: {
194 LOG(FATAL) << "Fat locked object " << obj << " found during object copy";
195 break;
196 }
197 case LockWord::kThinLocked: {
198 LOG(FATAL) << "Thin locked object " << obj << " found during object copy";
199 break;
200 }
201 case LockWord::kUnlocked:
202 // No hash, don't need to save it.
203 break;
204 case LockWord::kHashCode:
205 saved_hashes_.push_back(std::make_pair(obj, lw.GetHashCode()));
206 break;
207 default:
208 LOG(FATAL) << "Unreachable.";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700209 UNREACHABLE();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700210 }
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700211 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700212 DCHECK(IsImageOffsetAssigned(object));
213}
214
215void ImageWriter::AssignImageOffset(mirror::Object* object) {
216 DCHECK(object != nullptr);
217 SetImageOffset(object, image_end_);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800218 size_t object_size;
219 if (object->IsArtMethod()) {
220 // Methods are sized based on the target pointer size.
221 object_size = mirror::ArtMethod::InstanceSize(target_ptr_size_);
222 } else {
223 object_size = object->SizeOf();
224 }
225 image_end_ += RoundUp(object_size, 8); // 64-bit alignment
Mathieu Chartier590fee92013-09-13 13:46:47 -0700226 DCHECK_LT(image_end_, image_->Size());
227}
228
Ian Rogersef7d42f2014-01-06 12:55:46 -0800229bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700230 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700231 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700232}
233
Ian Rogersef7d42f2014-01-06 12:55:46 -0800234size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700235 DCHECK(object != nullptr);
236 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700237 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700238 size_t offset = lock_word.ForwardingAddress();
239 DCHECK_LT(offset, image_end_);
240 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700241}
242
Brian Carlstrom7940e442013-07-12 13:46:57 -0700243bool ImageWriter::AllocMemory() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700244 size_t length = RoundUp(Runtime::Current()->GetHeap()->GetTotalMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700245 std::string error_msg;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700246 image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, PROT_READ | PROT_WRITE,
Ian Rogers3cd86d62014-08-14 08:53:12 -0700247 false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700248 if (UNLIKELY(image_.get() == nullptr)) {
249 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700250 return false;
251 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700252
253 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700254 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
255 length));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700256 if (image_bitmap_.get() == nullptr) {
257 LOG(ERROR) << "Failed to allocate memory for image bitmap";
258 return false;
259 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700260 return true;
261}
262
263void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700264 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700265 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
266}
267
268bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700269 Thread* self = Thread::Current();
270 StackHandleScope<1> hs(self);
271 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700272 return true;
273}
274
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800275// Count the number of strings in the heap and put the result in arg as a size_t pointer.
276static void CountStringsCallback(Object* obj, void* arg)
277 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
278 if (obj->GetClass()->IsStringClass()) {
279 ++*reinterpret_cast<size_t*>(arg);
280 }
281}
282
283// Collect all the java.lang.String in the heap and put them in the output strings_ array.
284class StringCollector {
285 public:
286 StringCollector(Handle<mirror::ObjectArray<mirror::String>> strings, size_t index)
287 : strings_(strings), index_(index) {
288 }
289 static void Callback(Object* obj, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
290 auto* collector = reinterpret_cast<StringCollector*>(arg);
291 if (obj->GetClass()->IsStringClass()) {
292 collector->strings_->SetWithoutChecks<false>(collector->index_++, obj->AsString());
293 }
294 }
295 size_t GetIndex() const {
296 return index_;
297 }
298
299 private:
300 Handle<mirror::ObjectArray<mirror::String>> strings_;
301 size_t index_;
302};
303
304// Compare strings based on length, used for sorting strings by length / reverse length.
305class StringLengthComparator {
306 public:
307 explicit StringLengthComparator(Handle<mirror::ObjectArray<mirror::String>> strings)
308 : strings_(strings) {
309 }
310 bool operator()(size_t a, size_t b) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
311 return strings_->GetWithoutChecks(a)->GetLength() < strings_->GetWithoutChecks(b)->GetLength();
312 }
313
314 private:
315 Handle<mirror::ObjectArray<mirror::String>> strings_;
316};
317
318// If string a is a prefix of b or b is a prefix of a then they are considered equal. This
319// enables us to find prefixes instead of exact matches. Otherwise we do a normal string
320// comparison. The strings compared of the form <position, length> inside of the chars_ array.
321class SubstringComparator {
322 public:
323 explicit SubstringComparator(const std::vector<uint16_t>* const chars) : chars_(chars) {
324 }
325 bool operator()(const std::pair<size_t, size_t>& a, const std::pair<size_t, size_t>& b) {
326 size_t compare_length = std::min(a.second, b.second);
327 const uint16_t* ptr_a = &chars_->at(a.first);
328 const uint16_t* ptr_b = &chars_->at(b.first);
329 for (size_t i = 0; i < compare_length; ++i) {
330 if (ptr_a[i] != ptr_b[i]) {
331 return ptr_a[i] < ptr_b[i];
332 }
333 }
334 return false;
335 }
336
337 private:
338 const std::vector<uint16_t>* const chars_;
339};
340
341void ImageWriter::ProcessStrings() {
342 size_t total_strings = 0;
343 gc::Heap* heap = Runtime::Current()->GetHeap();
344 ClassLinker* cl = Runtime::Current()->GetClassLinker();
345 {
346 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
347 heap->VisitObjects(CountStringsCallback, &total_strings); // Count the strings.
348 }
349 Thread* self = Thread::Current();
350 StackHandleScope<1> hs(self);
351 auto strings = hs.NewHandle(cl->AllocStringArray(self, total_strings));
352 StringCollector string_collector(strings, 0U);
353 {
354 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
355 // Read strings into the array.
356 heap->VisitObjects(StringCollector::Callback, &string_collector);
357 }
358 // Some strings could have gotten freed if AllocStringArray caused a GC.
359 CHECK_LE(string_collector.GetIndex(), total_strings);
360 total_strings = string_collector.GetIndex();
361 size_t total_length = 0;
362 std::vector<size_t> reverse_sorted_strings;
363 for (size_t i = 0; i < total_strings; ++i) {
364 mirror::String* s = strings->GetWithoutChecks(i);
365 // Look up the string in the array.
366 total_length += s->GetLength();
367 reverse_sorted_strings.push_back(i);
368 }
369 // Sort by reverse length.
370 StringLengthComparator comparator(strings);
371 std::sort(reverse_sorted_strings.rbegin(), reverse_sorted_strings.rend(), comparator);
372 // Deduplicate prefixes and add strings to the char array.
373 std::vector<uint16_t> combined_chars(total_length, 0U);
374 size_t num_chars = 0;
375 // Characters of strings which are non equal prefix of another string (not the same string).
376 // We don't count the savings from equal strings since these would get interned later anyways.
377 size_t prefix_saved_chars = 0;
378 std::set<std::pair<size_t, size_t>, SubstringComparator> existing_strings((
379 SubstringComparator(&combined_chars)));
380 for (size_t i = 0; i < total_strings; ++i) {
381 mirror::String* s = strings->GetWithoutChecks(reverse_sorted_strings[i]);
382 // Add the string to the end of the char array.
383 size_t length = s->GetLength();
384 for (size_t j = 0; j < length; ++j) {
385 combined_chars[num_chars++] = s->CharAt(j);
386 }
387 // Try to see if the string exists as a prefix of an existing string.
388 size_t new_offset = 0;
389 std::pair<size_t, size_t> new_string(num_chars - length, length);
390 auto it = existing_strings.find(new_string);
391 if (it != existing_strings.end()) {
392 for (size_t j = 0; j < length; ++j) {
393 DCHECK_EQ(combined_chars[it->first + j], s->CharAt(j));
394 }
395 // Shares a prefix, set the offset to where the new offset will be.
396 new_offset = it->first;
397 // Remove the added chars.
398 num_chars -= length;
399 if (it->second != length) {
400 prefix_saved_chars += length;
401 }
402 } else {
403 new_offset = new_string.first;
404 existing_strings.insert(new_string);
405 }
406 s->SetOffset(new_offset);
407 }
408 // Allocate and update the char arrays.
409 auto* array = mirror::CharArray::Alloc(self, num_chars);
410 for (size_t i = 0; i < num_chars; ++i) {
411 array->SetWithoutChecks<false>(i, combined_chars[i]);
412 }
413 for (size_t i = 0; i < total_strings; ++i) {
414 strings->GetWithoutChecks(i)->SetArray(array);
415 }
416 VLOG(compiler) << "Total # image strings=" << total_strings << " combined length="
417 << total_length << " prefix saved chars=" << prefix_saved_chars;
418 ComputeEagerResolvedStrings();
419}
420
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700421void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700422 if (!obj->GetClass()->IsStringClass()) {
423 return;
424 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700425 mirror::String* string = obj->AsString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700426 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700427 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
428 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
429 size_t dex_cache_count = class_linker->GetDexCacheCount();
430 for (size_t i = 0; i < dex_cache_count; ++i) {
431 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700432 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800433 const DexFile::StringId* string_id;
434 if (UNLIKELY(string->GetLength() == 0)) {
435 string_id = dex_file.FindStringId("");
436 } else {
437 string_id = dex_file.FindStringId(utf16_string);
438 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700439 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700440 // This string occurs in this dex file, assign the dex cache entry.
441 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
442 if (dex_cache->GetResolvedString(string_idx) == NULL) {
443 dex_cache->SetResolvedString(string_idx, string);
444 }
445 }
446 }
447}
448
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800449void ImageWriter::ComputeEagerResolvedStrings() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700450 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
451 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700452}
453
Ian Rogersef7d42f2014-01-06 12:55:46 -0800454bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700455 std::string temp;
456 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700457}
458
459struct NonImageClasses {
460 ImageWriter* image_writer;
461 std::set<std::string>* non_image_classes;
462};
463
464void ImageWriter::PruneNonImageClasses() {
465 if (compiler_driver_.GetImageClasses() == NULL) {
466 return;
467 }
468 Runtime* runtime = Runtime::Current();
469 ClassLinker* class_linker = runtime->GetClassLinker();
470
471 // Make a list of classes we would like to prune.
472 std::set<std::string> non_image_classes;
473 NonImageClasses context;
474 context.image_writer = this;
475 context.non_image_classes = &non_image_classes;
476 class_linker->VisitClasses(NonImageClassesVisitor, &context);
477
478 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700479 for (const std::string& it : non_image_classes) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800480 bool result = class_linker->RemoveClass(it.c_str(), NULL);
481 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700482 }
483
484 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700485 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700486 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
487 size_t dex_cache_count = class_linker->GetDexCacheCount();
488 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
489 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700490 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
491 Class* klass = dex_cache->GetResolvedType(i);
492 if (klass != NULL && !IsImageClass(klass)) {
493 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700494 }
495 }
496 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700497 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700498 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
499 dex_cache->SetResolvedMethod(i, resolution_method);
500 }
501 }
502 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700503 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700504 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
505 dex_cache->SetResolvedField(i, NULL);
506 }
507 }
508 }
509}
510
511bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
512 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
513 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700514 std::string temp;
515 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700516 }
517 return true;
518}
519
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800520void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700521 if (compiler_driver_.GetImageClasses() != nullptr) {
522 gc::Heap* heap = Runtime::Current()->GetHeap();
523 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
524 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700525 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700526}
527
528void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
529 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700530 if (obj->IsClass()) {
531 Class* klass = obj->AsClass();
532 if (!image_writer->IsImageClass(klass)) {
533 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700534 std::string temp;
535 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700536 << " " << PrettyDescriptor(klass);
537 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700538 }
539}
540
541void ImageWriter::DumpImageClasses() {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700542 const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700543 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700544 for (const std::string& image_class : *image_classes) {
545 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700546 }
547}
548
Mathieu Chartier590fee92013-09-13 13:46:47 -0700549void ImageWriter::CalculateObjectOffsets(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700550 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700551 // if it is a string, we want to intern it if its not interned.
552 if (obj->GetClass()->IsStringClass()) {
553 // we must be an interned string that was forward referenced and already assigned
Mathieu Chartier590fee92013-09-13 13:46:47 -0700554 if (IsImageOffsetAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700555 DCHECK_EQ(obj, obj->AsString()->Intern());
556 return;
557 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700558 mirror::String* const interned = obj->AsString()->Intern();
559 if (obj != interned) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700560 if (!IsImageOffsetAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700561 // interned obj is after us, allocate its location early
Mathieu Chartier590fee92013-09-13 13:46:47 -0700562 AssignImageOffset(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700563 }
564 // point those looking for this object to the interned version.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700565 SetImageOffset(obj, GetImageOffset(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700566 return;
567 }
568 // else (obj == interned), nothing to do but fall through to the normal case
569 }
570
Mathieu Chartier590fee92013-09-13 13:46:47 -0700571 AssignImageOffset(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700572}
573
574ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
575 Runtime* runtime = Runtime::Current();
576 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700577 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700578 StackHandleScope<3> hs(self);
579 Handle<Class> object_array_class(hs.NewHandle(
580 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700581
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700582 // build an Object[] of all the DexCaches used in the source_space_.
583 // Since we can't hold the dex lock when allocating the dex_caches
584 // ObjectArray, we lock the dex lock twice, first to get the number
585 // of dex caches first and then lock it again to copy the dex
586 // caches. We check that the number of dex caches does not change.
587 size_t dex_cache_count;
588 {
589 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
590 dex_cache_count = class_linker->GetDexCacheCount();
591 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700592 Handle<ObjectArray<Object>> dex_caches(
593 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700594 dex_cache_count)));
595 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
596 {
597 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
598 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
599 << "The number of dex caches changed.";
600 for (size_t i = 0; i < dex_cache_count; ++i) {
601 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
602 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700603 }
604
605 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700606 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700607 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100608 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
609 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700610 image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
611 runtime->GetImtUnimplementedMethod());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100612 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
613 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
614 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
615 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
616 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
617 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
618 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700619 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100620 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700621 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
622 CHECK(image_roots->Get(i) != NULL);
623 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700624 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700625}
626
Mathieu Chartier590fee92013-09-13 13:46:47 -0700627// Walk instance fields of the given Class. Separate function to allow recursion on the super
628// class.
629void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
630 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700631 StackHandleScope<1> hs(Thread::Current());
632 Handle<mirror::Class> h_class(hs.NewHandle(klass));
633 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700634 if (super != nullptr) {
635 WalkInstanceFields(obj, super);
636 }
637 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700638 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000639 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700640 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700641 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700642 if (value != nullptr) {
643 WalkFieldsInOrder(value);
644 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000645 field_offset = MemberOffset(field_offset.Uint32Value() +
646 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700647 }
648}
649
650// For an unvisited object, visit it then all its children found via fields.
651void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
652 if (!IsImageOffsetAssigned(obj)) {
653 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700654 StackHandleScope<2> hs(Thread::Current());
655 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
656 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700657 // visit the object itself.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700658 CalculateObjectOffsets(h_obj.Get());
659 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700660 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700661 if (h_obj->IsClass()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700662 size_t num_static_fields = klass->NumReferenceStaticFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000663 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700664 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700665 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700666 if (value != nullptr) {
667 WalkFieldsInOrder(value);
668 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000669 field_offset = MemberOffset(field_offset.Uint32Value() +
670 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700671 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700672 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700673 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700674 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700675 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700676 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700677 mirror::Object* value = obj_array->Get(i);
678 if (value != nullptr) {
679 WalkFieldsInOrder(value);
680 }
681 }
682 }
683 }
684}
685
686void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
687 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
688 DCHECK(writer != nullptr);
689 writer->WalkFieldsInOrder(obj);
690}
691
Vladimir Markof4da6752014-08-01 19:04:18 +0100692void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700693 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700694 StackHandleScope<1> hs(self);
695 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700696
697 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700698 DCHECK_EQ(0U, image_end_);
699
Mathieu Chartier31e89252013-08-28 11:29:12 -0700700 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700701 // know where image_roots is going to end up
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700702 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700703
704 {
705 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700706 // TODO: Image spaces only?
Mathieu Chartier590fee92013-09-13 13:46:47 -0700707 DCHECK_LT(image_end_, image_->Size());
708 // Clear any pre-existing monitors which may have been in the monitor words.
709 heap->VisitObjects(WalkFieldsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700710 }
711
Vladimir Markof4da6752014-08-01 19:04:18 +0100712 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
713
714 // Note that image_end_ is left at end of used space
715}
716
717void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
718 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -0700719 const uint8_t* oat_file_begin = GetOatFileBegin();
720 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700721 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -0700722 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700723
Mathieu Chartier31e89252013-08-28 11:29:12 -0700724 // Return to write header at start of image with future location of image_roots. At this point,
725 // image_end_ is the size of the image (excluding bitmaps).
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700726 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800727 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
728 heap_bytes_per_bitmap_byte;
Vladimir Markof4da6752014-08-01 19:04:18 +0100729 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
730 static_cast<uint32_t>(image_end_),
731 RoundUp(image_end_, kPageSize),
732 RoundUp(bitmap_bytes, kPageSize),
733 image_roots_address_,
734 oat_file_->GetOatHeader().GetChecksum(),
735 PointerToLowMemUInt32(oat_file_begin),
736 PointerToLowMemUInt32(oat_data_begin_),
737 PointerToLowMemUInt32(oat_data_end),
Igor Murashkin46774762014-10-22 11:37:02 -0700738 PointerToLowMemUInt32(oat_file_end),
739 compile_pic_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700740}
741
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800742void ImageWriter::CopyAndFixupObjects() {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -0700743 ScopedAssertNoThreadSuspension ants(Thread::Current(), "ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700744 gc::Heap* heap = Runtime::Current()->GetHeap();
745 // TODO: heap validation can't handle this fix up pass
746 heap->DisableObjectValidation();
747 // TODO: Image spaces only?
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -0700748 WriterMutexLock mu(ants.Self(), *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700749 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
750 // Fix up the object previously had hash codes.
751 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700752 hash_pair.first->SetLockWord(LockWord::FromHashCode(hash_pair.second), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700753 }
754 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700755}
756
Mathieu Chartier590fee92013-09-13 13:46:47 -0700757void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700758 DCHECK(obj != nullptr);
759 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700760 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700761 // see GetLocalAddress for similar computation
762 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers13735952014-10-08 12:43:28 -0700763 uint8_t* dst = image_writer->image_->Begin() + offset;
764 const uint8_t* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800765 size_t n;
766 if (obj->IsArtMethod()) {
767 // Size without pointer fields since we don't want to overrun the buffer if target art method
768 // is 32 bits but source is 64 bits.
769 n = mirror::ArtMethod::SizeWithoutPointerFields();
770 } else {
771 n = obj->SizeOf();
772 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700773 DCHECK_LT(offset + n, image_writer->image_->Size());
774 memcpy(dst, src, n);
775 Object* copy = reinterpret_cast<Object*>(dst);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700776 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
777 // word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700778 copy->SetLockWord(LockWord(), false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700779 image_writer->FixupObject(obj, copy);
780}
781
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700782class FixupVisitor {
783 public:
784 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
785 }
786
787 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
788 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -0700789 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700790 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
791 // image.
792 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700793 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700794 }
795
796 // java.lang.ref.Reference visitor.
797 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
798 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
799 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
800 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700801 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700802 }
803
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700804 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700805 ImageWriter* const image_writer_;
806 mirror::Object* const copy_;
807};
808
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700809class FixupClassVisitor FINAL : public FixupVisitor {
810 public:
811 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
812 }
813
814 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
815 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
816 DCHECK(obj->IsClass());
817 FixupVisitor::operator()(obj, offset, false);
818
819 if (offset.Uint32Value() < mirror::Class::EmbeddedVTableOffset().Uint32Value()) {
820 return;
821 }
822 }
823
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700824 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
825 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700826 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
827 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
828 LOG(FATAL) << "Reference not expected here.";
829 }
830};
831
Ian Rogersef7d42f2014-01-06 12:55:46 -0800832void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700833 DCHECK(orig != nullptr);
834 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700835 if (kUseBakerOrBrooksReadBarrier) {
836 orig->AssertReadBarrierPointer();
837 if (kUseBrooksReadBarrier) {
838 // Note the address 'copy' isn't the same as the image address of 'orig'.
839 copy->SetReadBarrierPointer(GetImageAddress(orig));
840 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
841 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800842 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700843 if (orig->IsClass() && orig->AsClass()->ShouldHaveEmbeddedImtAndVTable()) {
844 FixupClassVisitor visitor(this, copy);
845 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
846 } else {
847 FixupVisitor visitor(this, copy);
848 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
849 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700850 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800851 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Mathieu Chartier2d721012014-11-10 11:08:06 -0800852 } else if (orig->IsClass() && orig->AsClass()->IsArtMethodClass()) {
853 // Set the right size for the target.
854 size_t size = mirror::ArtMethod::InstanceSize(target_ptr_size_);
855 down_cast<mirror::Class*>(copy)->SetObjectSizeWithoutChecks(size);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700856 }
857}
858
Ian Rogers13735952014-10-08 12:43:28 -0700859const uint8_t* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700860 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700861 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700862
863 // Use original code if it exists. Otherwise, set the code pointer to the resolution
864 // trampoline.
865
866 // Quick entrypoint:
Ian Rogers13735952014-10-08 12:43:28 -0700867 const uint8_t* quick_code = GetOatAddress(method->GetQuickOatCodeOffset());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700868 *quick_is_interpreted = false;
869 if (quick_code != nullptr &&
870 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
871 // We have code for a non-static or initialized method, just use the code.
872 } else if (quick_code == nullptr && method->IsNative() &&
873 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
874 // Non-static or initialized native method missing compiled code, use generic JNI version.
875 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
876 } else if (quick_code == nullptr && !method->IsNative()) {
877 // We don't have code at all for a non-native method, use the interpreter.
878 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
879 *quick_is_interpreted = true;
880 } else {
881 CHECK(!method->GetDeclaringClass()->IsInitialized());
882 // We have code for a static method, but need to go through the resolution stub for class
883 // initialization.
884 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
885 }
886 return quick_code;
887}
888
Ian Rogers13735952014-10-08 12:43:28 -0700889const uint8_t* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700890 // Calculate the quick entry point following the same logic as FixupMethod() below.
891 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700892 Runtime* runtime = Runtime::Current();
893 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700894 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700895 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
896 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700897 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
898 } else {
899 // We assume all methods have code. If they don't currently then we set them to the use the
900 // resolution trampoline. Abstract methods never have code and so we need to make sure their
901 // use results in an AbstractMethodError. We use the interpreter to achieve this.
902 if (UNLIKELY(method->IsAbstract())) {
903 return GetOatAddress(quick_to_interpreter_bridge_offset_);
904 } else {
905 bool quick_is_interpreted;
906 return GetQuickCode(method, &quick_is_interpreted);
907 }
908 }
909}
910
Ian Rogersef7d42f2014-01-06 12:55:46 -0800911void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -0700912 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
913 // oat_begin_
Mathieu Chartier2d721012014-11-10 11:08:06 -0800914 // For 64 bit targets we need to repack the current runtime pointer sized fields to the right
915 // locations.
916 // Copy all of the fields from the runtime methods to the target methods first since we did a
917 // bytewise copy earlier.
918 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
919 orig->GetEntryPointFromPortableCompiledCode(), target_ptr_size_);
920 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(orig->GetEntryPointFromInterpreter(),
921 target_ptr_size_);
922 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(orig->GetEntryPointFromJni(), target_ptr_size_);
923 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
924 orig->GetEntryPointFromQuickCompiledCode(), target_ptr_size_);
925 copy->SetNativeGcMapPtrSize<kVerifyNone>(orig->GetNativeGcMap(), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700926
Ian Rogers848871b2013-08-05 10:56:33 -0700927 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700928 Runtime* runtime = Runtime::Current();
929 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800930 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
931 GetOatAddress(portable_resolution_trampoline_offset_), target_ptr_size_);
932 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
933 GetOatAddress(quick_resolution_trampoline_offset_), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700934 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
935 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800936 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
937 GetOatAddress(portable_imt_conflict_trampoline_offset_), target_ptr_size_);
938 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
939 GetOatAddress(quick_imt_conflict_trampoline_offset_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700940 } else {
Ian Rogers848871b2013-08-05 10:56:33 -0700941 // We assume all methods have code. If they don't currently then we set them to the use the
942 // resolution trampoline. Abstract methods never have code and so we need to make sure their
943 // use results in an AbstractMethodError. We use the interpreter to achieve this.
944 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800945 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
946 GetOatAddress(portable_to_interpreter_bridge_offset_), target_ptr_size_);
947 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
948 GetOatAddress(quick_to_interpreter_bridge_offset_), target_ptr_size_);
949 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
950 reinterpret_cast<EntryPointFromInterpreter*>(const_cast<uint8_t*>(
951 GetOatAddress(interpreter_to_interpreter_bridge_offset_))), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -0700952 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700953 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -0700954 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800955 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +0200956
957 // Portable entrypoint:
Ian Rogers13735952014-10-08 12:43:28 -0700958 const uint8_t* portable_code = GetOatAddress(orig->GetPortableOatCodeOffset());
Sebastien Hertze1d07812014-05-21 15:44:09 +0200959 bool portable_is_interpreted = false;
960 if (portable_code != nullptr &&
961 (!orig->IsStatic() || orig->IsConstructor() || orig->GetDeclaringClass()->IsInitialized())) {
962 // We have code for a non-static or initialized method, just use the code.
963 } else if (portable_code == nullptr && orig->IsNative() &&
964 (!orig->IsStatic() || orig->GetDeclaringClass()->IsInitialized())) {
965 // Non-static or initialized native method missing compiled code, use generic JNI version.
966 // TODO: generic JNI support for LLVM.
967 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
968 } else if (portable_code == nullptr && !orig->IsNative()) {
969 // We don't have code at all for a non-native method, use the interpreter.
970 portable_code = GetOatAddress(portable_to_interpreter_bridge_offset_);
971 portable_is_interpreted = true;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800972 } else {
Sebastien Hertze1d07812014-05-21 15:44:09 +0200973 CHECK(!orig->GetDeclaringClass()->IsInitialized());
974 // We have code for a static method, but need to go through the resolution stub for class
975 // initialization.
976 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
Ian Rogers848871b2013-08-05 10:56:33 -0700977 }
Mathieu Chartier2d721012014-11-10 11:08:06 -0800978 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
979 portable_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +0200980 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -0700981 if (orig->IsNative()) {
982 // The native method's pointer is set to a stub to lookup via dlsym.
983 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier2d721012014-11-10 11:08:06 -0800984 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_),
985 target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -0700986 } else {
987 // Normal (non-abstract non-native) methods have various tables to relocate.
Ian Rogers848871b2013-08-05 10:56:33 -0700988 uint32_t native_gc_map_offset = orig->GetOatNativeGcMapOffset();
Ian Rogers13735952014-10-08 12:43:28 -0700989 const uint8_t* native_gc_map = GetOatAddress(native_gc_map_offset);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800990 copy->SetNativeGcMapPtrSize<kVerifyNone>(native_gc_map, target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -0700991 }
Sebastien Hertze1d07812014-05-21 15:44:09 +0200992
993 // Interpreter entrypoint:
994 // Set the interpreter entrypoint depending on whether there is compiled code or not.
995 uint32_t interpreter_code = (quick_is_interpreted && portable_is_interpreted)
996 ? interpreter_to_interpreter_bridge_offset_
997 : interpreter_to_compiled_code_bridge_offset_;
Mathieu Chartier2d721012014-11-10 11:08:06 -0800998 EntryPointFromInterpreter* interpreter_entrypoint =
Sebastien Hertze1d07812014-05-21 15:44:09 +0200999 reinterpret_cast<EntryPointFromInterpreter*>(
Mathieu Chartier2d721012014-11-10 11:08:06 -08001000 const_cast<uint8_t*>(GetOatAddress(interpreter_code)));
1001 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1002 interpreter_entrypoint, target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001003 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001004 }
1005}
1006
Alex Lighta59dd802014-07-02 16:28:08 -07001007static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001008 uint64_t data_sec_offset;
1009 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1010 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001011 return nullptr;
1012 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001013 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001014}
1015
Vladimir Markof4da6752014-08-01 19:04:18 +01001016void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001017 std::string error_msg;
1018 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
1019 MAP_SHARED, &error_msg));
1020 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001021 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001022 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001023 }
Alex Lighta59dd802014-07-02 16:28:08 -07001024 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1025 CHECK(oat_header != nullptr);
1026 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001027
Brian Carlstrom7940e442013-07-12 13:46:57 -07001028 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001029 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001030}
1031
1032} // namespace art