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/COFF.h" 20 #include "llvm/Support/Debug.h" 21 #include "llvm/Support/raw_ostream.h" 22 #include <cctype> 23 #include <limits> 24 25 using namespace llvm; 26 using namespace object; 27 28 using support::ulittle16_t; 29 using support::ulittle32_t; 30 using support::ulittle64_t; 31 using support::little16_t; 32 33 // Returns false if size is greater than the buffer size. And sets ec. 34 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) { 35 if (M.getBufferSize() < Size) { 36 EC = object_error::unexpected_eof; 37 return false; 38 } 39 return true; 40 } 41 42 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m. 43 // Returns unexpected_eof if error. 44 template <typename T> 45 static std::error_code getObject(const T *&Obj, MemoryBufferRef M, 46 const uint8_t *Ptr, 47 const size_t Size = sizeof(T)) { 48 uintptr_t Addr = uintptr_t(Ptr); 49 if (Addr + Size < Addr || Addr + Size < Size || 50 Addr + Size > uintptr_t(M.getBufferEnd())) { 51 return object_error::unexpected_eof; 52 } 53 Obj = reinterpret_cast<const T *>(Addr); 54 return object_error::success; 55 } 56 57 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without 58 // prefixed slashes. 59 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) { 60 assert(Str.size() <= 6 && "String too long, possible overflow."); 61 if (Str.size() > 6) 62 return true; 63 64 uint64_t Value = 0; 65 while (!Str.empty()) { 66 unsigned CharVal; 67 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25 68 CharVal = Str[0] - 'A'; 69 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51 70 CharVal = Str[0] - 'a' + 26; 71 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61 72 CharVal = Str[0] - '0' + 52; 73 else if (Str[0] == '+') // 62 74 CharVal = 62; 75 else if (Str[0] == '/') // 63 76 CharVal = 63; 77 else 78 return true; 79 80 Value = (Value * 64) + CharVal; 81 Str = Str.substr(1); 82 } 83 84 if (Value > std::numeric_limits<uint32_t>::max()) 85 return true; 86 87 Result = static_cast<uint32_t>(Value); 88 return false; 89 } 90 91 template <typename coff_symbol_type> 92 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const { 93 const coff_symbol_type *Addr = 94 reinterpret_cast<const coff_symbol_type *>(Ref.p); 95 96 #ifndef NDEBUG 97 // Verify that the symbol points to a valid entry in the symbol table. 98 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base()); 99 if (Offset < getPointerToSymbolTable() || 100 Offset >= getPointerToSymbolTable() + 101 (getNumberOfSymbols() * sizeof(coff_symbol_type))) 102 report_fatal_error("Symbol was outside of symbol table."); 103 104 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 && 105 "Symbol did not point to the beginning of a symbol"); 106 #endif 107 108 return Addr; 109 } 110 111 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const { 112 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p); 113 114 # ifndef NDEBUG 115 // Verify that the section points to a valid entry in the section table. 116 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections())) 117 report_fatal_error("Section was outside of section table."); 118 119 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable); 120 assert(Offset % sizeof(coff_section) == 0 && 121 "Section did not point to the beginning of a section"); 122 # endif 123 124 return Addr; 125 } 126 127 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const { 128 if (SymbolTable16) { 129 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref); 130 Symb += 1 + Symb->NumberOfAuxSymbols; 131 Ref.p = reinterpret_cast<uintptr_t>(Symb); 132 } else if (SymbolTable32) { 133 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref); 134 Symb += 1 + Symb->NumberOfAuxSymbols; 135 Ref.p = reinterpret_cast<uintptr_t>(Symb); 136 } else { 137 llvm_unreachable("no symbol table pointer!"); 138 } 139 } 140 141 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref, 142 StringRef &Result) const { 143 COFFSymbolRef Symb = getCOFFSymbol(Ref); 144 return getSymbolName(Symb, Result); 145 } 146 147 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref, 148 uint64_t &Result) const { 149 COFFSymbolRef Symb = getCOFFSymbol(Ref); 150 151 if (Symb.isAnyUndefined()) { 152 Result = UnknownAddressOrSize; 153 return object_error::success; 154 } 155 if (Symb.isCommon()) { 156 Result = UnknownAddressOrSize; 157 return object_error::success; 158 } 159 int32_t SectionNumber = Symb.getSectionNumber(); 160 if (!COFF::isReservedSectionNumber(SectionNumber)) { 161 const coff_section *Section = nullptr; 162 if (std::error_code EC = getSection(SectionNumber, Section)) 163 return EC; 164 165 Result = Section->VirtualAddress + Symb.getValue(); 166 return object_error::success; 167 } 168 169 Result = Symb.getValue(); 170 return object_error::success; 171 } 172 173 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref, 174 SymbolRef::Type &Result) const { 175 COFFSymbolRef Symb = getCOFFSymbol(Ref); 176 int32_t SectionNumber = Symb.getSectionNumber(); 177 Result = SymbolRef::ST_Other; 178 179 if (Symb.isAnyUndefined()) { 180 Result = SymbolRef::ST_Unknown; 181 } else if (Symb.isFunctionDefinition()) { 182 Result = SymbolRef::ST_Function; 183 } else if (Symb.isCommon()) { 184 Result = SymbolRef::ST_Data; 185 } else if (Symb.isFileRecord()) { 186 Result = SymbolRef::ST_File; 187 } else if (SectionNumber == COFF::IMAGE_SYM_DEBUG) { 188 Result = SymbolRef::ST_Debug; 189 } else if (!COFF::isReservedSectionNumber(SectionNumber)) { 190 const coff_section *Section = nullptr; 191 if (std::error_code EC = getSection(SectionNumber, Section)) 192 return EC; 193 uint32_t Characteristics = Section->Characteristics; 194 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE) 195 Result = SymbolRef::ST_Function; 196 else if (Characteristics & (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 197 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)) 198 Result = SymbolRef::ST_Data; 199 } 200 return object_error::success; 201 } 202 203 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const { 204 COFFSymbolRef Symb = getCOFFSymbol(Ref); 205 uint32_t Result = SymbolRef::SF_None; 206 207 if (Symb.isExternal() || Symb.isWeakExternal()) 208 Result |= SymbolRef::SF_Global; 209 210 if (Symb.isWeakExternal()) 211 Result |= SymbolRef::SF_Weak; 212 213 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE) 214 Result |= SymbolRef::SF_Absolute; 215 216 if (Symb.isFileRecord()) 217 Result |= SymbolRef::SF_FormatSpecific; 218 219 if (Symb.isSectionDefinition()) 220 Result |= SymbolRef::SF_FormatSpecific; 221 222 if (Symb.isCommon()) 223 Result |= SymbolRef::SF_Common; 224 225 if (Symb.isAnyUndefined()) 226 Result |= SymbolRef::SF_Undefined; 227 228 return Result; 229 } 230 231 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref, 232 uint64_t &Result) const { 233 COFFSymbolRef Symb = getCOFFSymbol(Ref); 234 235 if (Symb.isAnyUndefined()) { 236 Result = UnknownAddressOrSize; 237 return object_error::success; 238 } 239 if (Symb.isCommon()) { 240 Result = Symb.getValue(); 241 return object_error::success; 242 } 243 244 // Let's attempt to get the size of the symbol by looking at the address of 245 // the symbol after the symbol in question. 246 uint64_t SymbAddr; 247 if (std::error_code EC = getSymbolAddress(Ref, SymbAddr)) 248 return EC; 249 int32_t SectionNumber = Symb.getSectionNumber(); 250 if (COFF::isReservedSectionNumber(SectionNumber)) { 251 // Absolute and debug symbols aren't sorted in any interesting way. 252 Result = 0; 253 return object_error::success; 254 } 255 const section_iterator SecEnd = section_end(); 256 uint64_t AfterAddr = UnknownAddressOrSize; 257 for (const symbol_iterator &SymbI : symbols()) { 258 section_iterator SecI = SecEnd; 259 if (std::error_code EC = SymbI->getSection(SecI)) 260 return EC; 261 // Check the symbol's section, skip it if it's in the wrong section. 262 // First, make sure it is in any section. 263 if (SecI == SecEnd) 264 continue; 265 // Second, make sure it is in the same section as the symbol in question. 266 if (!sectionContainsSymbol(SecI->getRawDataRefImpl(), Ref)) 267 continue; 268 uint64_t Addr; 269 if (std::error_code EC = SymbI->getAddress(Addr)) 270 return EC; 271 // We want to compare our symbol in question with the closest possible 272 // symbol that comes after. 273 if (AfterAddr > Addr && Addr > SymbAddr) 274 AfterAddr = Addr; 275 } 276 if (AfterAddr == UnknownAddressOrSize) { 277 // No symbol comes after this one, assume that everything after our symbol 278 // is part of it. 279 const coff_section *Section = nullptr; 280 if (std::error_code EC = getSection(SectionNumber, Section)) 281 return EC; 282 Result = Section->SizeOfRawData - Symb.getValue(); 283 } else { 284 // Take the difference between our symbol and the symbol that comes after 285 // our symbol. 286 Result = AfterAddr - SymbAddr; 287 } 288 289 return object_error::success; 290 } 291 292 std::error_code 293 COFFObjectFile::getSymbolSection(DataRefImpl Ref, 294 section_iterator &Result) const { 295 COFFSymbolRef Symb = getCOFFSymbol(Ref); 296 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) { 297 Result = section_end(); 298 } else { 299 const coff_section *Sec = nullptr; 300 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec)) 301 return EC; 302 DataRefImpl Ref; 303 Ref.p = reinterpret_cast<uintptr_t>(Sec); 304 Result = section_iterator(SectionRef(Ref, this)); 305 } 306 return object_error::success; 307 } 308 309 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const { 310 const coff_section *Sec = toSec(Ref); 311 Sec += 1; 312 Ref.p = reinterpret_cast<uintptr_t>(Sec); 313 } 314 315 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref, 316 StringRef &Result) const { 317 const coff_section *Sec = toSec(Ref); 318 return getSectionName(Sec, Result); 319 } 320 321 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const { 322 const coff_section *Sec = toSec(Ref); 323 return Sec->VirtualAddress; 324 } 325 326 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const { 327 return getSectionSize(toSec(Ref)); 328 } 329 330 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref, 331 StringRef &Result) const { 332 const coff_section *Sec = toSec(Ref); 333 ArrayRef<uint8_t> Res; 334 std::error_code EC = getSectionContents(Sec, Res); 335 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size()); 336 return EC; 337 } 338 339 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const { 340 const coff_section *Sec = toSec(Ref); 341 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1); 342 } 343 344 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const { 345 const coff_section *Sec = toSec(Ref); 346 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE; 347 } 348 349 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const { 350 const coff_section *Sec = toSec(Ref); 351 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA; 352 } 353 354 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const { 355 const coff_section *Sec = toSec(Ref); 356 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA; 357 } 358 359 bool COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref) const { 360 // FIXME: Unimplemented 361 return true; 362 } 363 364 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const { 365 const coff_section *Sec = toSec(Ref); 366 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA; 367 } 368 369 bool COFFObjectFile::isSectionZeroInit(DataRefImpl Ref) const { 370 // FIXME: Unimplemented. 371 return false; 372 } 373 374 bool COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref) const { 375 // FIXME: Unimplemented. 376 return false; 377 } 378 379 bool COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef, 380 DataRefImpl SymbRef) const { 381 const coff_section *Sec = toSec(SecRef); 382 COFFSymbolRef Symb = getCOFFSymbol(SymbRef); 383 int32_t SecNumber = (Sec - SectionTable) + 1; 384 return SecNumber == Symb.getSectionNumber(); 385 } 386 387 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const { 388 const coff_section *Sec = toSec(Ref); 389 DataRefImpl Ret; 390 if (Sec->NumberOfRelocations == 0) { 391 Ret.p = 0; 392 } else { 393 auto begin = reinterpret_cast<const coff_relocation*>( 394 base() + Sec->PointerToRelocations); 395 if (Sec->hasExtendedRelocations()) { 396 // Skip the first relocation entry repurposed to store the number of 397 // relocations. 398 begin++; 399 } 400 Ret.p = reinterpret_cast<uintptr_t>(begin); 401 } 402 return relocation_iterator(RelocationRef(Ret, this)); 403 } 404 405 static uint32_t getNumberOfRelocations(const coff_section *Sec, 406 const uint8_t *base) { 407 // The field for the number of relocations in COFF section table is only 408 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to 409 // NumberOfRelocations field, and the actual relocation count is stored in the 410 // VirtualAddress field in the first relocation entry. 411 if (Sec->hasExtendedRelocations()) { 412 auto *FirstReloc = reinterpret_cast<const coff_relocation*>( 413 base + Sec->PointerToRelocations); 414 return FirstReloc->VirtualAddress; 415 } 416 return Sec->NumberOfRelocations; 417 } 418 419 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const { 420 const coff_section *Sec = toSec(Ref); 421 DataRefImpl Ret; 422 if (Sec->NumberOfRelocations == 0) { 423 Ret.p = 0; 424 } else { 425 auto begin = reinterpret_cast<const coff_relocation*>( 426 base() + Sec->PointerToRelocations); 427 uint32_t NumReloc = getNumberOfRelocations(Sec, base()); 428 Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc); 429 } 430 return relocation_iterator(RelocationRef(Ret, this)); 431 } 432 433 // Initialize the pointer to the symbol table. 434 std::error_code COFFObjectFile::initSymbolTablePtr() { 435 if (COFFHeader) 436 if (std::error_code EC = 437 getObject(SymbolTable16, Data, base() + getPointerToSymbolTable(), 438 getNumberOfSymbols() * getSymbolTableEntrySize())) 439 return EC; 440 441 if (COFFBigObjHeader) 442 if (std::error_code EC = 443 getObject(SymbolTable32, Data, base() + getPointerToSymbolTable(), 444 getNumberOfSymbols() * getSymbolTableEntrySize())) 445 return EC; 446 447 // Find string table. The first four byte of the string table contains the 448 // total size of the string table, including the size field itself. If the 449 // string table is empty, the value of the first four byte would be 4. 450 const uint8_t *StringTableAddr = 451 base() + getPointerToSymbolTable() + 452 getNumberOfSymbols() * getSymbolTableEntrySize(); 453 const ulittle32_t *StringTableSizePtr; 454 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr)) 455 return EC; 456 StringTableSize = *StringTableSizePtr; 457 if (std::error_code EC = 458 getObject(StringTable, Data, StringTableAddr, StringTableSize)) 459 return EC; 460 461 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some 462 // tools like cvtres write a size of 0 for an empty table instead of 4. 463 if (StringTableSize < 4) 464 StringTableSize = 4; 465 466 // Check that the string table is null terminated if has any in it. 467 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0) 468 return object_error::parse_failed; 469 return object_error::success; 470 } 471 472 // Returns the file offset for the given VA. 473 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const { 474 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase 475 : (uint64_t)PE32PlusHeader->ImageBase; 476 uint64_t Rva = Addr - ImageBase; 477 assert(Rva <= UINT32_MAX); 478 return getRvaPtr((uint32_t)Rva, Res); 479 } 480 481 // Returns the file offset for the given RVA. 482 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const { 483 for (const SectionRef &S : sections()) { 484 const coff_section *Section = getCOFFSection(S); 485 uint32_t SectionStart = Section->VirtualAddress; 486 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize; 487 if (SectionStart <= Addr && Addr < SectionEnd) { 488 uint32_t Offset = Addr - SectionStart; 489 Res = uintptr_t(base()) + Section->PointerToRawData + Offset; 490 return object_error::success; 491 } 492 } 493 return object_error::parse_failed; 494 } 495 496 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name 497 // table entry. 498 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint, 499 StringRef &Name) const { 500 uintptr_t IntPtr = 0; 501 if (std::error_code EC = getRvaPtr(Rva, IntPtr)) 502 return EC; 503 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr); 504 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr); 505 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2)); 506 return object_error::success; 507 } 508 509 // Find the import table. 510 std::error_code COFFObjectFile::initImportTablePtr() { 511 // First, we get the RVA of the import table. If the file lacks a pointer to 512 // the import table, do nothing. 513 const data_directory *DataEntry; 514 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry)) 515 return object_error::success; 516 517 // Do nothing if the pointer to import table is NULL. 518 if (DataEntry->RelativeVirtualAddress == 0) 519 return object_error::success; 520 521 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress; 522 // -1 because the last entry is the null entry. 523 NumberOfImportDirectory = DataEntry->Size / 524 sizeof(import_directory_table_entry) - 1; 525 526 // Find the section that contains the RVA. This is needed because the RVA is 527 // the import table's memory address which is different from its file offset. 528 uintptr_t IntPtr = 0; 529 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr)) 530 return EC; 531 ImportDirectory = reinterpret_cast< 532 const import_directory_table_entry *>(IntPtr); 533 return object_error::success; 534 } 535 536 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory. 537 std::error_code COFFObjectFile::initDelayImportTablePtr() { 538 const data_directory *DataEntry; 539 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry)) 540 return object_error::success; 541 if (DataEntry->RelativeVirtualAddress == 0) 542 return object_error::success; 543 544 uint32_t RVA = DataEntry->RelativeVirtualAddress; 545 NumberOfDelayImportDirectory = DataEntry->Size / 546 sizeof(delay_import_directory_table_entry) - 1; 547 548 uintptr_t IntPtr = 0; 549 if (std::error_code EC = getRvaPtr(RVA, IntPtr)) 550 return EC; 551 DelayImportDirectory = reinterpret_cast< 552 const delay_import_directory_table_entry *>(IntPtr); 553 return object_error::success; 554 } 555 556 // Find the export table. 557 std::error_code COFFObjectFile::initExportTablePtr() { 558 // First, we get the RVA of the export table. If the file lacks a pointer to 559 // the export table, do nothing. 560 const data_directory *DataEntry; 561 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry)) 562 return object_error::success; 563 564 // Do nothing if the pointer to export table is NULL. 565 if (DataEntry->RelativeVirtualAddress == 0) 566 return object_error::success; 567 568 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress; 569 uintptr_t IntPtr = 0; 570 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr)) 571 return EC; 572 ExportDirectory = 573 reinterpret_cast<const export_directory_table_entry *>(IntPtr); 574 return object_error::success; 575 } 576 577 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC) 578 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr), 579 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr), 580 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr), 581 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0), 582 ImportDirectory(nullptr), NumberOfImportDirectory(0), 583 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0), 584 ExportDirectory(nullptr) { 585 // Check that we at least have enough room for a header. 586 if (!checkSize(Data, EC, sizeof(coff_file_header))) 587 return; 588 589 // The current location in the file where we are looking at. 590 uint64_t CurPtr = 0; 591 592 // PE header is optional and is present only in executables. If it exists, 593 // it is placed right after COFF header. 594 bool HasPEHeader = false; 595 596 // Check if this is a PE/COFF file. 597 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) { 598 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte 599 // PE signature to find 'normal' COFF header. 600 const auto *DH = reinterpret_cast<const dos_header *>(base()); 601 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') { 602 CurPtr = DH->AddressOfNewExeHeader; 603 // Check the PE magic bytes. ("PE\0\0") 604 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) { 605 EC = object_error::parse_failed; 606 return; 607 } 608 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes. 609 HasPEHeader = true; 610 } 611 } 612 613 if ((EC = getObject(COFFHeader, Data, base() + CurPtr))) 614 return; 615 616 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF 617 // import libraries share a common prefix but bigobj is more restrictive. 618 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN && 619 COFFHeader->NumberOfSections == uint16_t(0xffff) && 620 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) { 621 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr))) 622 return; 623 624 // Verify that we are dealing with bigobj. 625 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion && 626 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic, 627 sizeof(COFF::BigObjMagic)) == 0) { 628 COFFHeader = nullptr; 629 CurPtr += sizeof(coff_bigobj_file_header); 630 } else { 631 // It's not a bigobj. 632 COFFBigObjHeader = nullptr; 633 } 634 } 635 if (COFFHeader) { 636 // The prior checkSize call may have failed. This isn't a hard error 637 // because we were just trying to sniff out bigobj. 638 EC = object_error::success; 639 CurPtr += sizeof(coff_file_header); 640 641 if (COFFHeader->isImportLibrary()) 642 return; 643 } 644 645 if (HasPEHeader) { 646 const pe32_header *Header; 647 if ((EC = getObject(Header, Data, base() + CurPtr))) 648 return; 649 650 const uint8_t *DataDirAddr; 651 uint64_t DataDirSize; 652 if (Header->Magic == COFF::PE32Header::PE32) { 653 PE32Header = Header; 654 DataDirAddr = base() + CurPtr + sizeof(pe32_header); 655 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize; 656 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) { 657 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header); 658 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header); 659 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize; 660 } else { 661 // It's neither PE32 nor PE32+. 662 EC = object_error::parse_failed; 663 return; 664 } 665 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize))) 666 return; 667 CurPtr += COFFHeader->SizeOfOptionalHeader; 668 } 669 670 if ((EC = getObject(SectionTable, Data, base() + CurPtr, 671 getNumberOfSections() * sizeof(coff_section)))) 672 return; 673 674 // Initialize the pointer to the symbol table. 675 if (getPointerToSymbolTable() != 0) 676 if ((EC = initSymbolTablePtr())) 677 return; 678 679 // Initialize the pointer to the beginning of the import table. 680 if ((EC = initImportTablePtr())) 681 return; 682 if ((EC = initDelayImportTablePtr())) 683 return; 684 685 // Initialize the pointer to the export table. 686 if ((EC = initExportTablePtr())) 687 return; 688 689 EC = object_error::success; 690 } 691 692 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const { 693 DataRefImpl Ret; 694 Ret.p = getSymbolTable(); 695 return basic_symbol_iterator(SymbolRef(Ret, this)); 696 } 697 698 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const { 699 // The symbol table ends where the string table begins. 700 DataRefImpl Ret; 701 Ret.p = reinterpret_cast<uintptr_t>(StringTable); 702 return basic_symbol_iterator(SymbolRef(Ret, this)); 703 } 704 705 import_directory_iterator COFFObjectFile::import_directory_begin() const { 706 return import_directory_iterator( 707 ImportDirectoryEntryRef(ImportDirectory, 0, this)); 708 } 709 710 import_directory_iterator COFFObjectFile::import_directory_end() const { 711 return import_directory_iterator( 712 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this)); 713 } 714 715 delay_import_directory_iterator 716 COFFObjectFile::delay_import_directory_begin() const { 717 return delay_import_directory_iterator( 718 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this)); 719 } 720 721 delay_import_directory_iterator 722 COFFObjectFile::delay_import_directory_end() const { 723 return delay_import_directory_iterator( 724 DelayImportDirectoryEntryRef( 725 DelayImportDirectory, NumberOfDelayImportDirectory, this)); 726 } 727 728 export_directory_iterator COFFObjectFile::export_directory_begin() const { 729 return export_directory_iterator( 730 ExportDirectoryEntryRef(ExportDirectory, 0, this)); 731 } 732 733 export_directory_iterator COFFObjectFile::export_directory_end() const { 734 if (!ExportDirectory) 735 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this)); 736 ExportDirectoryEntryRef Ref(ExportDirectory, 737 ExportDirectory->AddressTableEntries, this); 738 return export_directory_iterator(Ref); 739 } 740 741 section_iterator COFFObjectFile::section_begin() const { 742 DataRefImpl Ret; 743 Ret.p = reinterpret_cast<uintptr_t>(SectionTable); 744 return section_iterator(SectionRef(Ret, this)); 745 } 746 747 section_iterator COFFObjectFile::section_end() const { 748 DataRefImpl Ret; 749 int NumSections = 750 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections(); 751 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections); 752 return section_iterator(SectionRef(Ret, this)); 753 } 754 755 uint8_t COFFObjectFile::getBytesInAddress() const { 756 return getArch() == Triple::x86_64 ? 8 : 4; 757 } 758 759 StringRef COFFObjectFile::getFileFormatName() const { 760 switch(getMachine()) { 761 case COFF::IMAGE_FILE_MACHINE_I386: 762 return "COFF-i386"; 763 case COFF::IMAGE_FILE_MACHINE_AMD64: 764 return "COFF-x86-64"; 765 case COFF::IMAGE_FILE_MACHINE_ARMNT: 766 return "COFF-ARM"; 767 default: 768 return "COFF-<unknown arch>"; 769 } 770 } 771 772 unsigned COFFObjectFile::getArch() const { 773 switch (getMachine()) { 774 case COFF::IMAGE_FILE_MACHINE_I386: 775 return Triple::x86; 776 case COFF::IMAGE_FILE_MACHINE_AMD64: 777 return Triple::x86_64; 778 case COFF::IMAGE_FILE_MACHINE_ARMNT: 779 return Triple::thumb; 780 default: 781 return Triple::UnknownArch; 782 } 783 } 784 785 iterator_range<import_directory_iterator> 786 COFFObjectFile::import_directories() const { 787 return make_range(import_directory_begin(), import_directory_end()); 788 } 789 790 iterator_range<delay_import_directory_iterator> 791 COFFObjectFile::delay_import_directories() const { 792 return make_range(delay_import_directory_begin(), 793 delay_import_directory_end()); 794 } 795 796 iterator_range<export_directory_iterator> 797 COFFObjectFile::export_directories() const { 798 return make_range(export_directory_begin(), export_directory_end()); 799 } 800 801 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const { 802 Res = PE32Header; 803 return object_error::success; 804 } 805 806 std::error_code 807 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const { 808 Res = PE32PlusHeader; 809 return object_error::success; 810 } 811 812 std::error_code 813 COFFObjectFile::getDataDirectory(uint32_t Index, 814 const data_directory *&Res) const { 815 // Error if if there's no data directory or the index is out of range. 816 if (!DataDirectory) 817 return object_error::parse_failed; 818 assert(PE32Header || PE32PlusHeader); 819 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize 820 : PE32PlusHeader->NumberOfRvaAndSize; 821 if (Index > NumEnt) 822 return object_error::parse_failed; 823 Res = &DataDirectory[Index]; 824 return object_error::success; 825 } 826 827 std::error_code COFFObjectFile::getSection(int32_t Index, 828 const coff_section *&Result) const { 829 // Check for special index values. 830 if (COFF::isReservedSectionNumber(Index)) 831 Result = nullptr; 832 else if (Index > 0 && static_cast<uint32_t>(Index) <= getNumberOfSections()) 833 // We already verified the section table data, so no need to check again. 834 Result = SectionTable + (Index - 1); 835 else 836 return object_error::parse_failed; 837 return object_error::success; 838 } 839 840 std::error_code COFFObjectFile::getString(uint32_t Offset, 841 StringRef &Result) const { 842 if (StringTableSize <= 4) 843 // Tried to get a string from an empty string table. 844 return object_error::parse_failed; 845 if (Offset >= StringTableSize) 846 return object_error::unexpected_eof; 847 Result = StringRef(StringTable + Offset); 848 return object_error::success; 849 } 850 851 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol, 852 StringRef &Res) const { 853 // Check for string table entry. First 4 bytes are 0. 854 if (Symbol.getStringTableOffset().Zeroes == 0) { 855 uint32_t Offset = Symbol.getStringTableOffset().Offset; 856 if (std::error_code EC = getString(Offset, Res)) 857 return EC; 858 return object_error::success; 859 } 860 861 if (Symbol.getShortName()[COFF::NameSize - 1] == 0) 862 // Null terminated, let ::strlen figure out the length. 863 Res = StringRef(Symbol.getShortName()); 864 else 865 // Not null terminated, use all 8 bytes. 866 Res = StringRef(Symbol.getShortName(), COFF::NameSize); 867 return object_error::success; 868 } 869 870 ArrayRef<uint8_t> 871 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const { 872 const uint8_t *Aux = nullptr; 873 874 size_t SymbolSize = getSymbolTableEntrySize(); 875 if (Symbol.getNumberOfAuxSymbols() > 0) { 876 // AUX data comes immediately after the symbol in COFF 877 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize; 878 # ifndef NDEBUG 879 // Verify that the Aux symbol points to a valid entry in the symbol table. 880 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base()); 881 if (Offset < getPointerToSymbolTable() || 882 Offset >= 883 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize)) 884 report_fatal_error("Aux Symbol data was outside of symbol table."); 885 886 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 && 887 "Aux Symbol data did not point to the beginning of a symbol"); 888 # endif 889 } 890 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize); 891 } 892 893 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec, 894 StringRef &Res) const { 895 StringRef Name; 896 if (Sec->Name[COFF::NameSize - 1] == 0) 897 // Null terminated, let ::strlen figure out the length. 898 Name = Sec->Name; 899 else 900 // Not null terminated, use all 8 bytes. 901 Name = StringRef(Sec->Name, COFF::NameSize); 902 903 // Check for string table entry. First byte is '/'. 904 if (Name[0] == '/') { 905 uint32_t Offset; 906 if (Name[1] == '/') { 907 if (decodeBase64StringEntry(Name.substr(2), Offset)) 908 return object_error::parse_failed; 909 } else { 910 if (Name.substr(1).getAsInteger(10, Offset)) 911 return object_error::parse_failed; 912 } 913 if (std::error_code EC = getString(Offset, Name)) 914 return EC; 915 } 916 917 Res = Name; 918 return object_error::success; 919 } 920 921 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const { 922 // SizeOfRawData and VirtualSize change what they represent depending on 923 // whether or not we have an executable image. 924 // 925 // For object files, SizeOfRawData contains the size of section's data; 926 // VirtualSize is always zero. 927 // 928 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the 929 // actual section size is in VirtualSize. It is possible for VirtualSize to 930 // be greater than SizeOfRawData; the contents past that point should be 931 // considered to be zero. 932 uint32_t SectionSize; 933 if (Sec->VirtualSize) 934 SectionSize = std::min(Sec->VirtualSize, Sec->SizeOfRawData); 935 else 936 SectionSize = Sec->SizeOfRawData; 937 938 return SectionSize; 939 } 940 941 std::error_code 942 COFFObjectFile::getSectionContents(const coff_section *Sec, 943 ArrayRef<uint8_t> &Res) const { 944 // PointerToRawData and SizeOfRawData won't make sense for BSS sections, 945 // don't do anything interesting for them. 946 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 && 947 "BSS sections don't have contents!"); 948 // The only thing that we need to verify is that the contents is contained 949 // within the file bounds. We don't need to make sure it doesn't cover other 950 // data, as there's nothing that says that is not allowed. 951 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData; 952 uint32_t SectionSize = getSectionSize(Sec); 953 uintptr_t ConEnd = ConStart + SectionSize; 954 if (ConEnd > uintptr_t(Data.getBufferEnd())) 955 return object_error::parse_failed; 956 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize); 957 return object_error::success; 958 } 959 960 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const { 961 return reinterpret_cast<const coff_relocation*>(Rel.p); 962 } 963 964 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const { 965 Rel.p = reinterpret_cast<uintptr_t>( 966 reinterpret_cast<const coff_relocation*>(Rel.p) + 1); 967 } 968 969 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel, 970 uint64_t &Res) const { 971 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile"); 972 } 973 974 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel, 975 uint64_t &Res) const { 976 Res = toRel(Rel)->VirtualAddress; 977 return object_error::success; 978 } 979 980 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const { 981 const coff_relocation *R = toRel(Rel); 982 DataRefImpl Ref; 983 if (SymbolTable16) 984 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex); 985 else if (SymbolTable32) 986 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex); 987 else 988 llvm_unreachable("no symbol table pointer!"); 989 return symbol_iterator(SymbolRef(Ref, this)); 990 } 991 992 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel, 993 uint64_t &Res) const { 994 const coff_relocation* R = toRel(Rel); 995 Res = R->Type; 996 return object_error::success; 997 } 998 999 const coff_section * 1000 COFFObjectFile::getCOFFSection(const SectionRef &Section) const { 1001 return toSec(Section.getRawDataRefImpl()); 1002 } 1003 1004 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const { 1005 if (SymbolTable16) 1006 return toSymb<coff_symbol16>(Ref); 1007 if (SymbolTable32) 1008 return toSymb<coff_symbol32>(Ref); 1009 llvm_unreachable("no symbol table pointer!"); 1010 } 1011 1012 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const { 1013 return getCOFFSymbol(Symbol.getRawDataRefImpl()); 1014 } 1015 1016 const coff_relocation * 1017 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const { 1018 return toRel(Reloc.getRawDataRefImpl()); 1019 } 1020 1021 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \ 1022 case COFF::reloc_type: \ 1023 Res = #reloc_type; \ 1024 break; 1025 1026 std::error_code 1027 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel, 1028 SmallVectorImpl<char> &Result) const { 1029 const coff_relocation *Reloc = toRel(Rel); 1030 StringRef Res; 1031 switch (getMachine()) { 1032 case COFF::IMAGE_FILE_MACHINE_AMD64: 1033 switch (Reloc->Type) { 1034 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE); 1035 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64); 1036 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32); 1037 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB); 1038 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32); 1039 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1); 1040 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2); 1041 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3); 1042 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4); 1043 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5); 1044 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION); 1045 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL); 1046 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7); 1047 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN); 1048 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32); 1049 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR); 1050 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32); 1051 default: 1052 Res = "Unknown"; 1053 } 1054 break; 1055 case COFF::IMAGE_FILE_MACHINE_ARMNT: 1056 switch (Reloc->Type) { 1057 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE); 1058 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32); 1059 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB); 1060 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24); 1061 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11); 1062 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN); 1063 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24); 1064 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11); 1065 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION); 1066 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL); 1067 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A); 1068 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T); 1069 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T); 1070 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T); 1071 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T); 1072 default: 1073 Res = "Unknown"; 1074 } 1075 break; 1076 case COFF::IMAGE_FILE_MACHINE_I386: 1077 switch (Reloc->Type) { 1078 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE); 1079 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16); 1080 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16); 1081 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32); 1082 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB); 1083 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12); 1084 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION); 1085 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL); 1086 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN); 1087 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7); 1088 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32); 1089 default: 1090 Res = "Unknown"; 1091 } 1092 break; 1093 default: 1094 Res = "Unknown"; 1095 } 1096 Result.append(Res.begin(), Res.end()); 1097 return object_error::success; 1098 } 1099 1100 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME 1101 1102 std::error_code 1103 COFFObjectFile::getRelocationValueString(DataRefImpl Rel, 1104 SmallVectorImpl<char> &Result) const { 1105 const coff_relocation *Reloc = toRel(Rel); 1106 DataRefImpl Sym; 1107 ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex); 1108 if (std::error_code EC = Symb.getError()) 1109 return EC; 1110 Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr()); 1111 StringRef SymName; 1112 if (std::error_code EC = getSymbolName(Sym, SymName)) 1113 return EC; 1114 Result.append(SymName.begin(), SymName.end()); 1115 return object_error::success; 1116 } 1117 1118 bool COFFObjectFile::isRelocatableObject() const { 1119 return !DataDirectory; 1120 } 1121 1122 bool ImportDirectoryEntryRef:: 1123 operator==(const ImportDirectoryEntryRef &Other) const { 1124 return ImportTable == Other.ImportTable && Index == Other.Index; 1125 } 1126 1127 void ImportDirectoryEntryRef::moveNext() { 1128 ++Index; 1129 } 1130 1131 std::error_code ImportDirectoryEntryRef::getImportTableEntry( 1132 const import_directory_table_entry *&Result) const { 1133 Result = ImportTable + Index; 1134 return object_error::success; 1135 } 1136 1137 static imported_symbol_iterator 1138 makeImportedSymbolIterator(const COFFObjectFile *Object, 1139 uintptr_t Ptr, int Index) { 1140 if (Object->getBytesInAddress() == 4) { 1141 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr); 1142 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object)); 1143 } 1144 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr); 1145 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object)); 1146 } 1147 1148 static imported_symbol_iterator 1149 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) { 1150 uintptr_t IntPtr = 0; 1151 Object->getRvaPtr(RVA, IntPtr); 1152 return makeImportedSymbolIterator(Object, IntPtr, 0); 1153 } 1154 1155 static imported_symbol_iterator 1156 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) { 1157 uintptr_t IntPtr = 0; 1158 Object->getRvaPtr(RVA, IntPtr); 1159 // Forward the pointer to the last entry which is null. 1160 int Index = 0; 1161 if (Object->getBytesInAddress() == 4) { 1162 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr); 1163 while (*Entry++) 1164 ++Index; 1165 } else { 1166 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr); 1167 while (*Entry++) 1168 ++Index; 1169 } 1170 return makeImportedSymbolIterator(Object, IntPtr, Index); 1171 } 1172 1173 imported_symbol_iterator 1174 ImportDirectoryEntryRef::imported_symbol_begin() const { 1175 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA, 1176 OwningObject); 1177 } 1178 1179 imported_symbol_iterator 1180 ImportDirectoryEntryRef::imported_symbol_end() const { 1181 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA, 1182 OwningObject); 1183 } 1184 1185 iterator_range<imported_symbol_iterator> 1186 ImportDirectoryEntryRef::imported_symbols() const { 1187 return make_range(imported_symbol_begin(), imported_symbol_end()); 1188 } 1189 1190 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const { 1191 uintptr_t IntPtr = 0; 1192 if (std::error_code EC = 1193 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr)) 1194 return EC; 1195 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1196 return object_error::success; 1197 } 1198 1199 std::error_code 1200 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const { 1201 Result = ImportTable[Index].ImportLookupTableRVA; 1202 return object_error::success; 1203 } 1204 1205 std::error_code 1206 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const { 1207 Result = ImportTable[Index].ImportAddressTableRVA; 1208 return object_error::success; 1209 } 1210 1211 std::error_code ImportDirectoryEntryRef::getImportLookupEntry( 1212 const import_lookup_table_entry32 *&Result) const { 1213 uintptr_t IntPtr = 0; 1214 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA; 1215 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr)) 1216 return EC; 1217 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr); 1218 return object_error::success; 1219 } 1220 1221 bool DelayImportDirectoryEntryRef:: 1222 operator==(const DelayImportDirectoryEntryRef &Other) const { 1223 return Table == Other.Table && Index == Other.Index; 1224 } 1225 1226 void DelayImportDirectoryEntryRef::moveNext() { 1227 ++Index; 1228 } 1229 1230 imported_symbol_iterator 1231 DelayImportDirectoryEntryRef::imported_symbol_begin() const { 1232 return importedSymbolBegin(Table[Index].DelayImportNameTable, 1233 OwningObject); 1234 } 1235 1236 imported_symbol_iterator 1237 DelayImportDirectoryEntryRef::imported_symbol_end() const { 1238 return importedSymbolEnd(Table[Index].DelayImportNameTable, 1239 OwningObject); 1240 } 1241 1242 iterator_range<imported_symbol_iterator> 1243 DelayImportDirectoryEntryRef::imported_symbols() const { 1244 return make_range(imported_symbol_begin(), imported_symbol_end()); 1245 } 1246 1247 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const { 1248 uintptr_t IntPtr = 0; 1249 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr)) 1250 return EC; 1251 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1252 return object_error::success; 1253 } 1254 1255 std::error_code DelayImportDirectoryEntryRef:: 1256 getDelayImportTable(const delay_import_directory_table_entry *&Result) const { 1257 Result = Table; 1258 return object_error::success; 1259 } 1260 1261 std::error_code DelayImportDirectoryEntryRef:: 1262 getImportAddress(int AddrIndex, uint64_t &Result) const { 1263 uint32_t RVA = Table[Index].DelayImportAddressTable + 1264 AddrIndex * (OwningObject->is64() ? 8 : 4); 1265 uintptr_t IntPtr = 0; 1266 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr)) 1267 return EC; 1268 if (OwningObject->is64()) 1269 Result = *reinterpret_cast<const uint64_t *>(IntPtr); 1270 else 1271 Result = *reinterpret_cast<const uint32_t *>(IntPtr); 1272 return object_error::success; 1273 } 1274 1275 bool ExportDirectoryEntryRef:: 1276 operator==(const ExportDirectoryEntryRef &Other) const { 1277 return ExportTable == Other.ExportTable && Index == Other.Index; 1278 } 1279 1280 void ExportDirectoryEntryRef::moveNext() { 1281 ++Index; 1282 } 1283 1284 // Returns the name of the current export symbol. If the symbol is exported only 1285 // by ordinal, the empty string is set as a result. 1286 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const { 1287 uintptr_t IntPtr = 0; 1288 if (std::error_code EC = 1289 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr)) 1290 return EC; 1291 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1292 return object_error::success; 1293 } 1294 1295 // Returns the starting ordinal number. 1296 std::error_code 1297 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const { 1298 Result = ExportTable->OrdinalBase; 1299 return object_error::success; 1300 } 1301 1302 // Returns the export ordinal of the current export symbol. 1303 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const { 1304 Result = ExportTable->OrdinalBase + Index; 1305 return object_error::success; 1306 } 1307 1308 // Returns the address of the current export symbol. 1309 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const { 1310 uintptr_t IntPtr = 0; 1311 if (std::error_code EC = 1312 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr)) 1313 return EC; 1314 const export_address_table_entry *entry = 1315 reinterpret_cast<const export_address_table_entry *>(IntPtr); 1316 Result = entry[Index].ExportRVA; 1317 return object_error::success; 1318 } 1319 1320 // Returns the name of the current export symbol. If the symbol is exported only 1321 // by ordinal, the empty string is set as a result. 1322 std::error_code 1323 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const { 1324 uintptr_t IntPtr = 0; 1325 if (std::error_code EC = 1326 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr)) 1327 return EC; 1328 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr); 1329 1330 uint32_t NumEntries = ExportTable->NumberOfNamePointers; 1331 int Offset = 0; 1332 for (const ulittle16_t *I = Start, *E = Start + NumEntries; 1333 I < E; ++I, ++Offset) { 1334 if (*I != Index) 1335 continue; 1336 if (std::error_code EC = 1337 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr)) 1338 return EC; 1339 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr); 1340 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr)) 1341 return EC; 1342 Result = StringRef(reinterpret_cast<const char *>(IntPtr)); 1343 return object_error::success; 1344 } 1345 Result = ""; 1346 return object_error::success; 1347 } 1348 1349 bool ImportedSymbolRef:: 1350 operator==(const ImportedSymbolRef &Other) const { 1351 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64 1352 && Index == Other.Index; 1353 } 1354 1355 void ImportedSymbolRef::moveNext() { 1356 ++Index; 1357 } 1358 1359 std::error_code 1360 ImportedSymbolRef::getSymbolName(StringRef &Result) const { 1361 uint32_t RVA; 1362 if (Entry32) { 1363 // If a symbol is imported only by ordinal, it has no name. 1364 if (Entry32[Index].isOrdinal()) 1365 return object_error::success; 1366 RVA = Entry32[Index].getHintNameRVA(); 1367 } else { 1368 if (Entry64[Index].isOrdinal()) 1369 return object_error::success; 1370 RVA = Entry64[Index].getHintNameRVA(); 1371 } 1372 uintptr_t IntPtr = 0; 1373 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr)) 1374 return EC; 1375 // +2 because the first two bytes is hint. 1376 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2)); 1377 return object_error::success; 1378 } 1379 1380 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const { 1381 uint32_t RVA; 1382 if (Entry32) { 1383 if (Entry32[Index].isOrdinal()) { 1384 Result = Entry32[Index].getOrdinal(); 1385 return object_error::success; 1386 } 1387 RVA = Entry32[Index].getHintNameRVA(); 1388 } else { 1389 if (Entry64[Index].isOrdinal()) { 1390 Result = Entry64[Index].getOrdinal(); 1391 return object_error::success; 1392 } 1393 RVA = Entry64[Index].getHintNameRVA(); 1394 } 1395 uintptr_t IntPtr = 0; 1396 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr)) 1397 return EC; 1398 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr); 1399 return object_error::success; 1400 } 1401 1402 ErrorOr<std::unique_ptr<COFFObjectFile>> 1403 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) { 1404 std::error_code EC; 1405 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC)); 1406 if (EC) 1407 return EC; 1408 return std::move(Ret); 1409 } 1410