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