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