image_writer.cc revision 637c65b1e431fd90195b71c141b3590bd81cc91a
1/* 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 "compiler/driver/compiler_driver.h" 28#include "dex_file-inl.h" 29#include "gc/card_table-inl.h" 30#include "gc/large_object_space.h" 31#include "gc/space.h" 32#include "globals.h" 33#include "heap.h" 34#include "image.h" 35#include "intern_table.h" 36#include "mirror/array-inl.h" 37#include "mirror/class-inl.h" 38#include "mirror/class_loader.h" 39#include "mirror/dex_cache-inl.h" 40#include "mirror/field-inl.h" 41#include "mirror/abstract_method-inl.h" 42#include "mirror/object-inl.h" 43#include "mirror/object_array-inl.h" 44#include "oat.h" 45#include "oat_file.h" 46#include "object_utils.h" 47#include "runtime.h" 48#include "scoped_thread_state_change.h" 49#include "sirt_ref.h" 50#include "UniquePtr.h" 51#include "utils.h" 52 53using namespace art::mirror; 54 55namespace art { 56 57bool ImageWriter::Write(const std::string& image_filename, 58 uintptr_t image_begin, 59 const std::string& oat_filename, 60 const std::string& oat_location, 61 const CompilerDriver& compiler_driver) { 62 CHECK(!image_filename.empty()); 63 64 CHECK_NE(image_begin, 0U); 65 image_begin_ = reinterpret_cast<byte*>(image_begin); 66 67 Heap* heap = Runtime::Current()->GetHeap(); 68 const Spaces& spaces = heap->GetSpaces(); 69 70 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 71 const std::vector<DexCache*>& all_dex_caches = class_linker->GetDexCaches(); 72 for (size_t i = 0; i < all_dex_caches.size(); i++) { 73 DexCache* dex_cache = all_dex_caches[i]; 74 dex_caches_.insert(dex_cache); 75 } 76 77 UniquePtr<File> oat_file(OS::OpenFile(oat_filename.c_str(), true, false)); 78 if (oat_file.get() == NULL) { 79 LOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location; 80 return false; 81 } 82 oat_file_ = OatFile::OpenWritable(oat_file.get(), oat_location); 83 class_linker->RegisterOatFile(*oat_file_); 84 85 { 86 Thread::Current()->TransitionFromSuspendedToRunnable(); 87 PruneNonImageClasses(); // Remove junk 88 ComputeLazyFieldsForImageClasses(); // Add useful information 89 ComputeEagerResolvedStrings(); 90 Thread::Current()->TransitionFromRunnableToSuspended(kNative); 91 } 92 heap->CollectGarbage(false); // Remove garbage 93 // Trim size of alloc spaces 94 // TODO: C++0x auto 95 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) { 96 if ((*cur)->IsAllocSpace()) { 97 (*cur)->AsAllocSpace()->Trim(); 98 } 99 } 100 101 if (!AllocMemory()) { 102 return false; 103 } 104#ifndef NDEBUG 105 { 106 ScopedObjectAccess soa(Thread::Current()); 107 CheckNonImageClassesRemoved(); 108 } 109#endif 110 Thread::Current()->TransitionFromSuspendedToRunnable(); 111 size_t oat_loaded_size = 0; 112 size_t oat_data_offset = 0; 113 compiler_driver.GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset); 114 CalculateNewObjectOffsets(oat_loaded_size, oat_data_offset); 115 CopyAndFixupObjects(); 116 PatchOatCodeAndMethods(compiler_driver); 117 Thread::Current()->TransitionFromRunnableToSuspended(kNative); 118 119 UniquePtr<File> image_file(OS::OpenFile(image_filename.c_str(), true)); 120 if (image_file.get() == NULL) { 121 LOG(ERROR) << "Failed to open image file " << image_filename; 122 return false; 123 } 124 if (fchmod(image_file->Fd(), 0644) != 0) { 125 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename; 126 return EXIT_FAILURE; 127 } 128 bool success = image_file->WriteFully(image_->Begin(), image_end_); 129 if (!success) { 130 PLOG(ERROR) << "Failed to write image file " << image_filename; 131 return false; 132 } 133 return true; 134} 135 136bool ImageWriter::AllocMemory() { 137 const Spaces& spaces = Runtime::Current()->GetHeap()->GetSpaces(); 138 size_t size = 0; 139 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) { 140 if ((*it)->IsAllocSpace()) { 141 size += (*it)->Size(); 142 } 143 } 144 145 int prot = PROT_READ | PROT_WRITE; 146 size_t length = RoundUp(size, kPageSize); 147 image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, prot)); 148 if (image_.get() == NULL) { 149 LOG(ERROR) << "Failed to allocate memory for image file generation"; 150 return false; 151 } 152 return true; 153} 154 155void ImageWriter::ComputeLazyFieldsForImageClasses() { 156 Runtime* runtime = Runtime::Current(); 157 ClassLinker* class_linker = runtime->GetClassLinker(); 158 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL); 159} 160 161bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) { 162 c->ComputeName(); 163 return true; 164} 165 166void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg) { 167 if (!obj->GetClass()->IsStringClass()) { 168 return; 169 } 170 String* string = obj->AsString(); 171 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset(); 172 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg); 173 typedef Set::const_iterator CacheIt; // TODO: C++0x auto 174 for (CacheIt it = writer->dex_caches_.begin(), end = writer->dex_caches_.end(); it != end; ++it) { 175 DexCache* dex_cache = *it; 176 const DexFile& dex_file = *dex_cache->GetDexFile(); 177 const DexFile::StringId* string_id = dex_file.FindStringId(utf16_string); 178 if (string_id != NULL) { 179 // This string occurs in this dex file, assign the dex cache entry. 180 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id); 181 if (dex_cache->GetResolvedString(string_idx) == NULL) { 182 dex_cache->SetResolvedString(string_idx, string); 183 } 184 } 185 } 186} 187 188void ImageWriter::ComputeEagerResolvedStrings() 189 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 190 // TODO: Check image spaces only? 191 Heap* heap = Runtime::Current()->GetHeap(); 192 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_); 193 heap->FlushAllocStack(); 194 heap->GetLiveBitmap()->Walk(ComputeEagerResolvedStringsCallback, this); 195} 196 197bool ImageWriter::IsImageClass(const Class* klass) { 198 if (image_classes_ == NULL) { 199 return true; 200 } 201 while (klass->IsArrayClass()) { 202 klass = klass->GetComponentType(); 203 } 204 if (klass->IsPrimitive()) { 205 return true; 206 } 207 const std::string descriptor(ClassHelper(klass).GetDescriptor()); 208 return image_classes_->find(descriptor) != image_classes_->end(); 209} 210 211 212struct NonImageClasses { 213 ImageWriter* image_writer; 214 std::set<std::string>* non_image_classes; 215}; 216 217void ImageWriter::PruneNonImageClasses() { 218 if (image_classes_ == NULL) { 219 return; 220 } 221 Runtime* runtime = Runtime::Current(); 222 ClassLinker* class_linker = runtime->GetClassLinker(); 223 224 std::set<std::string> non_image_classes; 225 NonImageClasses context; 226 context.image_writer = this; 227 context.non_image_classes = &non_image_classes; 228 class_linker->VisitClasses(NonImageClassesVisitor, &context); 229 230 typedef std::set<std::string>::const_iterator ClassIt; // TODO: C++0x auto 231 for (ClassIt it = non_image_classes.begin(), end = non_image_classes.end(); it != end; ++it) { 232 class_linker->RemoveClass((*it).c_str(), NULL); 233 } 234 235 AbstractMethod* resolution_method = runtime->GetResolutionMethod(); 236 typedef Set::const_iterator CacheIt; // TODO: C++0x auto 237 for (CacheIt it = dex_caches_.begin(), end = dex_caches_.end(); it != end; ++it) { 238 DexCache* dex_cache = *it; 239 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) { 240 Class* klass = dex_cache->GetResolvedType(i); 241 if (klass != NULL && !IsImageClass(klass)) { 242 dex_cache->SetResolvedType(i, NULL); 243 dex_cache->GetInitializedStaticStorage()->Set(i, NULL); 244 } 245 } 246 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) { 247 AbstractMethod* method = dex_cache->GetResolvedMethod(i); 248 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) { 249 dex_cache->SetResolvedMethod(i, resolution_method); 250 } 251 } 252 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) { 253 Field* field = dex_cache->GetResolvedField(i); 254 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) { 255 dex_cache->SetResolvedField(i, NULL); 256 } 257 } 258 } 259} 260 261bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) { 262 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg); 263 if (!context->image_writer->IsImageClass(klass)) { 264 context->non_image_classes->insert(ClassHelper(klass).GetDescriptor()); 265 } 266 return true; 267} 268 269void ImageWriter::CheckNonImageClassesRemoved() 270 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 271 if (image_classes_ == NULL) { 272 return; 273 } 274 275 Heap* heap = Runtime::Current()->GetHeap(); 276 Thread* self = Thread::Current(); 277 { 278 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 279 heap->FlushAllocStack(); 280 } 281 282 ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_); 283 heap->GetLiveBitmap()->Walk(CheckNonImageClassesRemovedCallback, this); 284} 285 286void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) { 287 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg); 288 if (!obj->IsClass()) { 289 return; 290 } 291 Class* klass = obj->AsClass(); 292 if (!image_writer->IsImageClass(klass)) { 293 image_writer->DumpImageClasses(); 294 CHECK(image_writer->IsImageClass(klass)) << ClassHelper(klass).GetDescriptor() 295 << " " << PrettyDescriptor(klass); 296 } 297} 298 299void ImageWriter::DumpImageClasses() { 300 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto 301 for (It it = image_classes_->begin(), end = image_classes_->end(); it != end; ++it) { 302 LOG(INFO) << " " << *it; 303 } 304} 305 306void ImageWriter::CalculateNewObjectOffsetsCallback(Object* obj, void* arg) { 307 DCHECK(obj != NULL); 308 DCHECK(arg != NULL); 309 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg); 310 311 // if it is a string, we want to intern it if its not interned. 312 if (obj->GetClass()->IsStringClass()) { 313 // we must be an interned string that was forward referenced and already assigned 314 if (image_writer->IsImageOffsetAssigned(obj)) { 315 DCHECK_EQ(obj, obj->AsString()->Intern()); 316 return; 317 } 318 SirtRef<String> interned(Thread::Current(), obj->AsString()->Intern()); 319 if (obj != interned.get()) { 320 if (!image_writer->IsImageOffsetAssigned(interned.get())) { 321 // interned obj is after us, allocate its location early 322 image_writer->AssignImageOffset(interned.get()); 323 } 324 // point those looking for this object to the interned version. 325 image_writer->SetImageOffset(obj, image_writer->GetImageOffset(interned.get())); 326 return; 327 } 328 // else (obj == interned), nothing to do but fall through to the normal case 329 } 330 331 image_writer->AssignImageOffset(obj); 332} 333 334ObjectArray<Object>* ImageWriter::CreateImageRoots() const { 335 Runtime* runtime = Runtime::Current(); 336 ClassLinker* class_linker = runtime->GetClassLinker(); 337 Class* object_array_class = class_linker->FindSystemClass("[Ljava/lang/Object;"); 338 Thread* self = Thread::Current(); 339 340 // build an Object[] of all the DexCaches used in the source_space_ 341 ObjectArray<Object>* dex_caches = ObjectArray<Object>::Alloc(self, object_array_class, 342 dex_caches_.size()); 343 int i = 0; 344 typedef Set::const_iterator It; // TODO: C++0x auto 345 for (It it = dex_caches_.begin(), end = dex_caches_.end(); it != end; ++it, ++i) { 346 dex_caches->Set(i, *it); 347 } 348 349 // build an Object[] of the roots needed to restore the runtime 350 SirtRef<ObjectArray<Object> > 351 image_roots(self, 352 ObjectArray<Object>::Alloc(self, object_array_class, 353 ImageHeader::kImageRootsMax)); 354 image_roots->Set(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod()); 355 image_roots->Set(ImageHeader::kCalleeSaveMethod, 356 runtime->GetCalleeSaveMethod(Runtime::kSaveAll)); 357 image_roots->Set(ImageHeader::kRefsOnlySaveMethod, 358 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly)); 359 image_roots->Set(ImageHeader::kRefsAndArgsSaveMethod, 360 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs)); 361 image_roots->Set(ImageHeader::kOatLocation, 362 String::AllocFromModifiedUtf8(self, oat_file_->GetLocation().c_str())); 363 image_roots->Set(ImageHeader::kDexCaches, 364 dex_caches); 365 image_roots->Set(ImageHeader::kClassRoots, 366 class_linker->GetClassRoots()); 367 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) { 368 CHECK(image_roots->Get(i) != NULL); 369 } 370 return image_roots.get(); 371} 372 373void ImageWriter::CalculateNewObjectOffsets(size_t oat_loaded_size, size_t oat_data_offset) { 374 CHECK_NE(0U, oat_loaded_size); 375 Thread* self = Thread::Current(); 376 SirtRef<ObjectArray<Object> > image_roots(self, CreateImageRoots()); 377 378 Heap* heap = Runtime::Current()->GetHeap(); 379 const Spaces& spaces = heap->GetSpaces(); 380 DCHECK(!spaces.empty()); 381 DCHECK_EQ(0U, image_end_); 382 383 // leave space for the header, but do not write it yet, we need to 384 // know where image_roots is going to end up 385 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment 386 387 { 388 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 389 heap->FlushAllocStack(); 390 // TODO: Image spaces only? 391 // TODO: Add InOrderWalk to heap bitmap. 392 const char* old = self->StartAssertNoThreadSuspension("ImageWriter"); 393 DCHECK(heap->GetLargeObjectsSpace()->GetLiveObjects()->IsEmpty()); 394 for (Spaces::const_iterator it = spaces.begin(); it != spaces.end(); ++it) { 395 (*it)->GetLiveBitmap()->InOrderWalk(CalculateNewObjectOffsetsCallback, this); 396 DCHECK_LT(image_end_, image_->Size()); 397 } 398 self->EndAssertNoThreadSuspension(old); 399 } 400 401 const byte* oat_file_begin = image_begin_ + RoundUp(image_end_, kPageSize); 402 const byte* oat_file_end = oat_file_begin + oat_loaded_size; 403 oat_data_begin_ = oat_file_begin + oat_data_offset; 404 const byte* oat_data_end = oat_data_begin_ + oat_file_->Size(); 405 406 // return to write header at start of image with future location of image_roots 407 ImageHeader image_header(reinterpret_cast<uint32_t>(image_begin_), 408 reinterpret_cast<uint32_t>(GetImageAddress(image_roots.get())), 409 oat_file_->GetOatHeader().GetChecksum(), 410 reinterpret_cast<uint32_t>(oat_file_begin), 411 reinterpret_cast<uint32_t>(oat_data_begin_), 412 reinterpret_cast<uint32_t>(oat_data_end), 413 reinterpret_cast<uint32_t>(oat_file_end)); 414 memcpy(image_->Begin(), &image_header, sizeof(image_header)); 415 416 // Note that image_end_ is left at end of used space 417} 418 419void ImageWriter::CopyAndFixupObjects() 420 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 421 Thread* self = Thread::Current(); 422 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter"); 423 Heap* heap = Runtime::Current()->GetHeap(); 424 // TODO: heap validation can't handle this fix up pass 425 heap->DisableObjectValidation(); 426 // TODO: Image spaces only? 427 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_); 428 heap->FlushAllocStack(); 429 heap->GetLiveBitmap()->Walk(CopyAndFixupObjectsCallback, this); 430 self->EndAssertNoThreadSuspension(old_cause); 431} 432 433void ImageWriter::CopyAndFixupObjectsCallback(Object* object, void* arg) { 434 DCHECK(object != NULL); 435 DCHECK(arg != NULL); 436 const Object* obj = object; 437 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg); 438 439 // see GetLocalAddress for similar computation 440 size_t offset = image_writer->GetImageOffset(obj); 441 byte* dst = image_writer->image_->Begin() + offset; 442 const byte* src = reinterpret_cast<const byte*>(obj); 443 size_t n = obj->SizeOf(); 444 DCHECK_LT(offset + n, image_writer->image_->Size()); 445 memcpy(dst, src, n); 446 Object* copy = reinterpret_cast<Object*>(dst); 447 copy->SetField32(Object::MonitorOffset(), 0, false); // We may have inflated the lock during compilation. 448 image_writer->FixupObject(obj, copy); 449} 450 451void ImageWriter::FixupObject(const Object* orig, Object* copy) { 452 DCHECK(orig != NULL); 453 DCHECK(copy != NULL); 454 copy->SetClass(down_cast<Class*>(GetImageAddress(orig->GetClass()))); 455 // TODO: special case init of pointers to malloc data (or removal of these pointers) 456 if (orig->IsClass()) { 457 FixupClass(orig->AsClass(), down_cast<Class*>(copy)); 458 } else if (orig->IsObjectArray()) { 459 FixupObjectArray(orig->AsObjectArray<Object>(), down_cast<ObjectArray<Object>*>(copy)); 460 } else if (orig->IsMethod()) { 461 FixupMethod(orig->AsMethod(), down_cast<AbstractMethod*>(copy)); 462 } else { 463 FixupInstanceFields(orig, copy); 464 } 465} 466 467void ImageWriter::FixupClass(const Class* orig, Class* copy) { 468 FixupInstanceFields(orig, copy); 469 FixupStaticFields(orig, copy); 470} 471 472void ImageWriter::FixupMethod(const AbstractMethod* orig, AbstractMethod* copy) { 473 FixupInstanceFields(orig, copy); 474 475 // OatWriter replaces the code_ with an offset value. 476 // Here we readjust to a pointer relative to oat_begin_ 477 if (orig->IsAbstract()) { 478 // Code for abstract methods is set to the abstract method error stub when we load the image. 479 copy->SetEntryPointFromCompiledCode(NULL); 480 return; 481 } 482 483 if (orig == Runtime::Current()->GetResolutionMethod()) { 484 // The resolution method's code is set to the resolution trampoline when we load the image. 485 copy->SetEntryPointFromCompiledCode(NULL); 486 return; 487 } 488 489 // Non-abstract methods have code 490 copy->SetEntryPointFromCompiledCode(GetOatAddress(orig->GetOatCodeOffset())); 491 492 if (orig->IsNative()) { 493 // The native method's pointer is set to a stub to lookup via dlsym when we load the image. 494 // Note this is not the code_ pointer, that is handled above. 495 copy->SetNativeMethod(NULL); 496 } else { 497 // normal (non-abstract non-native) methods have mapping tables to relocate 498 uint32_t mapping_table_off = orig->GetOatMappingTableOffset(); 499 const byte* mapping_table = GetOatAddress(mapping_table_off); 500 copy->SetMappingTable(reinterpret_cast<const uint32_t*>(mapping_table)); 501 502 uint32_t vmap_table_offset = orig->GetOatVmapTableOffset(); 503 const byte* vmap_table = GetOatAddress(vmap_table_offset); 504 copy->SetVmapTable(reinterpret_cast<const uint16_t*>(vmap_table)); 505 506 uint32_t native_gc_map_offset = orig->GetOatNativeGcMapOffset(); 507 const byte* native_gc_map = GetOatAddress(native_gc_map_offset); 508 copy->SetNativeGcMap(reinterpret_cast<const uint8_t*>(native_gc_map)); 509 } 510} 511 512void ImageWriter::FixupObjectArray(const ObjectArray<Object>* orig, ObjectArray<Object>* copy) { 513 for (int32_t i = 0; i < orig->GetLength(); ++i) { 514 const Object* element = orig->Get(i); 515 copy->SetPtrWithoutChecks(i, GetImageAddress(element)); 516 } 517} 518 519void ImageWriter::FixupInstanceFields(const Object* orig, Object* copy) { 520 DCHECK(orig != NULL); 521 DCHECK(copy != NULL); 522 Class* klass = orig->GetClass(); 523 DCHECK(klass != NULL); 524 FixupFields(orig, 525 copy, 526 klass->GetReferenceInstanceOffsets(), 527 false); 528} 529 530void ImageWriter::FixupStaticFields(const Class* orig, Class* copy) { 531 DCHECK(orig != NULL); 532 DCHECK(copy != NULL); 533 FixupFields(orig, 534 copy, 535 orig->GetReferenceStaticOffsets(), 536 true); 537} 538 539void ImageWriter::FixupFields(const Object* orig, 540 Object* copy, 541 uint32_t ref_offsets, 542 bool is_static) { 543 if (ref_offsets != CLASS_WALK_SUPER) { 544 // Found a reference offset bitmap. Fixup the specified offsets. 545 while (ref_offsets != 0) { 546 size_t right_shift = CLZ(ref_offsets); 547 MemberOffset byte_offset = CLASS_OFFSET_FROM_CLZ(right_shift); 548 const Object* ref = orig->GetFieldObject<const Object*>(byte_offset, false); 549 // Use SetFieldPtr to avoid card marking since we are writing to the image. 550 copy->SetFieldPtr(byte_offset, GetImageAddress(ref), false); 551 ref_offsets &= ~(CLASS_HIGH_BIT >> right_shift); 552 } 553 } else { 554 // There is no reference offset bitmap. In the non-static case, 555 // walk up the class inheritance hierarchy and find reference 556 // offsets the hard way. In the static case, just consider this 557 // class. 558 for (const Class *klass = is_static ? orig->AsClass() : orig->GetClass(); 559 klass != NULL; 560 klass = is_static ? NULL : klass->GetSuperClass()) { 561 size_t num_reference_fields = (is_static 562 ? klass->NumReferenceStaticFields() 563 : klass->NumReferenceInstanceFields()); 564 for (size_t i = 0; i < num_reference_fields; ++i) { 565 Field* field = (is_static 566 ? klass->GetStaticField(i) 567 : klass->GetInstanceField(i)); 568 MemberOffset field_offset = field->GetOffset(); 569 const Object* ref = orig->GetFieldObject<const Object*>(field_offset, false); 570 // Use SetFieldPtr to avoid card marking since we are writing to the image. 571 copy->SetFieldPtr(field_offset, GetImageAddress(ref), false); 572 } 573 } 574 } 575 if (!is_static && orig->IsReferenceInstance()) { 576 // Fix-up referent, that isn't marked as an object field, for References. 577 Field* field = orig->GetClass()->FindInstanceField("referent", "Ljava/lang/Object;"); 578 MemberOffset field_offset = field->GetOffset(); 579 const Object* ref = orig->GetFieldObject<const Object*>(field_offset, false); 580 // Use SetFieldPtr to avoid card marking since we are writing to the image. 581 copy->SetFieldPtr(field_offset, GetImageAddress(ref), false); 582 } 583} 584 585static AbstractMethod* GetTargetMethod(const CompilerDriver::PatchInformation* patch) 586 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 587 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 588 DexCache* dex_cache = class_linker->FindDexCache(patch->GetDexFile()); 589 AbstractMethod* method = class_linker->ResolveMethod(patch->GetDexFile(), 590 patch->GetTargetMethodIdx(), 591 dex_cache, 592 NULL, 593 NULL, 594 patch->GetTargetInvokeType()); 595 CHECK(method != NULL) 596 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx(); 597 CHECK(!method->IsRuntimeMethod()) 598 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx(); 599 CHECK(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx()) == method) 600 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " " 601 << PrettyMethod(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx())) << " " 602 << PrettyMethod(method); 603 return method; 604} 605 606void ImageWriter::PatchOatCodeAndMethods(const CompilerDriver& compiler) { 607 Thread* self = Thread::Current(); 608 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 609 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter"); 610 611 typedef std::vector<const CompilerDriver::PatchInformation*> Patches; 612 const Patches& code_to_patch = compiler.GetCodeToPatch(); 613 for (size_t i = 0; i < code_to_patch.size(); i++) { 614 const CompilerDriver::PatchInformation* patch = code_to_patch[i]; 615 AbstractMethod* target = GetTargetMethod(patch); 616 uint32_t code = reinterpret_cast<uint32_t>(class_linker->GetOatCodeFor(target)); 617 uint32_t code_base = reinterpret_cast<uint32_t>(&oat_file_->GetOatHeader()); 618 uint32_t code_offset = code - code_base; 619 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetOatAddress(code_offset))); 620 } 621 622 const Patches& methods_to_patch = compiler.GetMethodsToPatch(); 623 for (size_t i = 0; i < methods_to_patch.size(); i++) { 624 const CompilerDriver::PatchInformation* patch = methods_to_patch[i]; 625 AbstractMethod* target = GetTargetMethod(patch); 626 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetImageAddress(target))); 627 } 628 629 // Update the image header with the new checksum after patching 630 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin()); 631 image_header->SetOatChecksum(oat_file_->GetOatHeader().GetChecksum()); 632 self->EndAssertNoThreadSuspension(old_cause); 633} 634 635void ImageWriter::SetPatchLocation(const CompilerDriver::PatchInformation* patch, uint32_t value) { 636 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 637 const void* oat_code = class_linker->GetOatCodeFor(patch->GetDexFile(), 638 patch->GetReferrerMethodIdx()); 639 OatHeader& oat_header = const_cast<OatHeader&>(oat_file_->GetOatHeader()); 640 // TODO: make this Thumb2 specific 641 uint8_t* base = reinterpret_cast<uint8_t*>(reinterpret_cast<uint32_t>(oat_code) & ~0x1); 642 uint32_t* patch_location = reinterpret_cast<uint32_t*>(base + patch->GetLiteralOffset()); 643#ifndef NDEBUG 644 const DexFile::MethodId& id = patch->GetDexFile().GetMethodId(patch->GetTargetMethodIdx()); 645 uint32_t expected = reinterpret_cast<uint32_t>(&id); 646 uint32_t actual = *patch_location; 647 CHECK(actual == expected || actual == value) << std::hex 648 << "actual=" << actual 649 << "expected=" << expected 650 << "value=" << value; 651#endif 652 *patch_location = value; 653 oat_header.UpdateChecksum(patch_location, sizeof(value)); 654} 655 656} // namespace art 657