1 //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file declares the COFFObjectFile class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Object/COFF.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/SmallString.h" 17 #include "llvm/ADT/StringSwitch.h" 18 #include "llvm/ADT/Triple.h" 19 #include "llvm/Support/Debug.h" 20 #include "llvm/Support/raw_ostream.h" 21 #include <cctype> 22 23 using namespace llvm; 24 using namespace object; 25 26 using support::ulittle8_t; 27 using support::ulittle16_t; 28 using support::ulittle32_t; 29 using support::little16_t; 30 31 // Returns false if size is greater than the buffer size. And sets ec. 32 static bool checkSize(const MemoryBuffer *M, error_code &EC, uint64_t Size) { 33 if (M->getBufferSize() < Size) { 34 EC = object_error::unexpected_eof; 35 return false; 36 } 37 return true; 38 } 39 40 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m. 41 // Returns unexpected_eof if error. 42 template<typename T> 43 static error_code getObject(const T *&Obj, const MemoryBuffer *M, 44 const uint8_t *Ptr, const size_t Size = sizeof(T)) { 45 uintptr_t Addr = uintptr_t(Ptr); 46 if (Addr + Size < Addr || 47 Addr + Size < Size || 48 Addr + Size > uintptr_t(M->getBufferEnd())) { 49 return object_error::unexpected_eof; 50 } 51 Obj = reinterpret_cast<const T *>(Addr); 52 return object_error::success; 53 } 54 55 const coff_symbol *COFFObjectFile::toSymb(DataRefImpl Ref) const { 56 const coff_symbol *Addr = reinterpret_cast<const coff_symbol*>(Ref.p); 57 58 # ifndef NDEBUG 59 // Verify that the symbol points to a valid entry in the symbol table. 60 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base()); 61 if (Offset < COFFHeader->PointerToSymbolTable 62 || Offset >= COFFHeader->PointerToSymbolTable 63 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol))) 64 report_fatal_error("Symbol was outside of symbol table."); 65 66 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol) 67 == 0 && "Symbol did not point to the beginning of a symbol"); 68 # endif 69 70 return Addr; 71 } 72 73 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const { 74 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p); 75 76 # ifndef NDEBUG 77 // Verify that the section points to a valid entry in the section table. 78 if (Addr < SectionTable 79 || Addr >= (SectionTable + COFFHeader->NumberOfSections)) 80 report_fatal_error("Section was outside of section table."); 81 82 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable); 83 assert(Offset % sizeof(coff_section) == 0 && 84 "Section did not point to the beginning of a section"); 85 # endif 86 87 return Addr; 88 } 89 90 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const { 91 const coff_symbol *Symb = toSymb(Ref); 92 Symb += 1 + Symb->NumberOfAuxSymbols; 93 Ref.p = reinterpret_cast<uintptr_t>(Symb); 94 } 95 96 error_code COFFObjectFile::getSymbolName(DataRefImpl Ref, 97 StringRef &Result) const { 98 const coff_symbol *Symb = toSymb(Ref); 99 return getSymbolName(Symb, Result); 100 } 101 102 error_code COFFObjectFile::getSymbolFileOffset(DataRefImpl Ref, 103 uint64_t &Result) const { 104 const coff_symbol *Symb = toSymb(Ref); 105 const coff_section *Section = NULL; 106 if (error_code EC = getSection(Symb->SectionNumber, Section)) 107 return EC; 108 109 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) 110 Result = UnknownAddressOrSize; 111 else if (Section) 112 Result = Section->PointerToRawData + Symb->Value; 113 else 114 Result = Symb->Value; 115 return object_error::success; 116 } 117 118 error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref, 119 uint64_t &Result) const { 120 const coff_symbol *Symb = toSymb(Ref); 121 const coff_section *Section = NULL; 122 if (error_code EC = getSection(Symb->SectionNumber, Section)) 123 return EC; 124 125 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) 126 Result = UnknownAddressOrSize; 127 else if (Section) 128 Result = Section->VirtualAddress + Symb->Value; 129 else 130 Result = Symb->Value; 131 return object_error::success; 132 } 133 134 error_code COFFObjectFile::getSymbolType(DataRefImpl Ref, 135 SymbolRef::Type &Result) const { 136 const coff_symbol *Symb = toSymb(Ref); 137 Result = SymbolRef::ST_Other; 138 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL && 139 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) { 140 Result = SymbolRef::ST_Unknown; 141 } else if (Symb->getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION) { 142 Result = SymbolRef::ST_Function; 143 } else { 144 uint32_t Characteristics = 0; 145 if (Symb->SectionNumber > 0) { 146 const coff_section *Section = NULL; 147 if (error_code EC = getSection(Symb->SectionNumber, Section)) 148 return EC; 149 Characteristics = Section->Characteristics; 150 } 151 if (Characteristics & COFF::IMAGE_SCN_MEM_READ && 152 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only. 153 Result = SymbolRef::ST_Data; 154 } 155 return object_error::success; 156 } 157 158 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const { 159 const coff_symbol *Symb = toSymb(Ref); 160 uint32_t Result = SymbolRef::SF_None; 161 162 // TODO: Correctly set SF_FormatSpecific, SF_ThreadLocal, SF_Common 163 164 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL && 165 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) 166 Result |= SymbolRef::SF_Undefined; 167 168 // TODO: This are certainly too restrictive. 169 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL) 170 Result |= SymbolRef::SF_Global; 171 172 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL) 173 Result |= SymbolRef::SF_Weak; 174 175 if (Symb->SectionNumber == COFF::IMAGE_SYM_ABSOLUTE) 176 Result |= SymbolRef::SF_Absolute; 177 178 return Result; 179 } 180 181 error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref, 182 uint64_t &Result) const { 183 // FIXME: Return the correct size. This requires looking at all the symbols 184 // in the same section as this symbol, and looking for either the next 185 // symbol, or the end of the section. 186 const coff_symbol *Symb = toSymb(Ref); 187 const coff_section *Section = NULL; 188 if (error_code EC = getSection(Symb->SectionNumber, Section)) 189 return EC; 190 191 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) 192 Result = UnknownAddressOrSize; 193 else if (Section) 194 Result = Section->SizeOfRawData - Symb->Value; 195 else 196 Result = 0; 197 return object_error::success; 198 } 199 200 error_code COFFObjectFile::getSymbolSection(DataRefImpl Ref, 201 section_iterator &Result) const { 202 const coff_symbol *Symb = toSymb(Ref); 203 if (Symb->SectionNumber <= COFF::IMAGE_SYM_UNDEFINED) 204 Result = end_sections(); 205 else { 206 const coff_section *Sec = 0; 207 if (error_code EC = getSection(Symb->SectionNumber, Sec)) return EC; 208 DataRefImpl Ref; 209 Ref.p = reinterpret_cast<uintptr_t>(Sec); 210 Result = section_iterator(SectionRef(Ref, this)); 211 } 212 return object_error::success; 213 } 214 215 error_code COFFObjectFile::getSymbolValue(DataRefImpl Ref, 216 uint64_t &Val) const { 217 report_fatal_error("getSymbolValue unimplemented in COFFObjectFile"); 218 } 219 220 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const { 221 const coff_section *Sec = toSec(Ref); 222 Sec += 1; 223 Ref.p = reinterpret_cast<uintptr_t>(Sec); 224 } 225 226 error_code COFFObjectFile::getSectionName(DataRefImpl Ref, 227 StringRef &Result) const { 228 const coff_section *Sec = toSec(Ref); 229 return getSectionName(Sec, Result); 230 } 231 232 error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref, 233 uint64_t &Result) const { 234 const coff_section *Sec = toSec(Ref); 235 Result = Sec->VirtualAddress; 236 return object_error::success; 237 } 238 239 error_code COFFObjectFile::getSectionSize(DataRefImpl Ref, 240 uint64_t &Result) const { 241 const coff_section *Sec = toSec(Ref); 242 Result = Sec->SizeOfRawData; 243 return object_error::success; 244 } 245 246 error_code COFFObjectFile::getSectionContents(DataRefImpl Ref, 247 StringRef &Result) const { 248 const coff_section *Sec = toSec(Ref); 249 ArrayRef<uint8_t> Res; 250 error_code EC = getSectionContents(Sec, Res); 251 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size()); 252 return EC; 253 } 254 255 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref, 256 uint64_t &Res) const { 257 const coff_section *Sec = toSec(Ref); 258 if (!Sec) 259 return object_error::parse_failed; 260 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1); 261 return object_error::success; 262 } 263 264 error_code COFFObjectFile::isSectionText(DataRefImpl Ref, 265 bool &Result) const { 266 const coff_section *Sec = toSec(Ref); 267 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE; 268 return object_error::success; 269 } 270 271 error_code COFFObjectFile::isSectionData(DataRefImpl Ref, 272 bool &Result) const { 273 const coff_section *Sec = toSec(Ref); 274 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA; 275 return object_error::success; 276 } 277 278 error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref, 279 bool &Result) const { 280 const coff_section *Sec = toSec(Ref); 281 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA; 282 return object_error::success; 283 } 284 285 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref, 286 bool &Result) const { 287 // FIXME: Unimplemented 288 Result = true; 289 return object_error::success; 290 } 291 292 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref, 293 bool &Result) const { 294 const coff_section *Sec = toSec(Ref); 295 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA; 296 return object_error::success; 297 } 298 299 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref, 300 bool &Result) const { 301 // FIXME: Unimplemented. 302 Result = false; 303 return object_error::success; 304 } 305 306 error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref, 307 bool &Result) const { 308 // FIXME: Unimplemented. 309 Result = false; 310 return object_error::success; 311 } 312 313 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef, 314 DataRefImpl SymbRef, 315 bool &Result) const { 316 const coff_section *Sec = toSec(SecRef); 317 const coff_symbol *Symb = toSymb(SymbRef); 318 const coff_section *SymbSec = 0; 319 if (error_code EC = getSection(Symb->SectionNumber, SymbSec)) return EC; 320 if (SymbSec == Sec) 321 Result = true; 322 else 323 Result = false; 324 return object_error::success; 325 } 326 327 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const { 328 const coff_section *Sec = toSec(Ref); 329 DataRefImpl Ret; 330 if (Sec->NumberOfRelocations == 0) 331 Ret.p = 0; 332 else 333 Ret.p = reinterpret_cast<uintptr_t>(base() + Sec->PointerToRelocations); 334 335 return relocation_iterator(RelocationRef(Ret, this)); 336 } 337 338 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const { 339 const coff_section *Sec = toSec(Ref); 340 DataRefImpl Ret; 341 if (Sec->NumberOfRelocations == 0) 342 Ret.p = 0; 343 else 344 Ret.p = reinterpret_cast<uintptr_t>( 345 reinterpret_cast<const coff_relocation*>( 346 base() + Sec->PointerToRelocations) 347 + Sec->NumberOfRelocations); 348 349 return relocation_iterator(RelocationRef(Ret, this)); 350 } 351 352 // Initialize the pointer to the symbol table. 353 error_code COFFObjectFile::initSymbolTablePtr() { 354 if (error_code EC = getObject( 355 SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable, 356 COFFHeader->NumberOfSymbols * sizeof(coff_symbol))) 357 return EC; 358 359 // Find string table. The first four byte of the string table contains the 360 // total size of the string table, including the size field itself. If the 361 // string table is empty, the value of the first four byte would be 4. 362 const uint8_t *StringTableAddr = 363 base() + COFFHeader->PointerToSymbolTable + 364 COFFHeader->NumberOfSymbols * sizeof(coff_symbol); 365 const ulittle32_t *StringTableSizePtr; 366 if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr)) 367 return EC; 368 StringTableSize = *StringTableSizePtr; 369 if (error_code EC = 370 getObject(StringTable, Data, StringTableAddr, StringTableSize)) 371 return EC; 372 373 // Check that the string table is null terminated if has any in it. 374 if (StringTableSize < 4 || 375 (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)) 376 return object_error::parse_failed; 377 return object_error::success; 378 } 379 380 // Returns the file offset for the given RVA. 381 error_code COFFObjectFile::getRvaPtr(uint32_t Rva, uintptr_t &Res) const { 382 for (section_iterator I = begin_sections(), E = end_sections(); I != E; 383 ++I) { 384 const coff_section *Section = getCOFFSection(I); 385 uint32_t SectionStart = Section->VirtualAddress; 386 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize; 387 if (SectionStart <= Rva && Rva < SectionEnd) { 388 uint32_t Offset = Rva - SectionStart; 389 Res = uintptr_t(base()) + Section->PointerToRawData + Offset; 390 return object_error::success; 391 } 392 } 393 return object_error::parse_failed; 394 } 395 396 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name 397 // table entry. 398 error_code COFFObjectFile:: 399 getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const { 400 uintptr_t IntPtr = 0; 401 if (error_code EC = getRvaPtr(Rva, IntPtr)) 402 return EC; 403 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr); 404 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr); 405 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2)); 406 return object_error::success; 407 } 408 409 // Find the import table. 410 error_code COFFObjectFile::initImportTablePtr() { 411 // First, we get the RVA of the import table. If the file lacks a pointer to 412 // the import table, do nothing. 413 const data_directory *DataEntry; 414 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry)) 415 return object_error::success; 416 417 // Do nothing if the pointer to import table is NULL. 418 if (DataEntry->RelativeVirtualAddress == 0) 419 return object_error::success; 420 421 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress; 422 NumberOfImportDirectory = DataEntry->Size / 423 sizeof(import_directory_table_entry); 424 425 // Find the section that contains the RVA. This is needed because the RVA is 426 // the import table's memory address which is different from its file offset. 427 uintptr_t IntPtr = 0; 428 if (error_code EC = getRvaPtr(ImportTableRva, IntPtr)) 429 return EC; 430 ImportDirectory = reinterpret_cast< 431 const import_directory_table_entry *>(IntPtr); 432 return object_error::success; 433 } 434 435 // Find the export table. 436 error_code COFFObjectFile::initExportTablePtr() { 437 // First, we get the RVA of the export table. If the file lacks a pointer to 438 // the export table, do nothing. 439 const data_directory *DataEntry; 440 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry)) 441 return object_error::success; 442 443 // Do nothing if the pointer to export table is NULL. 444 if (DataEntry->RelativeVirtualAddress == 0) 445 return object_error::success; 446 447 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress; 448 uintptr_t IntPtr = 0; 449 if (error_code EC = getRvaPtr(ExportTableRva, IntPtr)) 450 return EC; 451 ExportDirectory = 452 reinterpret_cast<const export_directory_table_entry *>(IntPtr); 453 return object_error::success; 454 } 455 456 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC, 457 bool BufferOwned) 458 : ObjectFile(Binary::ID_COFF, Object, BufferOwned), COFFHeader(0), 459 PE32Header(0), PE32PlusHeader(0), DataDirectory(0), SectionTable(0), 460 SymbolTable(0), StringTable(0), StringTableSize(0), ImportDirectory(0), 461 NumberOfImportDirectory(0), ExportDirectory(0) { 462 // Check that we at least have enough room for a header. 463 if (!checkSize(Data, EC, sizeof(coff_file_header))) return; 464 465 // The current location in the file where we are looking at. 466 uint64_t CurPtr = 0; 467 468 // PE header is optional and is present only in executables. If it exists, 469 // it is placed right after COFF header. 470 bool HasPEHeader = false; 471 472 // Check if this is a PE/COFF file. 473 if (base()[0] == 0x4d && base()[1] == 0x5a) { 474 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte 475 // PE signature to find 'normal' COFF header. 476 if (!checkSize(Data, EC, 0x3c + 8)) return; 477 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c); 478 // Check the PE magic bytes. ("PE\0\0") 479 if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) { 480 EC = object_error::parse_failed; 481 return; 482 } 483 CurPtr += 4; // Skip the PE magic bytes. 484 HasPEHeader = true; 485 } 486 487 if ((EC = getObject(COFFHeader, Data, base() + CurPtr))) 488 return; 489 CurPtr += sizeof(coff_file_header); 490 491 if (HasPEHeader) { 492 const pe32_header *Header; 493 if ((EC = getObject(Header, Data, base() + CurPtr))) 494 return; 495 496 const uint8_t *DataDirAddr; 497 uint64_t DataDirSize; 498 if (Header->Magic == 0x10b) { 499 PE32Header = Header; 500 DataDirAddr = base() + CurPtr + sizeof(pe32_header); 501 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize; 502 } else if (Header->Magic == 0x20b) { 503 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header); 504 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header); 505 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize; 506 } else { 507 // It's neither PE32 nor PE32+. 508 EC = object_error::parse_failed; 509 return; 510 } 511 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize))) 512 return; 513 CurPtr += COFFHeader->SizeOfOptionalHeader; 514 } 515 516 if (COFFHeader->isImportLibrary()) 517 return; 518 519 if ((EC = getObject(SectionTable, Data, base() + CurPtr, 520 COFFHeader->NumberOfSections * sizeof(coff_section)))) 521 return; 522 523 // Initialize the pointer to the symbol table. 524 if (COFFHeader->PointerToSymbolTable != 0) 525 if ((EC = initSymbolTablePtr())) 526 return; 527 528 // Initialize the pointer to the beginning of the import table. 529 if ((EC = initImportTablePtr())) 530 return; 531 532 // Initialize the pointer to the export table. 533 if ((EC = initExportTablePtr())) 534 return; 535 536 EC = object_error::success; 537 } 538 539 symbol_iterator COFFObjectFile::begin_symbols() const { 540 DataRefImpl Ret; 541 Ret.p = reinterpret_cast<uintptr_t>(SymbolTable); 542 return symbol_iterator(SymbolRef(Ret, this)); 543 } 544 545 symbol_iterator COFFObjectFile::end_symbols() const { 546 // The symbol table ends where the string table begins. 547 DataRefImpl Ret; 548 Ret.p = reinterpret_cast<uintptr_t>(StringTable); 549 return symbol_iterator(SymbolRef(Ret, this)); 550 } 551 552 library_iterator COFFObjectFile::begin_libraries_needed() const { 553 // TODO: implement 554 report_fatal_error("Libraries needed unimplemented in COFFObjectFile"); 555 } 556 557 library_iterator COFFObjectFile::end_libraries_needed() const { 558 // TODO: implement 559 report_fatal_error("Libraries needed unimplemented in COFFObjectFile"); 560 } 561 562 StringRef COFFObjectFile::getLoadName() const { 563 // COFF does not have this field. 564 return ""; 565 } 566 567 import_directory_iterator COFFObjectFile::import_directory_begin() const { 568 return import_directory_iterator( 569 ImportDirectoryEntryRef(ImportDirectory, 0, this)); 570 } 571 572 import_directory_iterator COFFObjectFile::import_directory_end() const { 573 return import_directory_iterator( 574 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this)); 575 } 576 577 export_directory_iterator COFFObjectFile::export_directory_begin() const { 578 return export_directory_iterator( 579 ExportDirectoryEntryRef(ExportDirectory, 0, this)); 580 } 581 582 export_directory_iterator COFFObjectFile::export_directory_end() const { 583 if (ExportDirectory == 0) 584 return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this)); 585 ExportDirectoryEntryRef Ref(ExportDirectory, 586 ExportDirectory->AddressTableEntries, this); 587 return export_directory_iterator(Ref); 588 } 589 590 section_iterator COFFObjectFile::begin_sections() const { 591 DataRefImpl Ret; 592 Ret.p = reinterpret_cast<uintptr_t>(SectionTable); 593 return section_iterator(SectionRef(Ret, this)); 594 } 595 596 section_iterator COFFObjectFile::end_sections() const { 597 DataRefImpl Ret; 598 int NumSections = COFFHeader->isImportLibrary() 599 ? 0 : COFFHeader->NumberOfSections; 600 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections); 601 return section_iterator(SectionRef(Ret, this)); 602 } 603 604 uint8_t COFFObjectFile::getBytesInAddress() const { 605 return getArch() == Triple::x86_64 ? 8 : 4; 606 } 607 608 StringRef COFFObjectFile::getFileFormatName() const { 609 switch(COFFHeader->Machine) { 610 case COFF::IMAGE_FILE_MACHINE_I386: 611 return "COFF-i386"; 612 case COFF::IMAGE_FILE_MACHINE_AMD64: 613 return "COFF-x86-64"; 614 default: 615 return "COFF-<unknown arch>"; 616 } 617 } 618 619 unsigned COFFObjectFile::getArch() const { 620 switch(COFFHeader->Machine) { 621 case COFF::IMAGE_FILE_MACHINE_I386: 622 return Triple::x86; 623 case COFF::IMAGE_FILE_MACHINE_AMD64: 624 return Triple::x86_64; 625 default: 626 return Triple::UnknownArch; 627 } 628 } 629 630 // This method is kept here because lld uses this. As soon as we make 631 // lld to use getCOFFHeader, this method will be removed. 632 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const { 633 return getCOFFHeader(Res); 634 } 635 636 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const { 637 Res = COFFHeader; 638 return object_error::success; 639 } 640 641 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const { 642 Res = PE32Header; 643 return object_error::success; 644 } 645 646 error_code 647 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const { 648 Res = PE32PlusHeader; 649 return object_error::success; 650 } 651 652 error_code COFFObjectFile::getDataDirectory(uint32_t Index, 653 const data_directory *&Res) const { 654 // Error if if there's no data directory or the index is out of range. 655 if (!DataDirectory) 656 return object_error::parse_failed; 657 assert(PE32Header || PE32PlusHeader); 658 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize 659 : PE32PlusHeader->NumberOfRvaAndSize; 660 if (Index > NumEnt) 661 return object_error::parse_failed; 662 Res = &DataDirectory[Index]; 663 return object_error::success; 664 } 665 666 error_code COFFObjectFile::getSection(int32_t Index, 667 const coff_section *&Result) const { 668 // Check for special index values. 669 if (Index == COFF::IMAGE_SYM_UNDEFINED || 670 Index == COFF::IMAGE_SYM_ABSOLUTE || 671 Index == COFF::IMAGE_SYM_DEBUG) 672 Result = NULL; 673 else if (Index > 0 && Index <= COFFHeader->NumberOfSections) 674 // We already verified the section table data, so no need to check again. 675 Result = SectionTable + (Index - 1); 676 else 677 return object_error::parse_failed; 678 return object_error::success; 679 } 680 681 error_code COFFObjectFile::getString(uint32_t Offset, 682 StringRef &Result) const { 683 if (StringTableSize <= 4) 684 // Tried to get a string from an empty string table. 685 return object_error::parse_failed; 686 if (Offset >= StringTableSize) 687 return object_error::unexpected_eof; 688 Result = StringRef(StringTable + Offset); 689 return object_error::success; 690 } 691 692 error_code COFFObjectFile::getSymbol(uint32_t Index, 693 const coff_symbol *&Result) const { 694 if (Index < COFFHeader->NumberOfSymbols) 695 Result = SymbolTable + Index; 696 else 697 return object_error::parse_failed; 698 return object_error::success; 699 } 700 701 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol, 702 StringRef &Res) const { 703 // Check for string table entry. First 4 bytes are 0. 704 if (Symbol->Name.Offset.Zeroes == 0) { 705 uint32_t Offset = Symbol->Name.Offset.Offset; 706 if (error_code EC = getString(Offset, Res)) 707 return EC; 708 return object_error::success; 709 } 710 711 if (Symbol->Name.ShortName[7] == 0) 712 // Null terminated, let ::strlen figure out the length. 713 Res = StringRef(Symbol->Name.ShortName); 714 else 715 // Not null terminated, use all 8 bytes. 716 Res = StringRef(Symbol->Name.ShortName, 8); 717 return object_error::success; 718 } 719 720 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData( 721 const coff_symbol *Symbol) const { 722 const uint8_t *Aux = NULL; 723 724 if (Symbol->NumberOfAuxSymbols > 0) { 725 // AUX data comes immediately after the symbol in COFF 726 Aux = reinterpret_cast<const uint8_t *>(Symbol + 1); 727 # ifndef NDEBUG 728 // Verify that the Aux symbol points to a valid entry in the symbol table. 729 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base()); 730 if (Offset < COFFHeader->PointerToSymbolTable 731 || Offset >= COFFHeader->PointerToSymbolTable 732 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol))) 733 report_fatal_error("Aux Symbol data was outside of symbol table."); 734 735 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol) 736 == 0 && "Aux Symbol data did not point to the beginning of a symbol"); 737 # endif 738 } 739 return ArrayRef<uint8_t>(Aux, 740 Symbol->NumberOfAuxSymbols * sizeof(coff_symbol)); 741 } 742 743 error_code COFFObjectFile::getSectionName(const coff_section *Sec, 744 StringRef &Res) const { 745 StringRef Name; 746 if (Sec->Name[7] == 0) 747 // Null terminated, let ::strlen figure out the length. 748 Name = Sec->Name; 749 else 750 // Not null terminated, use all 8 bytes. 751 Name = StringRef(Sec->Name, 8); 752 753 // Check for string table entry. First byte is '/'. 754 if (Name[0] == '/') { 755 uint32_t Offset; 756 if (Name.substr(1).getAsInteger(10, Offset)) 757 return object_error::parse_failed; 758 if (error_code EC = getString(Offset, Name)) 759 return EC; 760 } 761 762 Res = Name; 763 return object_error::success; 764 } 765 766 error_code COFFObjectFile::getSectionContents(const coff_section *Sec, 767 ArrayRef<uint8_t> &Res) const { 768 // The only thing that we need to verify is that the contents is contained 769 // within the file bounds. We don't need to make sure it doesn't cover other 770 // data, as there's nothing that says that is not allowed. 771 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData; 772 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData; 773 if (ConEnd > uintptr_t(Data->getBufferEnd())) 774 return object_error::parse_failed; 775 Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart), 776 Sec->SizeOfRawData); 777 return object_error::success; 778 } 779 780 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const { 781 return reinterpret_cast<const coff_relocation*>(Rel.p); 782 } 783 784 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const { 785 Rel.p = reinterpret_cast<uintptr_t>( 786 reinterpret_cast<const coff_relocation*>(Rel.p) + 1); 787 } 788 789 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel, 790 uint64_t &Res) const { 791 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile"); 792 } 793 794 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel, 795 uint64_t &Res) const { 796 Res = toRel(Rel)->VirtualAddress; 797 return object_error::success; 798 } 799 800 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const { 801 const coff_relocation* R = toRel(Rel); 802 DataRefImpl Ref; 803 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex); 804 return symbol_iterator(SymbolRef(Ref, this)); 805 } 806 807 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel, 808 uint64_t &Res) const { 809 const coff_relocation* R = toRel(Rel); 810 Res = R->Type; 811 return object_error::success; 812 } 813 814 const coff_section *COFFObjectFile::getCOFFSection(section_iterator &It) const { 815 return toSec(It->getRawDataRefImpl()); 816 } 817 818 const coff_symbol *COFFObjectFile::getCOFFSymbol(symbol_iterator &It) const { 819 return toSymb(It->getRawDataRefImpl()); 820 } 821 822 const coff_relocation *COFFObjectFile::getCOFFRelocation( 823 relocation_iterator &It) const { 824 return toRel(It->getRawDataRefImpl()); 825 } 826 827 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(enum) \ 828 case COFF::enum: Res = #enum; break; 829 830 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel, 831 SmallVectorImpl<char> &Result) const { 832 const coff_relocation *Reloc = toRel(Rel); 833 StringRef Res; 834 switch (COFFHeader->Machine) { 835 case COFF::IMAGE_FILE_MACHINE_AMD64: 836 switch (Reloc->Type) { 837 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE); 838 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64); 839 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32); 840 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB); 841 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32); 842 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1); 843 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2); 844 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3); 845 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4); 846 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5); 847 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION); 848 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL); 849 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7); 850 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN); 851 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32); 852 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR); 853 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32); 854 default: 855 Res = "Unknown"; 856 } 857 break; 858 case COFF::IMAGE_FILE_MACHINE_I386: 859 switch (Reloc->Type) { 860 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE); 861 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16); 862 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16); 863 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32); 864 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB); 865 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12); 866 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION); 867 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL); 868 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN); 869 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7); 870 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32); 871 default: 872 Res = "Unknown"; 873 } 874 break; 875 default: 876 Res = "Unknown"; 877 } 878 Result.append(Res.begin(), Res.end()); 879 return object_error::success; 880 } 881 882 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME 883 884 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel, 885 SmallVectorImpl<char> &Result) const { 886 const coff_relocation *Reloc = toRel(Rel); 887 const coff_symbol *Symb = 0; 888 if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC; 889 DataRefImpl Sym; 890 Sym.p = reinterpret_cast<uintptr_t>(Symb); 891 StringRef SymName; 892 if (error_code EC = getSymbolName(Sym, SymName)) return EC; 893 Result.append(SymName.begin(), SymName.end()); 894 return object_error::success; 895 } 896 897 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData, 898 LibraryRef &Result) const { 899 report_fatal_error("getLibraryNext not implemented in COFFObjectFile"); 900 } 901 902 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData, 903 StringRef &Result) const { 904 report_fatal_error("getLibraryPath not implemented in COFFObjectFile"); 905 } 906 907 bool ImportDirectoryEntryRef:: 908 operator==(const ImportDirectoryEntryRef &Other) const { 909 return ImportTable == Other.ImportTable && Index == Other.Index; 910 } 911 912 void ImportDirectoryEntryRef::moveNext() { 913 ++Index; 914 } 915 916 error_code ImportDirectoryEntryRef:: 917 getImportTableEntry(const import_directory_table_entry *&Result) const { 918 Result = ImportTable; 919 return object_error::success; 920 } 921 922 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const { 923 uintptr_t IntPtr = 0; 924 if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr)) 925 return EC; 926 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 927 return object_error::success; 928 } 929 930 error_code ImportDirectoryEntryRef::getImportLookupEntry( 931 const import_lookup_table_entry32 *&Result) const { 932 uintptr_t IntPtr = 0; 933 if (error_code EC = 934 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr)) 935 return EC; 936 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr); 937 return object_error::success; 938 } 939 940 bool ExportDirectoryEntryRef:: 941 operator==(const ExportDirectoryEntryRef &Other) const { 942 return ExportTable == Other.ExportTable && Index == Other.Index; 943 } 944 945 void ExportDirectoryEntryRef::moveNext() { 946 ++Index; 947 } 948 949 // Returns the name of the current export symbol. If the symbol is exported only 950 // by ordinal, the empty string is set as a result. 951 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const { 952 uintptr_t IntPtr = 0; 953 if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr)) 954 return EC; 955 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 956 return object_error::success; 957 } 958 959 // Returns the starting ordinal number. 960 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const { 961 Result = ExportTable->OrdinalBase; 962 return object_error::success; 963 } 964 965 // Returns the export ordinal of the current export symbol. 966 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const { 967 Result = ExportTable->OrdinalBase + Index; 968 return object_error::success; 969 } 970 971 // Returns the address of the current export symbol. 972 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const { 973 uintptr_t IntPtr = 0; 974 if (error_code EC = OwningObject->getRvaPtr( 975 ExportTable->ExportAddressTableRVA, IntPtr)) 976 return EC; 977 const export_address_table_entry *entry = 978 reinterpret_cast<const export_address_table_entry *>(IntPtr); 979 Result = entry[Index].ExportRVA; 980 return object_error::success; 981 } 982 983 // Returns the name of the current export symbol. If the symbol is exported only 984 // by ordinal, the empty string is set as a result. 985 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const { 986 uintptr_t IntPtr = 0; 987 if (error_code EC = OwningObject->getRvaPtr( 988 ExportTable->OrdinalTableRVA, IntPtr)) 989 return EC; 990 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr); 991 992 uint32_t NumEntries = ExportTable->NumberOfNamePointers; 993 int Offset = 0; 994 for (const ulittle16_t *I = Start, *E = Start + NumEntries; 995 I < E; ++I, ++Offset) { 996 if (*I != Index) 997 continue; 998 if (error_code EC = OwningObject->getRvaPtr( 999 ExportTable->NamePointerRVA, IntPtr)) 1000 return EC; 1001 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr); 1002 if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr)) 1003 return EC; 1004 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1005 return object_error::success; 1006 } 1007 Result = ""; 1008 return object_error::success; 1009 } 1010 1011 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object, 1012 bool BufferOwned) { 1013 error_code EC; 1014 OwningPtr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC, BufferOwned)); 1015 if (EC) 1016 return EC; 1017 return Ret.take(); 1018 } 1019