blob: af61bcc79a1497ce79039e33686a69d154c24b05 [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
21#include <vector>
22
23#include "base/logging.h"
24#include "base/unix_file/fd_file.h"
25#include "class_linker.h"
26#include "compiled_method.h"
27#include "dex_file-inl.h"
28#include "driver/compiler_driver.h"
29#include "elf_writer.h"
30#include "gc/accounting/card_table-inl.h"
31#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070032#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070033#include "gc/heap.h"
34#include "gc/space/large_object_space.h"
35#include "gc/space/space-inl.h"
36#include "globals.h"
37#include "image.h"
38#include "intern_table.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070039#include "mirror/art_field-inl.h"
40#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "mirror/array-inl.h"
42#include "mirror/class-inl.h"
43#include "mirror/class_loader.h"
44#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070045#include "mirror/object-inl.h"
46#include "mirror/object_array-inl.h"
47#include "oat.h"
48#include "oat_file.h"
49#include "object_utils.h"
50#include "runtime.h"
51#include "scoped_thread_state_change.h"
52#include "sirt_ref.h"
53#include "UniquePtr.h"
54#include "utils.h"
55
Brian Carlstromea46f952013-07-30 01:26:50 -070056using ::art::mirror::ArtField;
57using ::art::mirror::ArtMethod;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070058using ::art::mirror::Class;
59using ::art::mirror::DexCache;
60using ::art::mirror::EntryPointFromInterpreter;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070061using ::art::mirror::Object;
62using ::art::mirror::ObjectArray;
63using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070064
65namespace art {
66
67bool ImageWriter::Write(const std::string& image_filename,
68 uintptr_t image_begin,
69 const std::string& oat_filename,
70 const std::string& oat_location) {
71 CHECK(!image_filename.empty());
72
73 CHECK_NE(image_begin, 0U);
74 image_begin_ = reinterpret_cast<byte*>(image_begin);
75
76 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
77 const std::vector<DexCache*>& all_dex_caches = class_linker->GetDexCaches();
Mathieu Chartier02e25112013-08-14 16:14:24 -070078 dex_caches_.insert(all_dex_caches.begin(), all_dex_caches.end());
Brian Carlstrom7940e442013-07-12 13:46:57 -070079
Brian Carlstrom7571e8b2013-08-12 17:04:14 -070080 UniquePtr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -070081 if (oat_file.get() == NULL) {
82 LOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
83 return false;
84 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -070085 std::string error_msg;
86 oat_file_ = OatFile::OpenWritable(oat_file.get(), oat_location, &error_msg);
87 if (oat_file_ == nullptr) {
88 LOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
89 << ": " << error_msg;
Brian Carlstromc50d8e12013-07-23 22:35:16 -070090 return false;
91 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -070092 CHECK_EQ(class_linker->RegisterOatFile(oat_file_), oat_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -070093
Ian Rogers848871b2013-08-05 10:56:33 -070094 interpreter_to_interpreter_bridge_offset_ =
95 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
96 interpreter_to_compiled_code_bridge_offset_ =
97 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
98
99 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
100
Jeff Hao88474b42013-10-23 16:24:40 -0700101 portable_imt_conflict_trampoline_offset_ =
102 oat_file_->GetOatHeader().GetPortableImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700103 portable_resolution_trampoline_offset_ =
104 oat_file_->GetOatHeader().GetPortableResolutionTrampolineOffset();
105 portable_to_interpreter_bridge_offset_ =
106 oat_file_->GetOatHeader().GetPortableToInterpreterBridgeOffset();
107
Jeff Hao88474b42013-10-23 16:24:40 -0700108 quick_imt_conflict_trampoline_offset_ =
109 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700110 quick_resolution_trampoline_offset_ =
111 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
112 quick_to_interpreter_bridge_offset_ =
113 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700114 {
115 Thread::Current()->TransitionFromSuspendedToRunnable();
116 PruneNonImageClasses(); // Remove junk
117 ComputeLazyFieldsForImageClasses(); // Add useful information
118 ComputeEagerResolvedStrings();
119 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
120 }
121 gc::Heap* heap = Runtime::Current()->GetHeap();
122 heap->CollectGarbage(false); // Remove garbage.
123 // Trim size of alloc spaces.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700124 for (const auto& space : heap->GetContinuousSpaces()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700125 if (space->IsDlMallocSpace()) {
126 space->AsDlMallocSpace()->Trim();
127 }
128 }
129
130 if (!AllocMemory()) {
131 return false;
132 }
133#ifndef NDEBUG
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700134 { // NOLINT(whitespace/braces)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700135 ScopedObjectAccess soa(Thread::Current());
136 CheckNonImageClassesRemoved();
137 }
138#endif
139 Thread::Current()->TransitionFromSuspendedToRunnable();
140 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);
143 CalculateNewObjectOffsets(oat_loaded_size, oat_data_offset);
144 CopyAndFixupObjects();
145 PatchOatCodeAndMethods();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700146 // Record allocations into the image bitmap.
147 RecordImageAllocations();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700148 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
149
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700150 UniquePtr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700151 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700152 if (image_file.get() == NULL) {
153 LOG(ERROR) << "Failed to open image file " << image_filename;
154 return false;
155 }
156 if (fchmod(image_file->Fd(), 0644) != 0) {
157 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
158 return EXIT_FAILURE;
159 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700160
161 // Write out the image.
162 CHECK_EQ(image_end_, image_header->GetImageSize());
163 if (!image_file->WriteFully(image_->Begin(), image_end_)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700164 PLOG(ERROR) << "Failed to write image file " << image_filename;
165 return false;
166 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700167
168 // Write out the image bitmap at the page aligned start of the image end.
169 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
170 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
171 image_header->GetImageBitmapSize(),
172 image_header->GetImageBitmapOffset())) {
173 PLOG(ERROR) << "Failed to write image file " << image_filename;
174 return false;
175 }
176
Brian Carlstrom7940e442013-07-12 13:46:57 -0700177 return true;
178}
179
Mathieu Chartier31e89252013-08-28 11:29:12 -0700180void ImageWriter::RecordImageAllocations() {
181 uint64_t start_time = NanoTime();
182 CHECK(image_bitmap_.get() != nullptr);
183 for (const auto& it : offsets_) {
184 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + it.second);
185 DCHECK_ALIGNED(obj, kObjectAlignment);
186 image_bitmap_->Set(obj);
187 }
188 LOG(INFO) << "RecordImageAllocations took " << PrettyDuration(NanoTime() - start_time);
189}
190
Brian Carlstrom7940e442013-07-12 13:46:57 -0700191bool ImageWriter::AllocMemory() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700192 size_t size = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700193 for (const auto& space : Runtime::Current()->GetHeap()->GetContinuousSpaces()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700194 if (space->IsDlMallocSpace()) {
195 size += space->Size();
196 }
197 }
198
199 int prot = PROT_READ | PROT_WRITE;
200 size_t length = RoundUp(size, kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700201 std::string error_msg;
202 image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, prot, &error_msg));
203 if (UNLIKELY(image_.get() == nullptr)) {
204 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700205 return false;
206 }
207 return true;
208}
209
210void ImageWriter::ComputeLazyFieldsForImageClasses() {
211 Runtime* runtime = Runtime::Current();
212 ClassLinker* class_linker = runtime->GetClassLinker();
213 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
214}
215
216bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
217 c->ComputeName();
218 return true;
219}
220
221void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg) {
222 if (!obj->GetClass()->IsStringClass()) {
223 return;
224 }
225 String* string = obj->AsString();
226 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
227 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700228 for (DexCache* dex_cache : writer->dex_caches_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700229 const DexFile& dex_file = *dex_cache->GetDexFile();
230 const DexFile::StringId* string_id = dex_file.FindStringId(utf16_string);
231 if (string_id != NULL) {
232 // This string occurs in this dex file, assign the dex cache entry.
233 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
234 if (dex_cache->GetResolvedString(string_idx) == NULL) {
235 dex_cache->SetResolvedString(string_idx, string);
236 }
237 }
238 }
239}
240
241void ImageWriter::ComputeEagerResolvedStrings()
242 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
243 // TODO: Check image spaces only?
244 gc::Heap* heap = Runtime::Current()->GetHeap();
245 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
246 heap->FlushAllocStack();
247 heap->GetLiveBitmap()->Walk(ComputeEagerResolvedStringsCallback, this);
248}
249
250bool ImageWriter::IsImageClass(const Class* klass) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700251 return compiler_driver_.IsImageClass(ClassHelper(klass).GetDescriptorAsStringPiece());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700252}
253
254struct NonImageClasses {
255 ImageWriter* image_writer;
256 std::set<std::string>* non_image_classes;
257};
258
259void ImageWriter::PruneNonImageClasses() {
260 if (compiler_driver_.GetImageClasses() == NULL) {
261 return;
262 }
263 Runtime* runtime = Runtime::Current();
264 ClassLinker* class_linker = runtime->GetClassLinker();
265
266 // Make a list of classes we would like to prune.
267 std::set<std::string> non_image_classes;
268 NonImageClasses context;
269 context.image_writer = this;
270 context.non_image_classes = &non_image_classes;
271 class_linker->VisitClasses(NonImageClassesVisitor, &context);
272
273 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700274 for (const std::string& it : non_image_classes) {
275 class_linker->RemoveClass(it.c_str(), NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700276 }
277
278 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700279 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700280 for (DexCache* dex_cache : dex_caches_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700281 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
282 Class* klass = dex_cache->GetResolvedType(i);
283 if (klass != NULL && !IsImageClass(klass)) {
284 dex_cache->SetResolvedType(i, NULL);
285 dex_cache->GetInitializedStaticStorage()->Set(i, NULL);
286 }
287 }
288 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700289 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700290 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
291 dex_cache->SetResolvedMethod(i, resolution_method);
292 }
293 }
294 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700295 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700296 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
297 dex_cache->SetResolvedField(i, NULL);
298 }
299 }
300 }
301}
302
303bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
304 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
305 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogersfc0e94b2013-09-23 23:51:32 -0700306 context->non_image_classes->insert(ClassHelper(klass).GetDescriptorAsStringPiece().as_string());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700307 }
308 return true;
309}
310
311void ImageWriter::CheckNonImageClassesRemoved()
312 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
313 if (compiler_driver_.GetImageClasses() == NULL) {
314 return;
315 }
316
317 gc::Heap* heap = Runtime::Current()->GetHeap();
318 Thread* self = Thread::Current();
319 {
320 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
321 heap->FlushAllocStack();
322 }
323
324 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
325 heap->GetLiveBitmap()->Walk(CheckNonImageClassesRemovedCallback, this);
326}
327
328void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
329 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
330 if (!obj->IsClass()) {
331 return;
332 }
333 Class* klass = obj->AsClass();
334 if (!image_writer->IsImageClass(klass)) {
335 image_writer->DumpImageClasses();
336 CHECK(image_writer->IsImageClass(klass)) << ClassHelper(klass).GetDescriptor()
337 << " " << PrettyDescriptor(klass);
338 }
339}
340
341void ImageWriter::DumpImageClasses() {
342 CompilerDriver::DescriptorSet* image_classes = compiler_driver_.GetImageClasses();
343 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700344 for (const std::string& image_class : *image_classes) {
345 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700346 }
347}
348
349void ImageWriter::CalculateNewObjectOffsetsCallback(Object* obj, void* arg) {
350 DCHECK(obj != NULL);
351 DCHECK(arg != NULL);
352 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
353
354 // if it is a string, we want to intern it if its not interned.
355 if (obj->GetClass()->IsStringClass()) {
356 // we must be an interned string that was forward referenced and already assigned
357 if (image_writer->IsImageOffsetAssigned(obj)) {
358 DCHECK_EQ(obj, obj->AsString()->Intern());
359 return;
360 }
361 SirtRef<String> interned(Thread::Current(), obj->AsString()->Intern());
362 if (obj != interned.get()) {
363 if (!image_writer->IsImageOffsetAssigned(interned.get())) {
364 // interned obj is after us, allocate its location early
365 image_writer->AssignImageOffset(interned.get());
366 }
367 // point those looking for this object to the interned version.
368 image_writer->SetImageOffset(obj, image_writer->GetImageOffset(interned.get()));
369 return;
370 }
371 // else (obj == interned), nothing to do but fall through to the normal case
372 }
373
374 image_writer->AssignImageOffset(obj);
375}
376
377ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
378 Runtime* runtime = Runtime::Current();
379 ClassLinker* class_linker = runtime->GetClassLinker();
380 Class* object_array_class = class_linker->FindSystemClass("[Ljava/lang/Object;");
381 Thread* self = Thread::Current();
382
383 // build an Object[] of all the DexCaches used in the source_space_
384 ObjectArray<Object>* dex_caches = ObjectArray<Object>::Alloc(self, object_array_class,
385 dex_caches_.size());
386 int i = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700387 for (DexCache* dex_cache : dex_caches_) {
388 dex_caches->Set(i++, dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700389 }
390
391 // build an Object[] of the roots needed to restore the runtime
392 SirtRef<ObjectArray<Object> >
393 image_roots(self,
394 ObjectArray<Object>::Alloc(self, object_array_class,
395 ImageHeader::kImageRootsMax));
396 image_roots->Set(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700397 image_roots->Set(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
398 image_roots->Set(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700399 image_roots->Set(ImageHeader::kCalleeSaveMethod,
400 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
401 image_roots->Set(ImageHeader::kRefsOnlySaveMethod,
402 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
403 image_roots->Set(ImageHeader::kRefsAndArgsSaveMethod,
404 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
405 image_roots->Set(ImageHeader::kOatLocation,
406 String::AllocFromModifiedUtf8(self, oat_file_->GetLocation().c_str()));
407 image_roots->Set(ImageHeader::kDexCaches,
408 dex_caches);
409 image_roots->Set(ImageHeader::kClassRoots,
410 class_linker->GetClassRoots());
411 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
412 CHECK(image_roots->Get(i) != NULL);
413 }
414 return image_roots.get();
415}
416
417void ImageWriter::CalculateNewObjectOffsets(size_t oat_loaded_size, size_t oat_data_offset) {
418 CHECK_NE(0U, oat_loaded_size);
419 Thread* self = Thread::Current();
420 SirtRef<ObjectArray<Object> > image_roots(self, CreateImageRoots());
421
422 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700423 const auto& spaces = heap->GetContinuousSpaces();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700424 DCHECK(!spaces.empty());
425 DCHECK_EQ(0U, image_end_);
426
Mathieu Chartier31e89252013-08-28 11:29:12 -0700427 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700428 // know where image_roots is going to end up
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700429 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700430
431 {
432 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
433 heap->FlushAllocStack();
434 // TODO: Image spaces only?
435 // TODO: Add InOrderWalk to heap bitmap.
436 const char* old = self->StartAssertNoThreadSuspension("ImageWriter");
437 DCHECK(heap->GetLargeObjectsSpace()->GetLiveObjects()->IsEmpty());
Mathieu Chartier02e25112013-08-14 16:14:24 -0700438 for (const auto& space : spaces) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700439 space->GetLiveBitmap()->InOrderWalk(CalculateNewObjectOffsetsCallback, this);
440 DCHECK_LT(image_end_, image_->Size());
441 }
442 self->EndAssertNoThreadSuspension(old);
443 }
444
Mathieu Chartier31e89252013-08-28 11:29:12 -0700445 // Create the image bitmap.
446 image_bitmap_.reset(gc::accounting::SpaceBitmap::Create("image bitmap", image_->Begin(),
447 image_end_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700448 const byte* oat_file_begin = image_begin_ + RoundUp(image_end_, kPageSize);
449 const byte* oat_file_end = oat_file_begin + oat_loaded_size;
450 oat_data_begin_ = oat_file_begin + oat_data_offset;
451 const byte* oat_data_end = oat_data_begin_ + oat_file_->Size();
452
Mathieu Chartier31e89252013-08-28 11:29:12 -0700453 // Return to write header at start of image with future location of image_roots. At this point,
454 // image_end_ is the size of the image (excluding bitmaps).
Brian Carlstrom7940e442013-07-12 13:46:57 -0700455 ImageHeader image_header(reinterpret_cast<uint32_t>(image_begin_),
Mathieu Chartier31e89252013-08-28 11:29:12 -0700456 static_cast<uint32_t>(image_end_),
457 RoundUp(image_end_, kPageSize),
458 image_bitmap_->Size(),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700459 reinterpret_cast<uint32_t>(GetImageAddress(image_roots.get())),
460 oat_file_->GetOatHeader().GetChecksum(),
461 reinterpret_cast<uint32_t>(oat_file_begin),
462 reinterpret_cast<uint32_t>(oat_data_begin_),
463 reinterpret_cast<uint32_t>(oat_data_end),
464 reinterpret_cast<uint32_t>(oat_file_end));
465 memcpy(image_->Begin(), &image_header, sizeof(image_header));
466
467 // Note that image_end_ is left at end of used space
468}
469
470void ImageWriter::CopyAndFixupObjects()
471 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
472 Thread* self = Thread::Current();
473 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
474 gc::Heap* heap = Runtime::Current()->GetHeap();
475 // TODO: heap validation can't handle this fix up pass
476 heap->DisableObjectValidation();
477 // TODO: Image spaces only?
478 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
479 heap->FlushAllocStack();
480 heap->GetLiveBitmap()->Walk(CopyAndFixupObjectsCallback, this);
481 self->EndAssertNoThreadSuspension(old_cause);
482}
483
484void ImageWriter::CopyAndFixupObjectsCallback(Object* object, void* arg) {
485 DCHECK(object != NULL);
486 DCHECK(arg != NULL);
487 const Object* obj = object;
488 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
489
490 // see GetLocalAddress for similar computation
491 size_t offset = image_writer->GetImageOffset(obj);
492 byte* dst = image_writer->image_->Begin() + offset;
493 const byte* src = reinterpret_cast<const byte*>(obj);
494 size_t n = obj->SizeOf();
495 DCHECK_LT(offset + n, image_writer->image_->Size());
496 memcpy(dst, src, n);
497 Object* copy = reinterpret_cast<Object*>(dst);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700498 copy->SetField32(Object::MonitorOffset(), 0, false); // We may have inflated the lock during compilation.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700499 image_writer->FixupObject(obj, copy);
500}
501
502void ImageWriter::FixupObject(const Object* orig, Object* copy) {
503 DCHECK(orig != NULL);
504 DCHECK(copy != NULL);
505 copy->SetClass(down_cast<Class*>(GetImageAddress(orig->GetClass())));
506 // TODO: special case init of pointers to malloc data (or removal of these pointers)
507 if (orig->IsClass()) {
508 FixupClass(orig->AsClass(), down_cast<Class*>(copy));
509 } else if (orig->IsObjectArray()) {
510 FixupObjectArray(orig->AsObjectArray<Object>(), down_cast<ObjectArray<Object>*>(copy));
Brian Carlstromea46f952013-07-30 01:26:50 -0700511 } else if (orig->IsArtMethod()) {
512 FixupMethod(orig->AsArtMethod(), down_cast<ArtMethod*>(copy));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700513 } else {
514 FixupInstanceFields(orig, copy);
515 }
516}
517
518void ImageWriter::FixupClass(const Class* orig, Class* copy) {
519 FixupInstanceFields(orig, copy);
520 FixupStaticFields(orig, copy);
521}
522
Brian Carlstromea46f952013-07-30 01:26:50 -0700523void ImageWriter::FixupMethod(const ArtMethod* orig, ArtMethod* copy) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700524 FixupInstanceFields(orig, copy);
525
Ian Rogers848871b2013-08-05 10:56:33 -0700526 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
527 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -0700528
Ian Rogers848871b2013-08-05 10:56:33 -0700529 // The resolution method has a special trampoline to call.
530 if (UNLIKELY(orig == Runtime::Current()->GetResolutionMethod())) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700531#if defined(ART_USE_PORTABLE_COMPILER)
532 copy->SetEntryPointFromCompiledCode(GetOatAddress(portable_resolution_trampoline_offset_));
533#else
534 copy->SetEntryPointFromCompiledCode(GetOatAddress(quick_resolution_trampoline_offset_));
535#endif
Jeff Hao88474b42013-10-23 16:24:40 -0700536 } else if (UNLIKELY(orig == Runtime::Current()->GetImtConflictMethod())) {
537#if defined(ART_USE_PORTABLE_COMPILER)
538 copy->SetEntryPointFromCompiledCode(GetOatAddress(portable_imt_conflict_trampoline_offset_));
539#else
540 copy->SetEntryPointFromCompiledCode(GetOatAddress(quick_imt_conflict_trampoline_offset_));
541#endif
Brian Carlstrom7940e442013-07-12 13:46:57 -0700542 } else {
Ian Rogers848871b2013-08-05 10:56:33 -0700543 // We assume all methods have code. If they don't currently then we set them to the use the
544 // resolution trampoline. Abstract methods never have code and so we need to make sure their
545 // use results in an AbstractMethodError. We use the interpreter to achieve this.
546 if (UNLIKELY(orig->IsAbstract())) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700547#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogers848871b2013-08-05 10:56:33 -0700548 copy->SetEntryPointFromCompiledCode(GetOatAddress(portable_to_interpreter_bridge_offset_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700549#else
Ian Rogers848871b2013-08-05 10:56:33 -0700550 copy->SetEntryPointFromCompiledCode(GetOatAddress(quick_to_interpreter_bridge_offset_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700551#endif
Ian Rogers848871b2013-08-05 10:56:33 -0700552 copy->SetEntryPointFromInterpreter(reinterpret_cast<EntryPointFromInterpreter*>
553 (GetOatAddress(interpreter_to_interpreter_bridge_offset_)));
554 } else {
555 copy->SetEntryPointFromInterpreter(reinterpret_cast<EntryPointFromInterpreter*>
556 (GetOatAddress(interpreter_to_compiled_code_bridge_offset_)));
557 // Use original code if it exists. Otherwise, set the code pointer to the resolution
558 // trampoline.
559 const byte* code = GetOatAddress(orig->GetOatCodeOffset());
560 if (code != NULL) {
561 copy->SetEntryPointFromCompiledCode(code);
562 } else {
563#if defined(ART_USE_PORTABLE_COMPILER)
564 copy->SetEntryPointFromCompiledCode(GetOatAddress(portable_resolution_trampoline_offset_));
565#else
566 copy->SetEntryPointFromCompiledCode(GetOatAddress(quick_resolution_trampoline_offset_));
567#endif
568 }
569 if (orig->IsNative()) {
570 // The native method's pointer is set to a stub to lookup via dlsym.
571 // Note this is not the code_ pointer, that is handled above.
572 copy->SetNativeMethod(GetOatAddress(jni_dlsym_lookup_offset_));
573 } else {
574 // Normal (non-abstract non-native) methods have various tables to relocate.
575 uint32_t mapping_table_off = orig->GetOatMappingTableOffset();
576 const byte* mapping_table = GetOatAddress(mapping_table_off);
Ian Rogers1809a722013-08-09 22:05:32 -0700577 copy->SetMappingTable(mapping_table);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700578
Ian Rogers848871b2013-08-05 10:56:33 -0700579 uint32_t vmap_table_offset = orig->GetOatVmapTableOffset();
580 const byte* vmap_table = GetOatAddress(vmap_table_offset);
Ian Rogers1809a722013-08-09 22:05:32 -0700581 copy->SetVmapTable(vmap_table);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700582
Ian Rogers848871b2013-08-05 10:56:33 -0700583 uint32_t native_gc_map_offset = orig->GetOatNativeGcMapOffset();
584 const byte* native_gc_map = GetOatAddress(native_gc_map_offset);
585 copy->SetNativeGcMap(reinterpret_cast<const uint8_t*>(native_gc_map));
586 }
587 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700588 }
589}
590
591void ImageWriter::FixupObjectArray(const ObjectArray<Object>* orig, ObjectArray<Object>* copy) {
592 for (int32_t i = 0; i < orig->GetLength(); ++i) {
593 const Object* element = orig->Get(i);
594 copy->SetPtrWithoutChecks(i, GetImageAddress(element));
595 }
596}
597
598void ImageWriter::FixupInstanceFields(const Object* orig, Object* copy) {
599 DCHECK(orig != NULL);
600 DCHECK(copy != NULL);
601 Class* klass = orig->GetClass();
602 DCHECK(klass != NULL);
603 FixupFields(orig,
604 copy,
605 klass->GetReferenceInstanceOffsets(),
606 false);
607}
608
609void ImageWriter::FixupStaticFields(const Class* orig, Class* copy) {
610 DCHECK(orig != NULL);
611 DCHECK(copy != NULL);
612 FixupFields(orig,
613 copy,
614 orig->GetReferenceStaticOffsets(),
615 true);
616}
617
618void ImageWriter::FixupFields(const Object* orig,
619 Object* copy,
620 uint32_t ref_offsets,
621 bool is_static) {
622 if (ref_offsets != CLASS_WALK_SUPER) {
623 // Found a reference offset bitmap. Fixup the specified offsets.
624 while (ref_offsets != 0) {
625 size_t right_shift = CLZ(ref_offsets);
626 MemberOffset byte_offset = CLASS_OFFSET_FROM_CLZ(right_shift);
627 const Object* ref = orig->GetFieldObject<const Object*>(byte_offset, false);
628 // Use SetFieldPtr to avoid card marking since we are writing to the image.
629 copy->SetFieldPtr(byte_offset, GetImageAddress(ref), false);
630 ref_offsets &= ~(CLASS_HIGH_BIT >> right_shift);
631 }
632 } else {
633 // There is no reference offset bitmap. In the non-static case,
634 // walk up the class inheritance hierarchy and find reference
635 // offsets the hard way. In the static case, just consider this
636 // class.
637 for (const Class *klass = is_static ? orig->AsClass() : orig->GetClass();
638 klass != NULL;
639 klass = is_static ? NULL : klass->GetSuperClass()) {
640 size_t num_reference_fields = (is_static
641 ? klass->NumReferenceStaticFields()
642 : klass->NumReferenceInstanceFields());
643 for (size_t i = 0; i < num_reference_fields; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700644 ArtField* field = (is_static
645 ? klass->GetStaticField(i)
646 : klass->GetInstanceField(i));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700647 MemberOffset field_offset = field->GetOffset();
648 const Object* ref = orig->GetFieldObject<const Object*>(field_offset, false);
649 // Use SetFieldPtr to avoid card marking since we are writing to the image.
650 copy->SetFieldPtr(field_offset, GetImageAddress(ref), false);
651 }
652 }
653 }
654 if (!is_static && orig->IsReferenceInstance()) {
655 // Fix-up referent, that isn't marked as an object field, for References.
Brian Carlstromea46f952013-07-30 01:26:50 -0700656 ArtField* field = orig->GetClass()->FindInstanceField("referent", "Ljava/lang/Object;");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700657 MemberOffset field_offset = field->GetOffset();
658 const Object* ref = orig->GetFieldObject<const Object*>(field_offset, false);
659 // Use SetFieldPtr to avoid card marking since we are writing to the image.
660 copy->SetFieldPtr(field_offset, GetImageAddress(ref), false);
661 }
662}
663
Brian Carlstromea46f952013-07-30 01:26:50 -0700664static ArtMethod* GetTargetMethod(const CompilerDriver::PatchInformation* patch)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700665 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
666 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
667 DexCache* dex_cache = class_linker->FindDexCache(patch->GetDexFile());
Brian Carlstromea46f952013-07-30 01:26:50 -0700668 ArtMethod* method = class_linker->ResolveMethod(patch->GetDexFile(),
669 patch->GetTargetMethodIdx(),
670 dex_cache,
671 NULL,
672 NULL,
673 patch->GetTargetInvokeType());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700674 CHECK(method != NULL)
675 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
676 CHECK(!method->IsRuntimeMethod())
677 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
678 CHECK(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx()) == method)
679 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
680 << PrettyMethod(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx())) << " "
681 << PrettyMethod(method);
682 return method;
683}
684
685void ImageWriter::PatchOatCodeAndMethods() {
686 Thread* self = Thread::Current();
687 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
688 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
689
690 typedef std::vector<const CompilerDriver::PatchInformation*> Patches;
691 const Patches& code_to_patch = compiler_driver_.GetCodeToPatch();
692 for (size_t i = 0; i < code_to_patch.size(); i++) {
693 const CompilerDriver::PatchInformation* patch = code_to_patch[i];
Brian Carlstromea46f952013-07-30 01:26:50 -0700694 ArtMethod* target = GetTargetMethod(patch);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700695 uint32_t code = reinterpret_cast<uint32_t>(class_linker->GetOatCodeFor(target));
696 uint32_t code_base = reinterpret_cast<uint32_t>(&oat_file_->GetOatHeader());
697 uint32_t code_offset = code - code_base;
698 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetOatAddress(code_offset)));
699 }
700
701 const Patches& methods_to_patch = compiler_driver_.GetMethodsToPatch();
702 for (size_t i = 0; i < methods_to_patch.size(); i++) {
703 const CompilerDriver::PatchInformation* patch = methods_to_patch[i];
Brian Carlstromea46f952013-07-30 01:26:50 -0700704 ArtMethod* target = GetTargetMethod(patch);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700705 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetImageAddress(target)));
706 }
707
708 // Update the image header with the new checksum after patching
709 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
710 image_header->SetOatChecksum(oat_file_->GetOatHeader().GetChecksum());
711 self->EndAssertNoThreadSuspension(old_cause);
712}
713
714void ImageWriter::SetPatchLocation(const CompilerDriver::PatchInformation* patch, uint32_t value) {
715 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
716 const void* oat_code = class_linker->GetOatCodeFor(patch->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700717 patch->GetReferrerClassDefIdx(),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700718 patch->GetReferrerMethodIdx());
719 OatHeader& oat_header = const_cast<OatHeader&>(oat_file_->GetOatHeader());
720 // TODO: make this Thumb2 specific
721 uint8_t* base = reinterpret_cast<uint8_t*>(reinterpret_cast<uint32_t>(oat_code) & ~0x1);
722 uint32_t* patch_location = reinterpret_cast<uint32_t*>(base + patch->GetLiteralOffset());
723#ifndef NDEBUG
724 const DexFile::MethodId& id = patch->GetDexFile().GetMethodId(patch->GetTargetMethodIdx());
725 uint32_t expected = reinterpret_cast<uint32_t>(&id);
726 uint32_t actual = *patch_location;
727 CHECK(actual == expected || actual == value) << std::hex
728 << "actual=" << actual
729 << "expected=" << expected
730 << "value=" << value;
731#endif
732 *patch_location = value;
733 oat_header.UpdateChecksum(patch_location, sizeof(value));
734}
735
736} // namespace art