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