blob: b03727b0684bc368d876a509d12fb25b9613103b [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
Andreas Gampe4303ba92014-11-06 01:00:46 -0800152 if (oat_file->FlushCloseOrErase() != 0) {
153 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename << " for " << oat_location;
154 return false;
155 }
156
Ian Rogers700a4022014-05-19 16:49:03 -0700157 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700158 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700159 if (image_file.get() == NULL) {
160 LOG(ERROR) << "Failed to open image file " << image_filename;
161 return false;
162 }
163 if (fchmod(image_file->Fd(), 0644) != 0) {
164 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800165 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700166 return EXIT_FAILURE;
167 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700168
169 // Write out the image.
170 CHECK_EQ(image_end_, image_header->GetImageSize());
171 if (!image_file->WriteFully(image_->Begin(), image_end_)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700172 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800173 image_file->Erase();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700174 return false;
175 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700176
177 // Write out the image bitmap at the page aligned start of the image end.
178 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
179 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
180 image_header->GetImageBitmapSize(),
181 image_header->GetImageBitmapOffset())) {
182 PLOG(ERROR) << "Failed to write image file " << image_filename;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800183 image_file->Erase();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700184 return false;
185 }
186
Andreas Gampe4303ba92014-11-06 01:00:46 -0800187 if (image_file->FlushCloseOrErase() != 0) {
188 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
189 return false;
190 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700191 return true;
192}
193
Mathieu Chartier590fee92013-09-13 13:46:47 -0700194void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
195 DCHECK(object != nullptr);
196 DCHECK_NE(offset, 0U);
197 DCHECK(!IsImageOffsetAssigned(object));
198 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
199 DCHECK_ALIGNED(obj, kObjectAlignment);
200 image_bitmap_->Set(obj);
201 // Before we stomp over the lock word, save the hash code for later.
202 Monitor::Deflate(Thread::Current(), object);;
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700203 LockWord lw(object->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700204 switch (lw.GetState()) {
205 case LockWord::kFatLocked: {
206 LOG(FATAL) << "Fat locked object " << obj << " found during object copy";
207 break;
208 }
209 case LockWord::kThinLocked: {
210 LOG(FATAL) << "Thin locked object " << obj << " found during object copy";
211 break;
212 }
213 case LockWord::kUnlocked:
214 // No hash, don't need to save it.
215 break;
216 case LockWord::kHashCode:
217 saved_hashes_.push_back(std::make_pair(obj, lw.GetHashCode()));
218 break;
219 default:
220 LOG(FATAL) << "Unreachable.";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700221 UNREACHABLE();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700222 }
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700223 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700224 DCHECK(IsImageOffsetAssigned(object));
225}
226
227void ImageWriter::AssignImageOffset(mirror::Object* object) {
228 DCHECK(object != nullptr);
229 SetImageOffset(object, image_end_);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800230 size_t object_size;
231 if (object->IsArtMethod()) {
232 // Methods are sized based on the target pointer size.
233 object_size = mirror::ArtMethod::InstanceSize(target_ptr_size_);
234 } else {
235 object_size = object->SizeOf();
236 }
237 image_end_ += RoundUp(object_size, 8); // 64-bit alignment
Mathieu Chartier590fee92013-09-13 13:46:47 -0700238 DCHECK_LT(image_end_, image_->Size());
239}
240
Ian Rogersef7d42f2014-01-06 12:55:46 -0800241bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700242 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700243 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700244}
245
Ian Rogersef7d42f2014-01-06 12:55:46 -0800246size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700247 DCHECK(object != nullptr);
248 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700249 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700250 size_t offset = lock_word.ForwardingAddress();
251 DCHECK_LT(offset, image_end_);
252 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700253}
254
Brian Carlstrom7940e442013-07-12 13:46:57 -0700255bool ImageWriter::AllocMemory() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700256 size_t length = RoundUp(Runtime::Current()->GetHeap()->GetTotalMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700257 std::string error_msg;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700258 image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, PROT_READ | PROT_WRITE,
Ian Rogers3cd86d62014-08-14 08:53:12 -0700259 false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700260 if (UNLIKELY(image_.get() == nullptr)) {
261 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700262 return false;
263 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700264
265 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700266 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
267 length));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700268 if (image_bitmap_.get() == nullptr) {
269 LOG(ERROR) << "Failed to allocate memory for image bitmap";
270 return false;
271 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700272 return true;
273}
274
275void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700276 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700277 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
278}
279
280bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700281 Thread* self = Thread::Current();
282 StackHandleScope<1> hs(self);
283 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700284 return true;
285}
286
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800287// Count the number of strings in the heap and put the result in arg as a size_t pointer.
288static void CountStringsCallback(Object* obj, void* arg)
289 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
290 if (obj->GetClass()->IsStringClass()) {
291 ++*reinterpret_cast<size_t*>(arg);
292 }
293}
294
295// Collect all the java.lang.String in the heap and put them in the output strings_ array.
296class StringCollector {
297 public:
298 StringCollector(Handle<mirror::ObjectArray<mirror::String>> strings, size_t index)
299 : strings_(strings), index_(index) {
300 }
301 static void Callback(Object* obj, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
302 auto* collector = reinterpret_cast<StringCollector*>(arg);
303 if (obj->GetClass()->IsStringClass()) {
304 collector->strings_->SetWithoutChecks<false>(collector->index_++, obj->AsString());
305 }
306 }
307 size_t GetIndex() const {
308 return index_;
309 }
310
311 private:
312 Handle<mirror::ObjectArray<mirror::String>> strings_;
313 size_t index_;
314};
315
316// Compare strings based on length, used for sorting strings by length / reverse length.
317class StringLengthComparator {
318 public:
319 explicit StringLengthComparator(Handle<mirror::ObjectArray<mirror::String>> strings)
320 : strings_(strings) {
321 }
322 bool operator()(size_t a, size_t b) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
323 return strings_->GetWithoutChecks(a)->GetLength() < strings_->GetWithoutChecks(b)->GetLength();
324 }
325
326 private:
327 Handle<mirror::ObjectArray<mirror::String>> strings_;
328};
329
Mathieu Chartier88f21ca2014-11-18 14:13:58 -0800330// Normal string < comparison through the chars_ array.
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800331class SubstringComparator {
332 public:
333 explicit SubstringComparator(const std::vector<uint16_t>* const chars) : chars_(chars) {
334 }
335 bool operator()(const std::pair<size_t, size_t>& a, const std::pair<size_t, size_t>& b) {
Mathieu Chartier88f21ca2014-11-18 14:13:58 -0800336 return std::lexicographical_compare(chars_->begin() + a.first,
337 chars_->begin() + a.first + a.second,
338 chars_->begin() + b.first,
339 chars_->begin() + b.first + b.second);
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800340 }
341
342 private:
343 const std::vector<uint16_t>* const chars_;
344};
345
346void ImageWriter::ProcessStrings() {
347 size_t total_strings = 0;
348 gc::Heap* heap = Runtime::Current()->GetHeap();
349 ClassLinker* cl = Runtime::Current()->GetClassLinker();
350 {
351 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
352 heap->VisitObjects(CountStringsCallback, &total_strings); // Count the strings.
353 }
354 Thread* self = Thread::Current();
355 StackHandleScope<1> hs(self);
356 auto strings = hs.NewHandle(cl->AllocStringArray(self, total_strings));
357 StringCollector string_collector(strings, 0U);
358 {
359 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
360 // Read strings into the array.
361 heap->VisitObjects(StringCollector::Callback, &string_collector);
362 }
363 // Some strings could have gotten freed if AllocStringArray caused a GC.
364 CHECK_LE(string_collector.GetIndex(), total_strings);
365 total_strings = string_collector.GetIndex();
366 size_t total_length = 0;
367 std::vector<size_t> reverse_sorted_strings;
368 for (size_t i = 0; i < total_strings; ++i) {
369 mirror::String* s = strings->GetWithoutChecks(i);
370 // Look up the string in the array.
371 total_length += s->GetLength();
372 reverse_sorted_strings.push_back(i);
373 }
374 // Sort by reverse length.
375 StringLengthComparator comparator(strings);
376 std::sort(reverse_sorted_strings.rbegin(), reverse_sorted_strings.rend(), comparator);
377 // Deduplicate prefixes and add strings to the char array.
378 std::vector<uint16_t> combined_chars(total_length, 0U);
379 size_t num_chars = 0;
380 // Characters of strings which are non equal prefix of another string (not the same string).
381 // We don't count the savings from equal strings since these would get interned later anyways.
382 size_t prefix_saved_chars = 0;
383 std::set<std::pair<size_t, size_t>, SubstringComparator> existing_strings((
384 SubstringComparator(&combined_chars)));
385 for (size_t i = 0; i < total_strings; ++i) {
386 mirror::String* s = strings->GetWithoutChecks(reverse_sorted_strings[i]);
387 // Add the string to the end of the char array.
388 size_t length = s->GetLength();
389 for (size_t j = 0; j < length; ++j) {
390 combined_chars[num_chars++] = s->CharAt(j);
391 }
392 // Try to see if the string exists as a prefix of an existing string.
393 size_t new_offset = 0;
394 std::pair<size_t, size_t> new_string(num_chars - length, length);
Mathieu Chartier88f21ca2014-11-18 14:13:58 -0800395 auto it = existing_strings.lower_bound(new_string);
396 bool is_prefix = false;
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800397 if (it != existing_strings.end()) {
Mathieu Chartier88f21ca2014-11-18 14:13:58 -0800398 CHECK_LE(length, it->second);
399 is_prefix = std::equal(combined_chars.begin() + it->first,
400 combined_chars.begin() + it->first + it->second,
401 combined_chars.begin() + new_string.first);
402 }
403 if (is_prefix) {
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800404 // Shares a prefix, set the offset to where the new offset will be.
405 new_offset = it->first;
406 // Remove the added chars.
407 num_chars -= length;
408 if (it->second != length) {
409 prefix_saved_chars += length;
410 }
411 } else {
412 new_offset = new_string.first;
413 existing_strings.insert(new_string);
414 }
415 s->SetOffset(new_offset);
416 }
417 // Allocate and update the char arrays.
418 auto* array = mirror::CharArray::Alloc(self, num_chars);
419 for (size_t i = 0; i < num_chars; ++i) {
420 array->SetWithoutChecks<false>(i, combined_chars[i]);
421 }
422 for (size_t i = 0; i < total_strings; ++i) {
423 strings->GetWithoutChecks(i)->SetArray(array);
424 }
Mathieu Chartier88f21ca2014-11-18 14:13:58 -0800425 LOG(INFO) << "Total # image strings=" << total_strings << " combined length="
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800426 << total_length << " prefix saved chars=" << prefix_saved_chars;
427 ComputeEagerResolvedStrings();
428}
429
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700430void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700431 if (!obj->GetClass()->IsStringClass()) {
432 return;
433 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700434 mirror::String* string = obj->AsString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700435 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700436 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
437 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
438 size_t dex_cache_count = class_linker->GetDexCacheCount();
439 for (size_t i = 0; i < dex_cache_count; ++i) {
440 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700441 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800442 const DexFile::StringId* string_id;
443 if (UNLIKELY(string->GetLength() == 0)) {
444 string_id = dex_file.FindStringId("");
445 } else {
446 string_id = dex_file.FindStringId(utf16_string);
447 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700448 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700449 // This string occurs in this dex file, assign the dex cache entry.
450 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
451 if (dex_cache->GetResolvedString(string_idx) == NULL) {
452 dex_cache->SetResolvedString(string_idx, string);
453 }
454 }
455 }
456}
457
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800458void ImageWriter::ComputeEagerResolvedStrings() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700459 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
460 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700461}
462
Ian Rogersef7d42f2014-01-06 12:55:46 -0800463bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700464 std::string temp;
465 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700466}
467
468struct NonImageClasses {
469 ImageWriter* image_writer;
470 std::set<std::string>* non_image_classes;
471};
472
473void ImageWriter::PruneNonImageClasses() {
474 if (compiler_driver_.GetImageClasses() == NULL) {
475 return;
476 }
477 Runtime* runtime = Runtime::Current();
478 ClassLinker* class_linker = runtime->GetClassLinker();
479
480 // Make a list of classes we would like to prune.
481 std::set<std::string> non_image_classes;
482 NonImageClasses context;
483 context.image_writer = this;
484 context.non_image_classes = &non_image_classes;
485 class_linker->VisitClasses(NonImageClassesVisitor, &context);
486
487 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700488 for (const std::string& it : non_image_classes) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800489 bool result = class_linker->RemoveClass(it.c_str(), NULL);
490 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700491 }
492
493 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700494 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700495 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
496 size_t dex_cache_count = class_linker->GetDexCacheCount();
497 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
498 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700499 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
500 Class* klass = dex_cache->GetResolvedType(i);
501 if (klass != NULL && !IsImageClass(klass)) {
502 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700503 }
504 }
505 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700506 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700507 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
508 dex_cache->SetResolvedMethod(i, resolution_method);
509 }
510 }
511 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700512 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700513 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
514 dex_cache->SetResolvedField(i, NULL);
515 }
516 }
517 }
518}
519
520bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
521 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
522 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700523 std::string temp;
524 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700525 }
526 return true;
527}
528
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800529void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700530 if (compiler_driver_.GetImageClasses() != nullptr) {
531 gc::Heap* heap = Runtime::Current()->GetHeap();
532 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
533 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700534 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700535}
536
537void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
538 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700539 if (obj->IsClass()) {
540 Class* klass = obj->AsClass();
541 if (!image_writer->IsImageClass(klass)) {
542 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700543 std::string temp;
544 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700545 << " " << PrettyDescriptor(klass);
546 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700547 }
548}
549
550void ImageWriter::DumpImageClasses() {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700551 const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700552 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700553 for (const std::string& image_class : *image_classes) {
554 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700555 }
556}
557
Mathieu Chartier590fee92013-09-13 13:46:47 -0700558void ImageWriter::CalculateObjectOffsets(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700559 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700560 // if it is a string, we want to intern it if its not interned.
561 if (obj->GetClass()->IsStringClass()) {
562 // we must be an interned string that was forward referenced and already assigned
Mathieu Chartier590fee92013-09-13 13:46:47 -0700563 if (IsImageOffsetAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700564 DCHECK_EQ(obj, obj->AsString()->Intern());
565 return;
566 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700567 mirror::String* const interned = obj->AsString()->Intern();
568 if (obj != interned) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700569 if (!IsImageOffsetAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700570 // interned obj is after us, allocate its location early
Mathieu Chartier590fee92013-09-13 13:46:47 -0700571 AssignImageOffset(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700572 }
573 // point those looking for this object to the interned version.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700574 SetImageOffset(obj, GetImageOffset(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700575 return;
576 }
577 // else (obj == interned), nothing to do but fall through to the normal case
578 }
579
Mathieu Chartier590fee92013-09-13 13:46:47 -0700580 AssignImageOffset(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700581}
582
583ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
584 Runtime* runtime = Runtime::Current();
585 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700586 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700587 StackHandleScope<3> hs(self);
588 Handle<Class> object_array_class(hs.NewHandle(
589 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700590
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700591 // build an Object[] of all the DexCaches used in the source_space_.
592 // Since we can't hold the dex lock when allocating the dex_caches
593 // ObjectArray, we lock the dex lock twice, first to get the number
594 // of dex caches first and then lock it again to copy the dex
595 // caches. We check that the number of dex caches does not change.
596 size_t dex_cache_count;
597 {
598 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
599 dex_cache_count = class_linker->GetDexCacheCount();
600 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700601 Handle<ObjectArray<Object>> dex_caches(
602 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700603 dex_cache_count)));
604 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
605 {
606 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
607 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
608 << "The number of dex caches changed.";
609 for (size_t i = 0; i < dex_cache_count; ++i) {
610 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
611 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700612 }
613
614 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700615 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700616 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100617 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
618 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700619 image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
620 runtime->GetImtUnimplementedMethod());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100621 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
622 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
623 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
624 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
625 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
626 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
627 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700628 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100629 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700630 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
631 CHECK(image_roots->Get(i) != NULL);
632 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700633 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700634}
635
Mathieu Chartier590fee92013-09-13 13:46:47 -0700636// Walk instance fields of the given Class. Separate function to allow recursion on the super
637// class.
638void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
639 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700640 StackHandleScope<1> hs(Thread::Current());
641 Handle<mirror::Class> h_class(hs.NewHandle(klass));
642 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700643 if (super != nullptr) {
644 WalkInstanceFields(obj, super);
645 }
646 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700647 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000648 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700649 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700650 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700651 if (value != nullptr) {
652 WalkFieldsInOrder(value);
653 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000654 field_offset = MemberOffset(field_offset.Uint32Value() +
655 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700656 }
657}
658
659// For an unvisited object, visit it then all its children found via fields.
660void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
661 if (!IsImageOffsetAssigned(obj)) {
662 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700663 StackHandleScope<2> hs(Thread::Current());
664 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
665 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700666 // visit the object itself.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700667 CalculateObjectOffsets(h_obj.Get());
668 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700669 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700670 if (h_obj->IsClass()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700671 size_t num_static_fields = klass->NumReferenceStaticFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000672 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700673 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700674 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700675 if (value != nullptr) {
676 WalkFieldsInOrder(value);
677 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000678 field_offset = MemberOffset(field_offset.Uint32Value() +
679 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700680 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700681 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700682 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700683 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700684 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700685 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700686 mirror::Object* value = obj_array->Get(i);
687 if (value != nullptr) {
688 WalkFieldsInOrder(value);
689 }
690 }
691 }
692 }
693}
694
695void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
696 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
697 DCHECK(writer != nullptr);
698 writer->WalkFieldsInOrder(obj);
699}
700
Vladimir Markof4da6752014-08-01 19:04:18 +0100701void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700702 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700703 StackHandleScope<1> hs(self);
704 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700705
706 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700707 DCHECK_EQ(0U, image_end_);
708
Mathieu Chartier31e89252013-08-28 11:29:12 -0700709 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700710 // know where image_roots is going to end up
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700711 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700712
713 {
714 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700715 // TODO: Image spaces only?
Mathieu Chartier590fee92013-09-13 13:46:47 -0700716 DCHECK_LT(image_end_, image_->Size());
717 // Clear any pre-existing monitors which may have been in the monitor words.
718 heap->VisitObjects(WalkFieldsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700719 }
720
Vladimir Markof4da6752014-08-01 19:04:18 +0100721 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
722
723 // Note that image_end_ is left at end of used space
724}
725
726void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
727 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -0700728 const uint8_t* oat_file_begin = GetOatFileBegin();
729 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700730 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -0700731 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700732
Mathieu Chartier31e89252013-08-28 11:29:12 -0700733 // Return to write header at start of image with future location of image_roots. At this point,
734 // image_end_ is the size of the image (excluding bitmaps).
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700735 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800736 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
737 heap_bytes_per_bitmap_byte;
Vladimir Markof4da6752014-08-01 19:04:18 +0100738 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
739 static_cast<uint32_t>(image_end_),
740 RoundUp(image_end_, kPageSize),
741 RoundUp(bitmap_bytes, kPageSize),
742 image_roots_address_,
743 oat_file_->GetOatHeader().GetChecksum(),
744 PointerToLowMemUInt32(oat_file_begin),
745 PointerToLowMemUInt32(oat_data_begin_),
746 PointerToLowMemUInt32(oat_data_end),
Igor Murashkin46774762014-10-22 11:37:02 -0700747 PointerToLowMemUInt32(oat_file_end),
748 compile_pic_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700749}
750
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800751void ImageWriter::CopyAndFixupObjects() {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -0700752 ScopedAssertNoThreadSuspension ants(Thread::Current(), "ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700753 gc::Heap* heap = Runtime::Current()->GetHeap();
754 // TODO: heap validation can't handle this fix up pass
755 heap->DisableObjectValidation();
756 // TODO: Image spaces only?
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -0700757 WriterMutexLock mu(ants.Self(), *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700758 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
759 // Fix up the object previously had hash codes.
760 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700761 hash_pair.first->SetLockWord(LockWord::FromHashCode(hash_pair.second), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700762 }
763 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700764}
765
Mathieu Chartier590fee92013-09-13 13:46:47 -0700766void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700767 DCHECK(obj != nullptr);
768 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700769 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700770 // see GetLocalAddress for similar computation
771 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers13735952014-10-08 12:43:28 -0700772 uint8_t* dst = image_writer->image_->Begin() + offset;
773 const uint8_t* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800774 size_t n;
775 if (obj->IsArtMethod()) {
776 // Size without pointer fields since we don't want to overrun the buffer if target art method
777 // is 32 bits but source is 64 bits.
778 n = mirror::ArtMethod::SizeWithoutPointerFields();
779 } else {
780 n = obj->SizeOf();
781 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700782 DCHECK_LT(offset + n, image_writer->image_->Size());
783 memcpy(dst, src, n);
784 Object* copy = reinterpret_cast<Object*>(dst);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700785 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
786 // word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700787 copy->SetLockWord(LockWord(), false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700788 image_writer->FixupObject(obj, copy);
789}
790
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700791class FixupVisitor {
792 public:
793 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
794 }
795
796 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
797 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -0700798 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700799 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
800 // image.
801 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700802 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700803 }
804
805 // java.lang.ref.Reference visitor.
806 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
807 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
808 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
809 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700810 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700811 }
812
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700813 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700814 ImageWriter* const image_writer_;
815 mirror::Object* const copy_;
816};
817
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700818class FixupClassVisitor FINAL : public FixupVisitor {
819 public:
820 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
821 }
822
823 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
824 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
825 DCHECK(obj->IsClass());
826 FixupVisitor::operator()(obj, offset, false);
827
828 if (offset.Uint32Value() < mirror::Class::EmbeddedVTableOffset().Uint32Value()) {
829 return;
830 }
831 }
832
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700833 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
834 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700835 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
836 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
837 LOG(FATAL) << "Reference not expected here.";
838 }
839};
840
Ian Rogersef7d42f2014-01-06 12:55:46 -0800841void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700842 DCHECK(orig != nullptr);
843 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700844 if (kUseBakerOrBrooksReadBarrier) {
845 orig->AssertReadBarrierPointer();
846 if (kUseBrooksReadBarrier) {
847 // Note the address 'copy' isn't the same as the image address of 'orig'.
848 copy->SetReadBarrierPointer(GetImageAddress(orig));
849 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
850 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800851 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700852 if (orig->IsClass() && orig->AsClass()->ShouldHaveEmbeddedImtAndVTable()) {
853 FixupClassVisitor visitor(this, copy);
854 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
855 } else {
856 FixupVisitor visitor(this, copy);
857 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
858 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700859 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800860 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Mathieu Chartier2d721012014-11-10 11:08:06 -0800861 } else if (orig->IsClass() && orig->AsClass()->IsArtMethodClass()) {
862 // Set the right size for the target.
863 size_t size = mirror::ArtMethod::InstanceSize(target_ptr_size_);
864 down_cast<mirror::Class*>(copy)->SetObjectSizeWithoutChecks(size);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700865 }
866}
867
Ian Rogers13735952014-10-08 12:43:28 -0700868const uint8_t* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700869 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700870 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700871
872 // Use original code if it exists. Otherwise, set the code pointer to the resolution
873 // trampoline.
874
875 // Quick entrypoint:
Ian Rogers13735952014-10-08 12:43:28 -0700876 const uint8_t* quick_code = GetOatAddress(method->GetQuickOatCodeOffset());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700877 *quick_is_interpreted = false;
878 if (quick_code != nullptr &&
879 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
880 // We have code for a non-static or initialized method, just use the code.
881 } else if (quick_code == nullptr && method->IsNative() &&
882 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
883 // Non-static or initialized native method missing compiled code, use generic JNI version.
884 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
885 } else if (quick_code == nullptr && !method->IsNative()) {
886 // We don't have code at all for a non-native method, use the interpreter.
887 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
888 *quick_is_interpreted = true;
889 } else {
890 CHECK(!method->GetDeclaringClass()->IsInitialized());
891 // We have code for a static method, but need to go through the resolution stub for class
892 // initialization.
893 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
894 }
895 return quick_code;
896}
897
Ian Rogers13735952014-10-08 12:43:28 -0700898const uint8_t* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700899 // Calculate the quick entry point following the same logic as FixupMethod() below.
900 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700901 Runtime* runtime = Runtime::Current();
902 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700903 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700904 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
905 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700906 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
907 } else {
908 // We assume all methods have code. If they don't currently then we set them to the use the
909 // resolution trampoline. Abstract methods never have code and so we need to make sure their
910 // use results in an AbstractMethodError. We use the interpreter to achieve this.
911 if (UNLIKELY(method->IsAbstract())) {
912 return GetOatAddress(quick_to_interpreter_bridge_offset_);
913 } else {
914 bool quick_is_interpreted;
915 return GetQuickCode(method, &quick_is_interpreted);
916 }
917 }
918}
919
Ian Rogersef7d42f2014-01-06 12:55:46 -0800920void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -0700921 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
922 // oat_begin_
Mathieu Chartier2d721012014-11-10 11:08:06 -0800923 // For 64 bit targets we need to repack the current runtime pointer sized fields to the right
924 // locations.
925 // Copy all of the fields from the runtime methods to the target methods first since we did a
926 // bytewise copy earlier.
927 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
928 orig->GetEntryPointFromPortableCompiledCode(), target_ptr_size_);
929 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(orig->GetEntryPointFromInterpreter(),
930 target_ptr_size_);
931 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(orig->GetEntryPointFromJni(), target_ptr_size_);
932 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
933 orig->GetEntryPointFromQuickCompiledCode(), target_ptr_size_);
934 copy->SetNativeGcMapPtrSize<kVerifyNone>(orig->GetNativeGcMap(), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700935
Ian Rogers848871b2013-08-05 10:56:33 -0700936 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700937 Runtime* runtime = Runtime::Current();
938 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800939 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
940 GetOatAddress(portable_resolution_trampoline_offset_), target_ptr_size_);
941 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
942 GetOatAddress(quick_resolution_trampoline_offset_), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700943 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
944 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800945 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
946 GetOatAddress(portable_imt_conflict_trampoline_offset_), target_ptr_size_);
947 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
948 GetOatAddress(quick_imt_conflict_trampoline_offset_), target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700949 } else {
Ian Rogers848871b2013-08-05 10:56:33 -0700950 // We assume all methods have code. If they don't currently then we set them to the use the
951 // resolution trampoline. Abstract methods never have code and so we need to make sure their
952 // use results in an AbstractMethodError. We use the interpreter to achieve this.
953 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800954 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
955 GetOatAddress(portable_to_interpreter_bridge_offset_), target_ptr_size_);
956 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(
957 GetOatAddress(quick_to_interpreter_bridge_offset_), target_ptr_size_);
958 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
959 reinterpret_cast<EntryPointFromInterpreter*>(const_cast<uint8_t*>(
960 GetOatAddress(interpreter_to_interpreter_bridge_offset_))), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -0700961 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700962 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -0700963 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800964 copy->SetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +0200965
966 // Portable entrypoint:
Ian Rogers13735952014-10-08 12:43:28 -0700967 const uint8_t* portable_code = GetOatAddress(orig->GetPortableOatCodeOffset());
Sebastien Hertze1d07812014-05-21 15:44:09 +0200968 bool portable_is_interpreted = false;
969 if (portable_code != nullptr &&
970 (!orig->IsStatic() || orig->IsConstructor() || orig->GetDeclaringClass()->IsInitialized())) {
971 // We have code for a non-static or initialized method, just use the code.
972 } else if (portable_code == nullptr && orig->IsNative() &&
973 (!orig->IsStatic() || orig->GetDeclaringClass()->IsInitialized())) {
974 // Non-static or initialized native method missing compiled code, use generic JNI version.
975 // TODO: generic JNI support for LLVM.
976 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
977 } else if (portable_code == nullptr && !orig->IsNative()) {
978 // We don't have code at all for a non-native method, use the interpreter.
979 portable_code = GetOatAddress(portable_to_interpreter_bridge_offset_);
980 portable_is_interpreted = true;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800981 } else {
Sebastien Hertze1d07812014-05-21 15:44:09 +0200982 CHECK(!orig->GetDeclaringClass()->IsInitialized());
983 // We have code for a static method, but need to go through the resolution stub for class
984 // initialization.
985 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
Ian Rogers848871b2013-08-05 10:56:33 -0700986 }
Mathieu Chartier2d721012014-11-10 11:08:06 -0800987 copy->SetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(
988 portable_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +0200989 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -0700990 if (orig->IsNative()) {
991 // The native method's pointer is set to a stub to lookup via dlsym.
992 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier2d721012014-11-10 11:08:06 -0800993 copy->SetEntryPointFromJniPtrSize<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_),
994 target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -0700995 } else {
996 // Normal (non-abstract non-native) methods have various tables to relocate.
Ian Rogers848871b2013-08-05 10:56:33 -0700997 uint32_t native_gc_map_offset = orig->GetOatNativeGcMapOffset();
Ian Rogers13735952014-10-08 12:43:28 -0700998 const uint8_t* native_gc_map = GetOatAddress(native_gc_map_offset);
Mathieu Chartier2d721012014-11-10 11:08:06 -0800999 copy->SetNativeGcMapPtrSize<kVerifyNone>(native_gc_map, target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001000 }
Sebastien Hertze1d07812014-05-21 15:44:09 +02001001
1002 // Interpreter entrypoint:
1003 // Set the interpreter entrypoint depending on whether there is compiled code or not.
1004 uint32_t interpreter_code = (quick_is_interpreted && portable_is_interpreted)
1005 ? interpreter_to_interpreter_bridge_offset_
1006 : interpreter_to_compiled_code_bridge_offset_;
Mathieu Chartier2d721012014-11-10 11:08:06 -08001007 EntryPointFromInterpreter* interpreter_entrypoint =
Sebastien Hertze1d07812014-05-21 15:44:09 +02001008 reinterpret_cast<EntryPointFromInterpreter*>(
Mathieu Chartier2d721012014-11-10 11:08:06 -08001009 const_cast<uint8_t*>(GetOatAddress(interpreter_code)));
1010 copy->SetEntryPointFromInterpreterPtrSize<kVerifyNone>(
1011 interpreter_entrypoint, target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07001012 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001013 }
1014}
1015
Alex Lighta59dd802014-07-02 16:28:08 -07001016static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07001017 uint64_t data_sec_offset;
1018 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
1019 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07001020 return nullptr;
1021 }
Tong Shen62d1ca32014-09-03 17:24:56 -07001022 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08001023}
1024
Vladimir Markof4da6752014-08-01 19:04:18 +01001025void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07001026 std::string error_msg;
1027 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
1028 MAP_SHARED, &error_msg));
1029 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001030 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07001031 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001032 }
Alex Lighta59dd802014-07-02 16:28:08 -07001033 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
1034 CHECK(oat_header != nullptr);
1035 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001036
Brian Carlstrom7940e442013-07-12 13:46:57 -07001037 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07001038 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001039}
1040
1041} // namespace art