blob: 548ea9eee4fe2ae80c50e5b3563ccda44b7f9efc [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"
32#include "gc/heap.h"
33#include "gc/space/large_object_space.h"
34#include "gc/space/space-inl.h"
35#include "globals.h"
36#include "image.h"
37#include "intern_table.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070038#include "mirror/art_field-inl.h"
39#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070040#include "mirror/array-inl.h"
41#include "mirror/class-inl.h"
42#include "mirror/class_loader.h"
43#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070044#include "mirror/object-inl.h"
45#include "mirror/object_array-inl.h"
46#include "oat.h"
47#include "oat_file.h"
48#include "object_utils.h"
49#include "runtime.h"
50#include "scoped_thread_state_change.h"
51#include "sirt_ref.h"
52#include "UniquePtr.h"
53#include "utils.h"
54
Brian Carlstromea46f952013-07-30 01:26:50 -070055using ::art::mirror::ArtField;
56using ::art::mirror::ArtMethod;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070057using ::art::mirror::Class;
58using ::art::mirror::DexCache;
59using ::art::mirror::EntryPointFromInterpreter;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070060using ::art::mirror::Object;
61using ::art::mirror::ObjectArray;
62using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070063
64namespace art {
65
66bool ImageWriter::Write(const std::string& image_filename,
67 uintptr_t image_begin,
68 const std::string& oat_filename,
69 const std::string& oat_location) {
70 CHECK(!image_filename.empty());
71
72 CHECK_NE(image_begin, 0U);
73 image_begin_ = reinterpret_cast<byte*>(image_begin);
74
75 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
76 const std::vector<DexCache*>& all_dex_caches = class_linker->GetDexCaches();
Mathieu Chartier02e25112013-08-14 16:14:24 -070077 dex_caches_.insert(all_dex_caches.begin(), all_dex_caches.end());
Brian Carlstrom7940e442013-07-12 13:46:57 -070078
Brian Carlstrom7571e8b2013-08-12 17:04:14 -070079 UniquePtr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -070080 if (oat_file.get() == NULL) {
81 LOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
82 return false;
83 }
84 oat_file_ = OatFile::OpenWritable(oat_file.get(), oat_location);
Brian Carlstromc50d8e12013-07-23 22:35:16 -070085 if (oat_file_ == NULL) {
86 LOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location;
87 return false;
88 }
Brian Carlstrom7940e442013-07-12 13:46:57 -070089 class_linker->RegisterOatFile(*oat_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -070090
Ian Rogers848871b2013-08-05 10:56:33 -070091 interpreter_to_interpreter_bridge_offset_ =
92 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
93 interpreter_to_compiled_code_bridge_offset_ =
94 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
95
96 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
97
98 portable_resolution_trampoline_offset_ =
99 oat_file_->GetOatHeader().GetPortableResolutionTrampolineOffset();
100 portable_to_interpreter_bridge_offset_ =
101 oat_file_->GetOatHeader().GetPortableToInterpreterBridgeOffset();
102
103 quick_resolution_trampoline_offset_ =
104 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
105 quick_to_interpreter_bridge_offset_ =
106 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700107 {
108 Thread::Current()->TransitionFromSuspendedToRunnable();
109 PruneNonImageClasses(); // Remove junk
110 ComputeLazyFieldsForImageClasses(); // Add useful information
111 ComputeEagerResolvedStrings();
112 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
113 }
114 gc::Heap* heap = Runtime::Current()->GetHeap();
115 heap->CollectGarbage(false); // Remove garbage.
116 // Trim size of alloc spaces.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700117 for (const auto& space : heap->GetContinuousSpaces()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700118 if (space->IsDlMallocSpace()) {
119 space->AsDlMallocSpace()->Trim();
120 }
121 }
122
123 if (!AllocMemory()) {
124 return false;
125 }
126#ifndef NDEBUG
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700127 { // NOLINT(whitespace/braces)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700128 ScopedObjectAccess soa(Thread::Current());
129 CheckNonImageClassesRemoved();
130 }
131#endif
132 Thread::Current()->TransitionFromSuspendedToRunnable();
133 size_t oat_loaded_size = 0;
134 size_t oat_data_offset = 0;
135 ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
136 CalculateNewObjectOffsets(oat_loaded_size, oat_data_offset);
137 CopyAndFixupObjects();
138 PatchOatCodeAndMethods();
139 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
140
Brian Carlstrom7571e8b2013-08-12 17:04:14 -0700141 UniquePtr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700142 if (image_file.get() == NULL) {
143 LOG(ERROR) << "Failed to open image file " << image_filename;
144 return false;
145 }
146 if (fchmod(image_file->Fd(), 0644) != 0) {
147 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
148 return EXIT_FAILURE;
149 }
150 bool success = image_file->WriteFully(image_->Begin(), image_end_);
151 if (!success) {
152 PLOG(ERROR) << "Failed to write image file " << image_filename;
153 return false;
154 }
155 return true;
156}
157
158bool ImageWriter::AllocMemory() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700159 size_t size = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700160 for (const auto& space : Runtime::Current()->GetHeap()->GetContinuousSpaces()) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700161 if (space->IsDlMallocSpace()) {
162 size += space->Size();
163 }
164 }
165
166 int prot = PROT_READ | PROT_WRITE;
167 size_t length = RoundUp(size, kPageSize);
168 image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, prot));
169 if (image_.get() == NULL) {
170 LOG(ERROR) << "Failed to allocate memory for image file generation";
171 return false;
172 }
173 return true;
174}
175
176void ImageWriter::ComputeLazyFieldsForImageClasses() {
177 Runtime* runtime = Runtime::Current();
178 ClassLinker* class_linker = runtime->GetClassLinker();
179 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
180}
181
182bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
183 c->ComputeName();
184 return true;
185}
186
187void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg) {
188 if (!obj->GetClass()->IsStringClass()) {
189 return;
190 }
191 String* string = obj->AsString();
192 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
193 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700194 for (DexCache* dex_cache : writer->dex_caches_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700195 const DexFile& dex_file = *dex_cache->GetDexFile();
196 const DexFile::StringId* string_id = dex_file.FindStringId(utf16_string);
197 if (string_id != NULL) {
198 // This string occurs in this dex file, assign the dex cache entry.
199 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
200 if (dex_cache->GetResolvedString(string_idx) == NULL) {
201 dex_cache->SetResolvedString(string_idx, string);
202 }
203 }
204 }
205}
206
207void ImageWriter::ComputeEagerResolvedStrings()
208 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
209 // TODO: Check image spaces only?
210 gc::Heap* heap = Runtime::Current()->GetHeap();
211 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
212 heap->FlushAllocStack();
213 heap->GetLiveBitmap()->Walk(ComputeEagerResolvedStringsCallback, this);
214}
215
216bool ImageWriter::IsImageClass(const Class* klass) {
217 return compiler_driver_.IsImageClass(ClassHelper(klass).GetDescriptor());
218}
219
220struct NonImageClasses {
221 ImageWriter* image_writer;
222 std::set<std::string>* non_image_classes;
223};
224
225void ImageWriter::PruneNonImageClasses() {
226 if (compiler_driver_.GetImageClasses() == NULL) {
227 return;
228 }
229 Runtime* runtime = Runtime::Current();
230 ClassLinker* class_linker = runtime->GetClassLinker();
231
232 // Make a list of classes we would like to prune.
233 std::set<std::string> non_image_classes;
234 NonImageClasses context;
235 context.image_writer = this;
236 context.non_image_classes = &non_image_classes;
237 class_linker->VisitClasses(NonImageClassesVisitor, &context);
238
239 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700240 for (const std::string& it : non_image_classes) {
241 class_linker->RemoveClass(it.c_str(), NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700242 }
243
244 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700245 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700246 for (DexCache* dex_cache : dex_caches_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700247 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
248 Class* klass = dex_cache->GetResolvedType(i);
249 if (klass != NULL && !IsImageClass(klass)) {
250 dex_cache->SetResolvedType(i, NULL);
251 dex_cache->GetInitializedStaticStorage()->Set(i, NULL);
252 }
253 }
254 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700255 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700256 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
257 dex_cache->SetResolvedMethod(i, resolution_method);
258 }
259 }
260 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700261 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700262 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
263 dex_cache->SetResolvedField(i, NULL);
264 }
265 }
266 }
267}
268
269bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
270 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
271 if (!context->image_writer->IsImageClass(klass)) {
272 context->non_image_classes->insert(ClassHelper(klass).GetDescriptor());
273 }
274 return true;
275}
276
277void ImageWriter::CheckNonImageClassesRemoved()
278 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
279 if (compiler_driver_.GetImageClasses() == NULL) {
280 return;
281 }
282
283 gc::Heap* heap = Runtime::Current()->GetHeap();
284 Thread* self = Thread::Current();
285 {
286 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
287 heap->FlushAllocStack();
288 }
289
290 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
291 heap->GetLiveBitmap()->Walk(CheckNonImageClassesRemovedCallback, this);
292}
293
294void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
295 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
296 if (!obj->IsClass()) {
297 return;
298 }
299 Class* klass = obj->AsClass();
300 if (!image_writer->IsImageClass(klass)) {
301 image_writer->DumpImageClasses();
302 CHECK(image_writer->IsImageClass(klass)) << ClassHelper(klass).GetDescriptor()
303 << " " << PrettyDescriptor(klass);
304 }
305}
306
307void ImageWriter::DumpImageClasses() {
308 CompilerDriver::DescriptorSet* image_classes = compiler_driver_.GetImageClasses();
309 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700310 for (const std::string& image_class : *image_classes) {
311 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700312 }
313}
314
315void ImageWriter::CalculateNewObjectOffsetsCallback(Object* obj, void* arg) {
316 DCHECK(obj != NULL);
317 DCHECK(arg != NULL);
318 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
319
320 // if it is a string, we want to intern it if its not interned.
321 if (obj->GetClass()->IsStringClass()) {
322 // we must be an interned string that was forward referenced and already assigned
323 if (image_writer->IsImageOffsetAssigned(obj)) {
324 DCHECK_EQ(obj, obj->AsString()->Intern());
325 return;
326 }
327 SirtRef<String> interned(Thread::Current(), obj->AsString()->Intern());
328 if (obj != interned.get()) {
329 if (!image_writer->IsImageOffsetAssigned(interned.get())) {
330 // interned obj is after us, allocate its location early
331 image_writer->AssignImageOffset(interned.get());
332 }
333 // point those looking for this object to the interned version.
334 image_writer->SetImageOffset(obj, image_writer->GetImageOffset(interned.get()));
335 return;
336 }
337 // else (obj == interned), nothing to do but fall through to the normal case
338 }
339
340 image_writer->AssignImageOffset(obj);
341}
342
343ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
344 Runtime* runtime = Runtime::Current();
345 ClassLinker* class_linker = runtime->GetClassLinker();
346 Class* object_array_class = class_linker->FindSystemClass("[Ljava/lang/Object;");
347 Thread* self = Thread::Current();
348
349 // build an Object[] of all the DexCaches used in the source_space_
350 ObjectArray<Object>* dex_caches = ObjectArray<Object>::Alloc(self, object_array_class,
351 dex_caches_.size());
352 int i = 0;
Mathieu Chartier02e25112013-08-14 16:14:24 -0700353 for (DexCache* dex_cache : dex_caches_) {
354 dex_caches->Set(i++, dex_cache);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700355 }
356
357 // build an Object[] of the roots needed to restore the runtime
358 SirtRef<ObjectArray<Object> >
359 image_roots(self,
360 ObjectArray<Object>::Alloc(self, object_array_class,
361 ImageHeader::kImageRootsMax));
362 image_roots->Set(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
363 image_roots->Set(ImageHeader::kCalleeSaveMethod,
364 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
365 image_roots->Set(ImageHeader::kRefsOnlySaveMethod,
366 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
367 image_roots->Set(ImageHeader::kRefsAndArgsSaveMethod,
368 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
369 image_roots->Set(ImageHeader::kOatLocation,
370 String::AllocFromModifiedUtf8(self, oat_file_->GetLocation().c_str()));
371 image_roots->Set(ImageHeader::kDexCaches,
372 dex_caches);
373 image_roots->Set(ImageHeader::kClassRoots,
374 class_linker->GetClassRoots());
375 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
376 CHECK(image_roots->Get(i) != NULL);
377 }
378 return image_roots.get();
379}
380
381void ImageWriter::CalculateNewObjectOffsets(size_t oat_loaded_size, size_t oat_data_offset) {
382 CHECK_NE(0U, oat_loaded_size);
383 Thread* self = Thread::Current();
384 SirtRef<ObjectArray<Object> > image_roots(self, CreateImageRoots());
385
386 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier02e25112013-08-14 16:14:24 -0700387 const auto& spaces = heap->GetContinuousSpaces();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700388 DCHECK(!spaces.empty());
389 DCHECK_EQ(0U, image_end_);
390
391 // leave space for the header, but do not write it yet, we need to
392 // know where image_roots is going to end up
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700393 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700394
395 {
396 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
397 heap->FlushAllocStack();
398 // TODO: Image spaces only?
399 // TODO: Add InOrderWalk to heap bitmap.
400 const char* old = self->StartAssertNoThreadSuspension("ImageWriter");
401 DCHECK(heap->GetLargeObjectsSpace()->GetLiveObjects()->IsEmpty());
Mathieu Chartier02e25112013-08-14 16:14:24 -0700402 for (const auto& space : spaces) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700403 space->GetLiveBitmap()->InOrderWalk(CalculateNewObjectOffsetsCallback, this);
404 DCHECK_LT(image_end_, image_->Size());
405 }
406 self->EndAssertNoThreadSuspension(old);
407 }
408
409 const byte* oat_file_begin = image_begin_ + RoundUp(image_end_, kPageSize);
410 const byte* oat_file_end = oat_file_begin + oat_loaded_size;
411 oat_data_begin_ = oat_file_begin + oat_data_offset;
412 const byte* oat_data_end = oat_data_begin_ + oat_file_->Size();
413
414 // return to write header at start of image with future location of image_roots
415 ImageHeader image_header(reinterpret_cast<uint32_t>(image_begin_),
416 reinterpret_cast<uint32_t>(GetImageAddress(image_roots.get())),
417 oat_file_->GetOatHeader().GetChecksum(),
418 reinterpret_cast<uint32_t>(oat_file_begin),
419 reinterpret_cast<uint32_t>(oat_data_begin_),
420 reinterpret_cast<uint32_t>(oat_data_end),
421 reinterpret_cast<uint32_t>(oat_file_end));
422 memcpy(image_->Begin(), &image_header, sizeof(image_header));
423
424 // Note that image_end_ is left at end of used space
425}
426
427void ImageWriter::CopyAndFixupObjects()
428 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
429 Thread* self = Thread::Current();
430 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
431 gc::Heap* heap = Runtime::Current()->GetHeap();
432 // TODO: heap validation can't handle this fix up pass
433 heap->DisableObjectValidation();
434 // TODO: Image spaces only?
435 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
436 heap->FlushAllocStack();
437 heap->GetLiveBitmap()->Walk(CopyAndFixupObjectsCallback, this);
438 self->EndAssertNoThreadSuspension(old_cause);
439}
440
441void ImageWriter::CopyAndFixupObjectsCallback(Object* object, void* arg) {
442 DCHECK(object != NULL);
443 DCHECK(arg != NULL);
444 const Object* obj = object;
445 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
446
447 // see GetLocalAddress for similar computation
448 size_t offset = image_writer->GetImageOffset(obj);
449 byte* dst = image_writer->image_->Begin() + offset;
450 const byte* src = reinterpret_cast<const byte*>(obj);
451 size_t n = obj->SizeOf();
452 DCHECK_LT(offset + n, image_writer->image_->Size());
453 memcpy(dst, src, n);
454 Object* copy = reinterpret_cast<Object*>(dst);
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700455 copy->SetField32(Object::MonitorOffset(), 0, false); // We may have inflated the lock during compilation.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700456 image_writer->FixupObject(obj, copy);
457}
458
459void ImageWriter::FixupObject(const Object* orig, Object* copy) {
460 DCHECK(orig != NULL);
461 DCHECK(copy != NULL);
462 copy->SetClass(down_cast<Class*>(GetImageAddress(orig->GetClass())));
463 // TODO: special case init of pointers to malloc data (or removal of these pointers)
464 if (orig->IsClass()) {
465 FixupClass(orig->AsClass(), down_cast<Class*>(copy));
466 } else if (orig->IsObjectArray()) {
467 FixupObjectArray(orig->AsObjectArray<Object>(), down_cast<ObjectArray<Object>*>(copy));
Brian Carlstromea46f952013-07-30 01:26:50 -0700468 } else if (orig->IsArtMethod()) {
469 FixupMethod(orig->AsArtMethod(), down_cast<ArtMethod*>(copy));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700470 } else {
471 FixupInstanceFields(orig, copy);
472 }
473}
474
475void ImageWriter::FixupClass(const Class* orig, Class* copy) {
476 FixupInstanceFields(orig, copy);
477 FixupStaticFields(orig, copy);
478}
479
Brian Carlstromea46f952013-07-30 01:26:50 -0700480void ImageWriter::FixupMethod(const ArtMethod* orig, ArtMethod* copy) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700481 FixupInstanceFields(orig, copy);
482
Ian Rogers848871b2013-08-05 10:56:33 -0700483 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
484 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -0700485
Ian Rogers848871b2013-08-05 10:56:33 -0700486 // The resolution method has a special trampoline to call.
487 if (UNLIKELY(orig == Runtime::Current()->GetResolutionMethod())) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700488#if defined(ART_USE_PORTABLE_COMPILER)
489 copy->SetEntryPointFromCompiledCode(GetOatAddress(portable_resolution_trampoline_offset_));
490#else
491 copy->SetEntryPointFromCompiledCode(GetOatAddress(quick_resolution_trampoline_offset_));
492#endif
Brian Carlstrom7940e442013-07-12 13:46:57 -0700493 } else {
Ian Rogers848871b2013-08-05 10:56:33 -0700494 // We assume all methods have code. If they don't currently then we set them to the use the
495 // resolution trampoline. Abstract methods never have code and so we need to make sure their
496 // use results in an AbstractMethodError. We use the interpreter to achieve this.
497 if (UNLIKELY(orig->IsAbstract())) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700498#if defined(ART_USE_PORTABLE_COMPILER)
Ian Rogers848871b2013-08-05 10:56:33 -0700499 copy->SetEntryPointFromCompiledCode(GetOatAddress(portable_to_interpreter_bridge_offset_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700500#else
Ian Rogers848871b2013-08-05 10:56:33 -0700501 copy->SetEntryPointFromCompiledCode(GetOatAddress(quick_to_interpreter_bridge_offset_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700502#endif
Ian Rogers848871b2013-08-05 10:56:33 -0700503 copy->SetEntryPointFromInterpreter(reinterpret_cast<EntryPointFromInterpreter*>
504 (GetOatAddress(interpreter_to_interpreter_bridge_offset_)));
505 } else {
506 copy->SetEntryPointFromInterpreter(reinterpret_cast<EntryPointFromInterpreter*>
507 (GetOatAddress(interpreter_to_compiled_code_bridge_offset_)));
508 // Use original code if it exists. Otherwise, set the code pointer to the resolution
509 // trampoline.
510 const byte* code = GetOatAddress(orig->GetOatCodeOffset());
511 if (code != NULL) {
512 copy->SetEntryPointFromCompiledCode(code);
513 } else {
514#if defined(ART_USE_PORTABLE_COMPILER)
515 copy->SetEntryPointFromCompiledCode(GetOatAddress(portable_resolution_trampoline_offset_));
516#else
517 copy->SetEntryPointFromCompiledCode(GetOatAddress(quick_resolution_trampoline_offset_));
518#endif
519 }
520 if (orig->IsNative()) {
521 // The native method's pointer is set to a stub to lookup via dlsym.
522 // Note this is not the code_ pointer, that is handled above.
523 copy->SetNativeMethod(GetOatAddress(jni_dlsym_lookup_offset_));
524 } else {
525 // Normal (non-abstract non-native) methods have various tables to relocate.
526 uint32_t mapping_table_off = orig->GetOatMappingTableOffset();
527 const byte* mapping_table = GetOatAddress(mapping_table_off);
Ian Rogers1809a722013-08-09 22:05:32 -0700528 copy->SetMappingTable(mapping_table);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700529
Ian Rogers848871b2013-08-05 10:56:33 -0700530 uint32_t vmap_table_offset = orig->GetOatVmapTableOffset();
531 const byte* vmap_table = GetOatAddress(vmap_table_offset);
Ian Rogers1809a722013-08-09 22:05:32 -0700532 copy->SetVmapTable(vmap_table);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700533
Ian Rogers848871b2013-08-05 10:56:33 -0700534 uint32_t native_gc_map_offset = orig->GetOatNativeGcMapOffset();
535 const byte* native_gc_map = GetOatAddress(native_gc_map_offset);
536 copy->SetNativeGcMap(reinterpret_cast<const uint8_t*>(native_gc_map));
537 }
538 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700539 }
540}
541
542void ImageWriter::FixupObjectArray(const ObjectArray<Object>* orig, ObjectArray<Object>* copy) {
543 for (int32_t i = 0; i < orig->GetLength(); ++i) {
544 const Object* element = orig->Get(i);
545 copy->SetPtrWithoutChecks(i, GetImageAddress(element));
546 }
547}
548
549void ImageWriter::FixupInstanceFields(const Object* orig, Object* copy) {
550 DCHECK(orig != NULL);
551 DCHECK(copy != NULL);
552 Class* klass = orig->GetClass();
553 DCHECK(klass != NULL);
554 FixupFields(orig,
555 copy,
556 klass->GetReferenceInstanceOffsets(),
557 false);
558}
559
560void ImageWriter::FixupStaticFields(const Class* orig, Class* copy) {
561 DCHECK(orig != NULL);
562 DCHECK(copy != NULL);
563 FixupFields(orig,
564 copy,
565 orig->GetReferenceStaticOffsets(),
566 true);
567}
568
569void ImageWriter::FixupFields(const Object* orig,
570 Object* copy,
571 uint32_t ref_offsets,
572 bool is_static) {
573 if (ref_offsets != CLASS_WALK_SUPER) {
574 // Found a reference offset bitmap. Fixup the specified offsets.
575 while (ref_offsets != 0) {
576 size_t right_shift = CLZ(ref_offsets);
577 MemberOffset byte_offset = CLASS_OFFSET_FROM_CLZ(right_shift);
578 const Object* ref = orig->GetFieldObject<const Object*>(byte_offset, false);
579 // Use SetFieldPtr to avoid card marking since we are writing to the image.
580 copy->SetFieldPtr(byte_offset, GetImageAddress(ref), false);
581 ref_offsets &= ~(CLASS_HIGH_BIT >> right_shift);
582 }
583 } else {
584 // There is no reference offset bitmap. In the non-static case,
585 // walk up the class inheritance hierarchy and find reference
586 // offsets the hard way. In the static case, just consider this
587 // class.
588 for (const Class *klass = is_static ? orig->AsClass() : orig->GetClass();
589 klass != NULL;
590 klass = is_static ? NULL : klass->GetSuperClass()) {
591 size_t num_reference_fields = (is_static
592 ? klass->NumReferenceStaticFields()
593 : klass->NumReferenceInstanceFields());
594 for (size_t i = 0; i < num_reference_fields; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700595 ArtField* field = (is_static
596 ? klass->GetStaticField(i)
597 : klass->GetInstanceField(i));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700598 MemberOffset field_offset = field->GetOffset();
599 const Object* ref = orig->GetFieldObject<const Object*>(field_offset, false);
600 // Use SetFieldPtr to avoid card marking since we are writing to the image.
601 copy->SetFieldPtr(field_offset, GetImageAddress(ref), false);
602 }
603 }
604 }
605 if (!is_static && orig->IsReferenceInstance()) {
606 // Fix-up referent, that isn't marked as an object field, for References.
Brian Carlstromea46f952013-07-30 01:26:50 -0700607 ArtField* field = orig->GetClass()->FindInstanceField("referent", "Ljava/lang/Object;");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700608 MemberOffset field_offset = field->GetOffset();
609 const Object* ref = orig->GetFieldObject<const Object*>(field_offset, false);
610 // Use SetFieldPtr to avoid card marking since we are writing to the image.
611 copy->SetFieldPtr(field_offset, GetImageAddress(ref), false);
612 }
613}
614
Brian Carlstromea46f952013-07-30 01:26:50 -0700615static ArtMethod* GetTargetMethod(const CompilerDriver::PatchInformation* patch)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700616 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
617 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
618 DexCache* dex_cache = class_linker->FindDexCache(patch->GetDexFile());
Brian Carlstromea46f952013-07-30 01:26:50 -0700619 ArtMethod* method = class_linker->ResolveMethod(patch->GetDexFile(),
620 patch->GetTargetMethodIdx(),
621 dex_cache,
622 NULL,
623 NULL,
624 patch->GetTargetInvokeType());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700625 CHECK(method != NULL)
626 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
627 CHECK(!method->IsRuntimeMethod())
628 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
629 CHECK(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx()) == method)
630 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
631 << PrettyMethod(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx())) << " "
632 << PrettyMethod(method);
633 return method;
634}
635
636void ImageWriter::PatchOatCodeAndMethods() {
637 Thread* self = Thread::Current();
638 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
639 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
640
641 typedef std::vector<const CompilerDriver::PatchInformation*> Patches;
642 const Patches& code_to_patch = compiler_driver_.GetCodeToPatch();
643 for (size_t i = 0; i < code_to_patch.size(); i++) {
644 const CompilerDriver::PatchInformation* patch = code_to_patch[i];
Brian Carlstromea46f952013-07-30 01:26:50 -0700645 ArtMethod* target = GetTargetMethod(patch);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700646 uint32_t code = reinterpret_cast<uint32_t>(class_linker->GetOatCodeFor(target));
647 uint32_t code_base = reinterpret_cast<uint32_t>(&oat_file_->GetOatHeader());
648 uint32_t code_offset = code - code_base;
649 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetOatAddress(code_offset)));
650 }
651
652 const Patches& methods_to_patch = compiler_driver_.GetMethodsToPatch();
653 for (size_t i = 0; i < methods_to_patch.size(); i++) {
654 const CompilerDriver::PatchInformation* patch = methods_to_patch[i];
Brian Carlstromea46f952013-07-30 01:26:50 -0700655 ArtMethod* target = GetTargetMethod(patch);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700656 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetImageAddress(target)));
657 }
658
659 // Update the image header with the new checksum after patching
660 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
661 image_header->SetOatChecksum(oat_file_->GetOatHeader().GetChecksum());
662 self->EndAssertNoThreadSuspension(old_cause);
663}
664
665void ImageWriter::SetPatchLocation(const CompilerDriver::PatchInformation* patch, uint32_t value) {
666 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
667 const void* oat_code = class_linker->GetOatCodeFor(patch->GetDexFile(),
668 patch->GetReferrerMethodIdx());
669 OatHeader& oat_header = const_cast<OatHeader&>(oat_file_->GetOatHeader());
670 // TODO: make this Thumb2 specific
671 uint8_t* base = reinterpret_cast<uint8_t*>(reinterpret_cast<uint32_t>(oat_code) & ~0x1);
672 uint32_t* patch_location = reinterpret_cast<uint32_t*>(base + patch->GetLiteralOffset());
673#ifndef NDEBUG
674 const DexFile::MethodId& id = patch->GetDexFile().GetMethodId(patch->GetTargetMethodIdx());
675 uint32_t expected = reinterpret_cast<uint32_t>(&id);
676 uint32_t actual = *patch_location;
677 CHECK(actual == expected || actual == value) << std::hex
678 << "actual=" << actual
679 << "expected=" << expected
680 << "value=" << value;
681#endif
682 *patch_location = value;
683 oat_header.UpdateChecksum(patch_location, sizeof(value));
684}
685
686} // namespace art