blob: 6096625aa1df2c8a4cdb1cfb73250049926a9f58 [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() {
71 {
72 Thread::Current()->TransitionFromSuspendedToRunnable();
73 PruneNonImageClasses(); // Remove junk
74 ComputeLazyFieldsForImageClasses(); // Add useful information
Vladimir Markof4da6752014-08-01 19:04:18 +010075 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
76 }
77 gc::Heap* heap = Runtime::Current()->GetHeap();
78 heap->CollectGarbage(false); // Remove garbage.
79
80 if (!AllocMemory()) {
81 return false;
82 }
83
84 if (kIsDebugBuild) {
85 ScopedObjectAccess soa(Thread::Current());
86 CheckNonImageClassesRemoved();
87 }
88
89 Thread::Current()->TransitionFromSuspendedToRunnable();
90 CalculateNewObjectOffsets();
91 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
92
93 return true;
94}
95
Brian Carlstrom7940e442013-07-12 13:46:57 -070096bool ImageWriter::Write(const std::string& image_filename,
Brian Carlstrom7940e442013-07-12 13:46:57 -070097 const std::string& oat_filename,
98 const std::string& oat_location) {
99 CHECK(!image_filename.empty());
100
Brian Carlstrom7940e442013-07-12 13:46:57 -0700101 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700102
Ian Rogers700a4022014-05-19 16:49:03 -0700103 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700104 if (oat_file.get() == NULL) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800105 PLOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700106 return false;
107 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700108 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -0700109 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, &error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700110 if (oat_file_ == nullptr) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800111 PLOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700112 << ": " << error_msg;
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700113 return false;
114 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700115 CHECK_EQ(class_linker->RegisterOatFile(oat_file_), oat_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700116
Ian Rogers848871b2013-08-05 10:56:33 -0700117 interpreter_to_interpreter_bridge_offset_ =
118 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
119 interpreter_to_compiled_code_bridge_offset_ =
120 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
121
122 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
123
Jeff Hao88474b42013-10-23 16:24:40 -0700124 portable_imt_conflict_trampoline_offset_ =
125 oat_file_->GetOatHeader().GetPortableImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700126 portable_resolution_trampoline_offset_ =
127 oat_file_->GetOatHeader().GetPortableResolutionTrampolineOffset();
128 portable_to_interpreter_bridge_offset_ =
129 oat_file_->GetOatHeader().GetPortableToInterpreterBridgeOffset();
130
Andreas Gampe2da88232014-02-27 12:26:20 -0800131 quick_generic_jni_trampoline_offset_ =
132 oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
Jeff Hao88474b42013-10-23 16:24:40 -0700133 quick_imt_conflict_trampoline_offset_ =
134 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700135 quick_resolution_trampoline_offset_ =
136 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
137 quick_to_interpreter_bridge_offset_ =
138 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700139
Brian Carlstrom7940e442013-07-12 13:46:57 -0700140 size_t oat_loaded_size = 0;
141 size_t oat_data_offset = 0;
142 ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
Alex Light53cb16b2014-06-12 11:26:29 -0700143
Vladimir Markof4da6752014-08-01 19:04:18 +0100144 Thread::Current()->TransitionFromSuspendedToRunnable();
145 CreateHeader(oat_loaded_size, oat_data_offset);
146 CopyAndFixupObjects();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700147 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
148
Vladimir Markof4da6752014-08-01 19:04:18 +0100149 SetOatChecksumFromElfFile(oat_file.get());
150
Ian Rogers700a4022014-05-19 16:49:03 -0700151 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700152 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700153 if (image_file.get() == NULL) {
154 LOG(ERROR) << "Failed to open image file " << image_filename;
155 return false;
156 }
157 if (fchmod(image_file->Fd(), 0644) != 0) {
158 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
159 return EXIT_FAILURE;
160 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700161
162 // Write out the image.
163 CHECK_EQ(image_end_, image_header->GetImageSize());
164 if (!image_file->WriteFully(image_->Begin(), image_end_)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700165 PLOG(ERROR) << "Failed to write image file " << image_filename;
166 return false;
167 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700168
169 // Write out the image bitmap at the page aligned start of the image end.
170 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
171 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
172 image_header->GetImageBitmapSize(),
173 image_header->GetImageBitmapOffset())) {
174 PLOG(ERROR) << "Failed to write image file " << image_filename;
175 return false;
176 }
177
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 return true;
179}
180
Mathieu Chartier590fee92013-09-13 13:46:47 -0700181void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
182 DCHECK(object != nullptr);
183 DCHECK_NE(offset, 0U);
184 DCHECK(!IsImageOffsetAssigned(object));
185 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
186 DCHECK_ALIGNED(obj, kObjectAlignment);
187 image_bitmap_->Set(obj);
188 // Before we stomp over the lock word, save the hash code for later.
189 Monitor::Deflate(Thread::Current(), object);;
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700190 LockWord lw(object->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700191 switch (lw.GetState()) {
192 case LockWord::kFatLocked: {
193 LOG(FATAL) << "Fat locked object " << obj << " found during object copy";
194 break;
195 }
196 case LockWord::kThinLocked: {
197 LOG(FATAL) << "Thin locked object " << obj << " found during object copy";
198 break;
199 }
200 case LockWord::kUnlocked:
201 // No hash, don't need to save it.
202 break;
203 case LockWord::kHashCode:
204 saved_hashes_.push_back(std::make_pair(obj, lw.GetHashCode()));
205 break;
206 default:
207 LOG(FATAL) << "Unreachable.";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700208 UNREACHABLE();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700209 }
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700210 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700211 DCHECK(IsImageOffsetAssigned(object));
212}
213
214void ImageWriter::AssignImageOffset(mirror::Object* object) {
215 DCHECK(object != nullptr);
216 SetImageOffset(object, image_end_);
217 image_end_ += RoundUp(object->SizeOf(), 8); // 64-bit alignment
218 DCHECK_LT(image_end_, image_->Size());
219}
220
Ian Rogersef7d42f2014-01-06 12:55:46 -0800221bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700222 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700223 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700224}
225
Ian Rogersef7d42f2014-01-06 12:55:46 -0800226size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700227 DCHECK(object != nullptr);
228 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700229 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700230 size_t offset = lock_word.ForwardingAddress();
231 DCHECK_LT(offset, image_end_);
232 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700233}
234
Brian Carlstrom7940e442013-07-12 13:46:57 -0700235bool ImageWriter::AllocMemory() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700236 size_t length = RoundUp(Runtime::Current()->GetHeap()->GetTotalMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700237 std::string error_msg;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700238 image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, PROT_READ | PROT_WRITE,
Ian Rogers3cd86d62014-08-14 08:53:12 -0700239 false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700240 if (UNLIKELY(image_.get() == nullptr)) {
241 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700242 return false;
243 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700244
245 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700246 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
247 length));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700248 if (image_bitmap_.get() == nullptr) {
249 LOG(ERROR) << "Failed to allocate memory for image bitmap";
250 return false;
251 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700252 return true;
253}
254
255void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700256 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700257 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
258}
259
260bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700261 Thread* self = Thread::Current();
262 StackHandleScope<1> hs(self);
263 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700264 return true;
265}
266
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800267// Count the number of strings in the heap and put the result in arg as a size_t pointer.
268static void CountStringsCallback(Object* obj, void* arg)
269 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
270 if (obj->GetClass()->IsStringClass()) {
271 ++*reinterpret_cast<size_t*>(arg);
272 }
273}
274
275// Collect all the java.lang.String in the heap and put them in the output strings_ array.
276class StringCollector {
277 public:
278 StringCollector(Handle<mirror::ObjectArray<mirror::String>> strings, size_t index)
279 : strings_(strings), index_(index) {
280 }
281 static void Callback(Object* obj, void* arg) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
282 auto* collector = reinterpret_cast<StringCollector*>(arg);
283 if (obj->GetClass()->IsStringClass()) {
284 collector->strings_->SetWithoutChecks<false>(collector->index_++, obj->AsString());
285 }
286 }
287 size_t GetIndex() const {
288 return index_;
289 }
290
291 private:
292 Handle<mirror::ObjectArray<mirror::String>> strings_;
293 size_t index_;
294};
295
296// Compare strings based on length, used for sorting strings by length / reverse length.
297class StringLengthComparator {
298 public:
299 explicit StringLengthComparator(Handle<mirror::ObjectArray<mirror::String>> strings)
300 : strings_(strings) {
301 }
302 bool operator()(size_t a, size_t b) const SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
303 return strings_->GetWithoutChecks(a)->GetLength() < strings_->GetWithoutChecks(b)->GetLength();
304 }
305
306 private:
307 Handle<mirror::ObjectArray<mirror::String>> strings_;
308};
309
310// If string a is a prefix of b or b is a prefix of a then they are considered equal. This
311// enables us to find prefixes instead of exact matches. Otherwise we do a normal string
312// comparison. The strings compared of the form <position, length> inside of the chars_ array.
313class SubstringComparator {
314 public:
315 explicit SubstringComparator(const std::vector<uint16_t>* const chars) : chars_(chars) {
316 }
317 bool operator()(const std::pair<size_t, size_t>& a, const std::pair<size_t, size_t>& b) {
318 size_t compare_length = std::min(a.second, b.second);
319 const uint16_t* ptr_a = &chars_->at(a.first);
320 const uint16_t* ptr_b = &chars_->at(b.first);
321 for (size_t i = 0; i < compare_length; ++i) {
322 if (ptr_a[i] != ptr_b[i]) {
323 return ptr_a[i] < ptr_b[i];
324 }
325 }
326 return false;
327 }
328
329 private:
330 const std::vector<uint16_t>* const chars_;
331};
332
333void ImageWriter::ProcessStrings() {
334 size_t total_strings = 0;
335 gc::Heap* heap = Runtime::Current()->GetHeap();
336 ClassLinker* cl = Runtime::Current()->GetClassLinker();
337 {
338 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
339 heap->VisitObjects(CountStringsCallback, &total_strings); // Count the strings.
340 }
341 Thread* self = Thread::Current();
342 StackHandleScope<1> hs(self);
343 auto strings = hs.NewHandle(cl->AllocStringArray(self, total_strings));
344 StringCollector string_collector(strings, 0U);
345 {
346 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
347 // Read strings into the array.
348 heap->VisitObjects(StringCollector::Callback, &string_collector);
349 }
350 // Some strings could have gotten freed if AllocStringArray caused a GC.
351 CHECK_LE(string_collector.GetIndex(), total_strings);
352 total_strings = string_collector.GetIndex();
353 size_t total_length = 0;
354 std::vector<size_t> reverse_sorted_strings;
355 for (size_t i = 0; i < total_strings; ++i) {
356 mirror::String* s = strings->GetWithoutChecks(i);
357 // Look up the string in the array.
358 total_length += s->GetLength();
359 reverse_sorted_strings.push_back(i);
360 }
361 // Sort by reverse length.
362 StringLengthComparator comparator(strings);
363 std::sort(reverse_sorted_strings.rbegin(), reverse_sorted_strings.rend(), comparator);
364 // Deduplicate prefixes and add strings to the char array.
365 std::vector<uint16_t> combined_chars(total_length, 0U);
366 size_t num_chars = 0;
367 // Characters of strings which are non equal prefix of another string (not the same string).
368 // We don't count the savings from equal strings since these would get interned later anyways.
369 size_t prefix_saved_chars = 0;
370 std::set<std::pair<size_t, size_t>, SubstringComparator> existing_strings((
371 SubstringComparator(&combined_chars)));
372 for (size_t i = 0; i < total_strings; ++i) {
373 mirror::String* s = strings->GetWithoutChecks(reverse_sorted_strings[i]);
374 // Add the string to the end of the char array.
375 size_t length = s->GetLength();
376 for (size_t j = 0; j < length; ++j) {
377 combined_chars[num_chars++] = s->CharAt(j);
378 }
379 // Try to see if the string exists as a prefix of an existing string.
380 size_t new_offset = 0;
381 std::pair<size_t, size_t> new_string(num_chars - length, length);
382 auto it = existing_strings.find(new_string);
383 if (it != existing_strings.end()) {
384 for (size_t j = 0; j < length; ++j) {
385 DCHECK_EQ(combined_chars[it->first + j], s->CharAt(j));
386 }
387 // Shares a prefix, set the offset to where the new offset will be.
388 new_offset = it->first;
389 // Remove the added chars.
390 num_chars -= length;
391 if (it->second != length) {
392 prefix_saved_chars += length;
393 }
394 } else {
395 new_offset = new_string.first;
396 existing_strings.insert(new_string);
397 }
398 s->SetOffset(new_offset);
399 }
400 // Allocate and update the char arrays.
401 auto* array = mirror::CharArray::Alloc(self, num_chars);
402 for (size_t i = 0; i < num_chars; ++i) {
403 array->SetWithoutChecks<false>(i, combined_chars[i]);
404 }
405 for (size_t i = 0; i < total_strings; ++i) {
406 strings->GetWithoutChecks(i)->SetArray(array);
407 }
408 VLOG(compiler) << "Total # image strings=" << total_strings << " combined length="
409 << total_length << " prefix saved chars=" << prefix_saved_chars;
410 ComputeEagerResolvedStrings();
411}
412
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700413void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700414 if (!obj->GetClass()->IsStringClass()) {
415 return;
416 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700417 mirror::String* string = obj->AsString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700418 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700419 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
420 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
421 size_t dex_cache_count = class_linker->GetDexCacheCount();
422 for (size_t i = 0; i < dex_cache_count; ++i) {
423 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700424 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800425 const DexFile::StringId* string_id;
426 if (UNLIKELY(string->GetLength() == 0)) {
427 string_id = dex_file.FindStringId("");
428 } else {
429 string_id = dex_file.FindStringId(utf16_string);
430 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700431 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700432 // This string occurs in this dex file, assign the dex cache entry.
433 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
434 if (dex_cache->GetResolvedString(string_idx) == NULL) {
435 dex_cache->SetResolvedString(string_idx, string);
436 }
437 }
438 }
439}
440
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800441void ImageWriter::ComputeEagerResolvedStrings() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700442 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
443 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700444}
445
Ian Rogersef7d42f2014-01-06 12:55:46 -0800446bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700447 std::string temp;
448 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700449}
450
451struct NonImageClasses {
452 ImageWriter* image_writer;
453 std::set<std::string>* non_image_classes;
454};
455
456void ImageWriter::PruneNonImageClasses() {
457 if (compiler_driver_.GetImageClasses() == NULL) {
458 return;
459 }
460 Runtime* runtime = Runtime::Current();
461 ClassLinker* class_linker = runtime->GetClassLinker();
462
463 // Make a list of classes we would like to prune.
464 std::set<std::string> non_image_classes;
465 NonImageClasses context;
466 context.image_writer = this;
467 context.non_image_classes = &non_image_classes;
468 class_linker->VisitClasses(NonImageClassesVisitor, &context);
469
470 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700471 for (const std::string& it : non_image_classes) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800472 bool result = class_linker->RemoveClass(it.c_str(), NULL);
473 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700474 }
475
476 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700477 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700478 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
479 size_t dex_cache_count = class_linker->GetDexCacheCount();
480 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
481 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700482 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
483 Class* klass = dex_cache->GetResolvedType(i);
484 if (klass != NULL && !IsImageClass(klass)) {
485 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700486 }
487 }
488 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700489 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700490 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
491 dex_cache->SetResolvedMethod(i, resolution_method);
492 }
493 }
494 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700495 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700496 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
497 dex_cache->SetResolvedField(i, NULL);
498 }
499 }
500 }
501}
502
503bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
504 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
505 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700506 std::string temp;
507 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700508 }
509 return true;
510}
511
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800512void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700513 if (compiler_driver_.GetImageClasses() != nullptr) {
514 gc::Heap* heap = Runtime::Current()->GetHeap();
515 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
516 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700517 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700518}
519
520void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
521 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700522 if (obj->IsClass()) {
523 Class* klass = obj->AsClass();
524 if (!image_writer->IsImageClass(klass)) {
525 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700526 std::string temp;
527 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700528 << " " << PrettyDescriptor(klass);
529 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700530 }
531}
532
533void ImageWriter::DumpImageClasses() {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700534 const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700535 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700536 for (const std::string& image_class : *image_classes) {
537 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700538 }
539}
540
Mathieu Chartier590fee92013-09-13 13:46:47 -0700541void ImageWriter::CalculateObjectOffsets(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700542 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700543 // if it is a string, we want to intern it if its not interned.
544 if (obj->GetClass()->IsStringClass()) {
545 // we must be an interned string that was forward referenced and already assigned
Mathieu Chartier590fee92013-09-13 13:46:47 -0700546 if (IsImageOffsetAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700547 DCHECK_EQ(obj, obj->AsString()->Intern());
548 return;
549 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700550 mirror::String* const interned = obj->AsString()->Intern();
551 if (obj != interned) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700552 if (!IsImageOffsetAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700553 // interned obj is after us, allocate its location early
Mathieu Chartier590fee92013-09-13 13:46:47 -0700554 AssignImageOffset(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700555 }
556 // point those looking for this object to the interned version.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700557 SetImageOffset(obj, GetImageOffset(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700558 return;
559 }
560 // else (obj == interned), nothing to do but fall through to the normal case
561 }
562
Mathieu Chartier590fee92013-09-13 13:46:47 -0700563 AssignImageOffset(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700564}
565
566ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
567 Runtime* runtime = Runtime::Current();
568 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700569 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700570 StackHandleScope<3> hs(self);
571 Handle<Class> object_array_class(hs.NewHandle(
572 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700573
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700574 // build an Object[] of all the DexCaches used in the source_space_.
575 // Since we can't hold the dex lock when allocating the dex_caches
576 // ObjectArray, we lock the dex lock twice, first to get the number
577 // of dex caches first and then lock it again to copy the dex
578 // caches. We check that the number of dex caches does not change.
579 size_t dex_cache_count;
580 {
581 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
582 dex_cache_count = class_linker->GetDexCacheCount();
583 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700584 Handle<ObjectArray<Object>> dex_caches(
585 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700586 dex_cache_count)));
587 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
588 {
589 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
590 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
591 << "The number of dex caches changed.";
592 for (size_t i = 0; i < dex_cache_count; ++i) {
593 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
594 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700595 }
596
597 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700598 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700599 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100600 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
601 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700602 image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
603 runtime->GetImtUnimplementedMethod());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100604 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
605 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
606 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
607 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
608 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
609 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
610 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700611 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100612 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700613 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
614 CHECK(image_roots->Get(i) != NULL);
615 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700616 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700617}
618
Mathieu Chartier590fee92013-09-13 13:46:47 -0700619// Walk instance fields of the given Class. Separate function to allow recursion on the super
620// class.
621void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
622 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700623 StackHandleScope<1> hs(Thread::Current());
624 Handle<mirror::Class> h_class(hs.NewHandle(klass));
625 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700626 if (super != nullptr) {
627 WalkInstanceFields(obj, super);
628 }
629 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700630 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000631 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700632 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700633 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700634 if (value != nullptr) {
635 WalkFieldsInOrder(value);
636 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000637 field_offset = MemberOffset(field_offset.Uint32Value() +
638 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700639 }
640}
641
642// For an unvisited object, visit it then all its children found via fields.
643void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
644 if (!IsImageOffsetAssigned(obj)) {
645 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700646 StackHandleScope<2> hs(Thread::Current());
647 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
648 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700649 // visit the object itself.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700650 CalculateObjectOffsets(h_obj.Get());
651 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700652 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700653 if (h_obj->IsClass()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700654 size_t num_static_fields = klass->NumReferenceStaticFields();
Vladimir Marko76649e82014-11-10 18:32:59 +0000655 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700656 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700657 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700658 if (value != nullptr) {
659 WalkFieldsInOrder(value);
660 }
Vladimir Marko76649e82014-11-10 18:32:59 +0000661 field_offset = MemberOffset(field_offset.Uint32Value() +
662 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700663 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700664 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700665 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700666 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700667 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700668 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700669 mirror::Object* value = obj_array->Get(i);
670 if (value != nullptr) {
671 WalkFieldsInOrder(value);
672 }
673 }
674 }
675 }
676}
677
678void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
679 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
680 DCHECK(writer != nullptr);
681 writer->WalkFieldsInOrder(obj);
682}
683
Vladimir Markof4da6752014-08-01 19:04:18 +0100684void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700685 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700686 StackHandleScope<1> hs(self);
687 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700688
689 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700690 DCHECK_EQ(0U, image_end_);
691
Mathieu Chartier31e89252013-08-28 11:29:12 -0700692 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700693 // know where image_roots is going to end up
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700694 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700695
696 {
697 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700698 // TODO: Image spaces only?
Mathieu Chartier590fee92013-09-13 13:46:47 -0700699 DCHECK_LT(image_end_, image_->Size());
700 // Clear any pre-existing monitors which may have been in the monitor words.
701 heap->VisitObjects(WalkFieldsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700702 }
703
Vladimir Markof4da6752014-08-01 19:04:18 +0100704 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
705
706 // Note that image_end_ is left at end of used space
707}
708
709void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
710 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -0700711 const uint8_t* oat_file_begin = GetOatFileBegin();
712 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700713 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -0700714 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700715
Mathieu Chartier31e89252013-08-28 11:29:12 -0700716 // Return to write header at start of image with future location of image_roots. At this point,
717 // image_end_ is the size of the image (excluding bitmaps).
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700718 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800719 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
720 heap_bytes_per_bitmap_byte;
Vladimir Markof4da6752014-08-01 19:04:18 +0100721 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
722 static_cast<uint32_t>(image_end_),
723 RoundUp(image_end_, kPageSize),
724 RoundUp(bitmap_bytes, kPageSize),
725 image_roots_address_,
726 oat_file_->GetOatHeader().GetChecksum(),
727 PointerToLowMemUInt32(oat_file_begin),
728 PointerToLowMemUInt32(oat_data_begin_),
729 PointerToLowMemUInt32(oat_data_end),
Igor Murashkin46774762014-10-22 11:37:02 -0700730 PointerToLowMemUInt32(oat_file_end),
731 compile_pic_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700732}
733
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800734void ImageWriter::CopyAndFixupObjects() {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -0700735 ScopedAssertNoThreadSuspension ants(Thread::Current(), "ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700736 gc::Heap* heap = Runtime::Current()->GetHeap();
737 // TODO: heap validation can't handle this fix up pass
738 heap->DisableObjectValidation();
739 // TODO: Image spaces only?
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -0700740 WriterMutexLock mu(ants.Self(), *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700741 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
742 // Fix up the object previously had hash codes.
743 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700744 hash_pair.first->SetLockWord(LockWord::FromHashCode(hash_pair.second), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700745 }
746 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700747}
748
Mathieu Chartier590fee92013-09-13 13:46:47 -0700749void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700750 DCHECK(obj != nullptr);
751 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700752 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700753 // see GetLocalAddress for similar computation
754 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers13735952014-10-08 12:43:28 -0700755 uint8_t* dst = image_writer->image_->Begin() + offset;
756 const uint8_t* src = reinterpret_cast<const uint8_t*>(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700757 size_t n = obj->SizeOf();
758 DCHECK_LT(offset + n, image_writer->image_->Size());
759 memcpy(dst, src, n);
760 Object* copy = reinterpret_cast<Object*>(dst);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700761 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
762 // word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700763 copy->SetLockWord(LockWord(), false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700764 image_writer->FixupObject(obj, copy);
765}
766
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700767class FixupVisitor {
768 public:
769 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
770 }
771
772 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
773 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -0700774 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700775 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
776 // image.
777 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700778 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700779 }
780
781 // java.lang.ref.Reference visitor.
782 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
783 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
784 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
785 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700786 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700787 }
788
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700789 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700790 ImageWriter* const image_writer_;
791 mirror::Object* const copy_;
792};
793
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700794class FixupClassVisitor FINAL : public FixupVisitor {
795 public:
796 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
797 }
798
799 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
800 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
801 DCHECK(obj->IsClass());
802 FixupVisitor::operator()(obj, offset, false);
803
804 if (offset.Uint32Value() < mirror::Class::EmbeddedVTableOffset().Uint32Value()) {
805 return;
806 }
807 }
808
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700809 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
810 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700811 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
812 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
813 LOG(FATAL) << "Reference not expected here.";
814 }
815};
816
Ian Rogersef7d42f2014-01-06 12:55:46 -0800817void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700818 DCHECK(orig != nullptr);
819 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700820 if (kUseBakerOrBrooksReadBarrier) {
821 orig->AssertReadBarrierPointer();
822 if (kUseBrooksReadBarrier) {
823 // Note the address 'copy' isn't the same as the image address of 'orig'.
824 copy->SetReadBarrierPointer(GetImageAddress(orig));
825 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
826 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800827 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700828 if (orig->IsClass() && orig->AsClass()->ShouldHaveEmbeddedImtAndVTable()) {
829 FixupClassVisitor visitor(this, copy);
830 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
831 } else {
832 FixupVisitor visitor(this, copy);
833 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
834 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700835 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800836 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700837 }
838}
839
Ian Rogers13735952014-10-08 12:43:28 -0700840const uint8_t* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700841 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700842 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700843
844 // Use original code if it exists. Otherwise, set the code pointer to the resolution
845 // trampoline.
846
847 // Quick entrypoint:
Ian Rogers13735952014-10-08 12:43:28 -0700848 const uint8_t* quick_code = GetOatAddress(method->GetQuickOatCodeOffset());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700849 *quick_is_interpreted = false;
850 if (quick_code != nullptr &&
851 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
852 // We have code for a non-static or initialized method, just use the code.
853 } else if (quick_code == nullptr && method->IsNative() &&
854 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
855 // Non-static or initialized native method missing compiled code, use generic JNI version.
856 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
857 } else if (quick_code == nullptr && !method->IsNative()) {
858 // We don't have code at all for a non-native method, use the interpreter.
859 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
860 *quick_is_interpreted = true;
861 } else {
862 CHECK(!method->GetDeclaringClass()->IsInitialized());
863 // We have code for a static method, but need to go through the resolution stub for class
864 // initialization.
865 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
866 }
867 return quick_code;
868}
869
Ian Rogers13735952014-10-08 12:43:28 -0700870const uint8_t* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700871 // Calculate the quick entry point following the same logic as FixupMethod() below.
872 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700873 Runtime* runtime = Runtime::Current();
874 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700875 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700876 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
877 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700878 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
879 } else {
880 // We assume all methods have code. If they don't currently then we set them to the use the
881 // resolution trampoline. Abstract methods never have code and so we need to make sure their
882 // use results in an AbstractMethodError. We use the interpreter to achieve this.
883 if (UNLIKELY(method->IsAbstract())) {
884 return GetOatAddress(quick_to_interpreter_bridge_offset_);
885 } else {
886 bool quick_is_interpreted;
887 return GetQuickCode(method, &quick_is_interpreted);
888 }
889 }
890}
891
Ian Rogersef7d42f2014-01-06 12:55:46 -0800892void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -0700893 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
894 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -0700895
Ian Rogers848871b2013-08-05 10:56:33 -0700896 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700897 Runtime* runtime = Runtime::Current();
898 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800899 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_resolution_trampoline_offset_));
900 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_resolution_trampoline_offset_));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700901 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
902 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800903 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_imt_conflict_trampoline_offset_));
904 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_imt_conflict_trampoline_offset_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700905 } else {
Ian Rogers848871b2013-08-05 10:56:33 -0700906 // We assume all methods have code. If they don't currently then we set them to the use the
907 // resolution trampoline. Abstract methods never have code and so we need to make sure their
908 // use results in an AbstractMethodError. We use the interpreter to achieve this.
909 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800910 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_to_interpreter_bridge_offset_));
911 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_to_interpreter_bridge_offset_));
912 copy->SetEntryPointFromInterpreter<kVerifyNone>(reinterpret_cast<EntryPointFromInterpreter*>
Ian Rogers13735952014-10-08 12:43:28 -0700913 (const_cast<uint8_t*>(GetOatAddress(interpreter_to_interpreter_bridge_offset_))));
Ian Rogers848871b2013-08-05 10:56:33 -0700914 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700915 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -0700916 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Sebastien Hertze1d07812014-05-21 15:44:09 +0200917 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(quick_code);
918
919 // Portable entrypoint:
Ian Rogers13735952014-10-08 12:43:28 -0700920 const uint8_t* portable_code = GetOatAddress(orig->GetPortableOatCodeOffset());
Sebastien Hertze1d07812014-05-21 15:44:09 +0200921 bool portable_is_interpreted = false;
922 if (portable_code != nullptr &&
923 (!orig->IsStatic() || orig->IsConstructor() || orig->GetDeclaringClass()->IsInitialized())) {
924 // We have code for a non-static or initialized method, just use the code.
925 } else if (portable_code == nullptr && orig->IsNative() &&
926 (!orig->IsStatic() || orig->GetDeclaringClass()->IsInitialized())) {
927 // Non-static or initialized native method missing compiled code, use generic JNI version.
928 // TODO: generic JNI support for LLVM.
929 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
930 } else if (portable_code == nullptr && !orig->IsNative()) {
931 // We don't have code at all for a non-native method, use the interpreter.
932 portable_code = GetOatAddress(portable_to_interpreter_bridge_offset_);
933 portable_is_interpreted = true;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800934 } else {
Sebastien Hertze1d07812014-05-21 15:44:09 +0200935 CHECK(!orig->GetDeclaringClass()->IsInitialized());
936 // We have code for a static method, but need to go through the resolution stub for class
937 // initialization.
938 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
Ian Rogers848871b2013-08-05 10:56:33 -0700939 }
Sebastien Hertze1d07812014-05-21 15:44:09 +0200940 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(portable_code);
941
942 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -0700943 if (orig->IsNative()) {
944 // The native method's pointer is set to a stub to lookup via dlsym.
945 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800946 copy->SetNativeMethod<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_));
Ian Rogers848871b2013-08-05 10:56:33 -0700947 } else {
948 // Normal (non-abstract non-native) methods have various tables to relocate.
Ian Rogers848871b2013-08-05 10:56:33 -0700949 uint32_t native_gc_map_offset = orig->GetOatNativeGcMapOffset();
Ian Rogers13735952014-10-08 12:43:28 -0700950 const uint8_t* native_gc_map = GetOatAddress(native_gc_map_offset);
Mathieu Chartier4e305412014-02-19 10:54:44 -0800951 copy->SetNativeGcMap<kVerifyNone>(reinterpret_cast<const uint8_t*>(native_gc_map));
Ian Rogers848871b2013-08-05 10:56:33 -0700952 }
Sebastien Hertze1d07812014-05-21 15:44:09 +0200953
954 // Interpreter entrypoint:
955 // Set the interpreter entrypoint depending on whether there is compiled code or not.
956 uint32_t interpreter_code = (quick_is_interpreted && portable_is_interpreted)
957 ? interpreter_to_interpreter_bridge_offset_
958 : interpreter_to_compiled_code_bridge_offset_;
959 copy->SetEntryPointFromInterpreter<kVerifyNone>(
960 reinterpret_cast<EntryPointFromInterpreter*>(
Ian Rogers13735952014-10-08 12:43:28 -0700961 const_cast<uint8_t*>(GetOatAddress(interpreter_code))));
Ian Rogers848871b2013-08-05 10:56:33 -0700962 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700963 }
964}
965
Alex Lighta59dd802014-07-02 16:28:08 -0700966static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700967 uint64_t data_sec_offset;
968 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
969 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -0700970 return nullptr;
971 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700972 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800973}
974
Vladimir Markof4da6752014-08-01 19:04:18 +0100975void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700976 std::string error_msg;
977 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
978 MAP_SHARED, &error_msg));
979 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100980 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -0700981 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700982 }
Alex Lighta59dd802014-07-02 16:28:08 -0700983 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
984 CHECK(oat_header != nullptr);
985 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700986
Brian Carlstrom7940e442013-07-12 13:46:57 -0700987 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -0700988 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700989}
990
991} // namespace art