1 //===- COFFObjectFile.cpp - COFF object file implementation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the COFFObjectFile class.
12 //===----------------------------------------------------------------------===//
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/Object/Binary.h"
19 #include "llvm/Object/COFF.h"
20 #include "llvm/Object/Error.h"
21 #include "llvm/Object/ObjectFile.h"
22 #include "llvm/Support/COFF.h"
23 #include "llvm/Support/Endian.h"
24 #include "llvm/Support/Error.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/MemoryBuffer.h"
35 #include <system_error>
38 using namespace object;
40 using support::ulittle16_t;
41 using support::ulittle32_t;
42 using support::ulittle64_t;
43 using support::little16_t;
45 // Returns false if size is greater than the buffer size. And sets ec.
46 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
47 if (M.getBufferSize() < Size) {
48 EC = object_error::unexpected_eof;
54 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
55 const uint64_t Size) {
56 if (Addr + Size < Addr || Addr + Size < Size ||
57 Addr + Size > uintptr_t(M.getBufferEnd()) ||
58 Addr < uintptr_t(M.getBufferStart())) {
59 return object_error::unexpected_eof;
61 return std::error_code();
64 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
65 // Returns unexpected_eof if error.
67 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
69 const uint64_t Size = sizeof(T)) {
70 uintptr_t Addr = uintptr_t(Ptr);
71 if (std::error_code EC = checkOffset(M, Addr, Size))
73 Obj = reinterpret_cast<const T *>(Addr);
74 return std::error_code();
77 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
79 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
80 assert(Str.size() <= 6 && "String too long, possible overflow.");
85 while (!Str.empty()) {
87 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
88 CharVal = Str[0] - 'A';
89 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
90 CharVal = Str[0] - 'a' + 26;
91 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
92 CharVal = Str[0] - '0' + 52;
93 else if (Str[0] == '+') // 62
95 else if (Str[0] == '/') // 63
100 Value = (Value * 64) + CharVal;
104 if (Value > std::numeric_limits<uint32_t>::max())
107 Result = static_cast<uint32_t>(Value);
111 template <typename coff_symbol_type>
112 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
113 const coff_symbol_type *Addr =
114 reinterpret_cast<const coff_symbol_type *>(Ref.p);
116 assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
118 // Verify that the symbol points to a valid entry in the symbol table.
119 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
121 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
122 "Symbol did not point to the beginning of a symbol");
128 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
129 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
132 // Verify that the section points to a valid entry in the section table.
133 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
134 report_fatal_error("Section was outside of section table.");
136 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
137 assert(Offset % sizeof(coff_section) == 0 &&
138 "Section did not point to the beginning of a section");
144 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
145 auto End = reinterpret_cast<uintptr_t>(StringTable);
147 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
148 Symb += 1 + Symb->NumberOfAuxSymbols;
149 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
150 } else if (SymbolTable32) {
151 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
152 Symb += 1 + Symb->NumberOfAuxSymbols;
153 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
155 llvm_unreachable("no symbol table pointer!");
159 Expected<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
160 COFFSymbolRef Symb = getCOFFSymbol(Ref);
162 std::error_code EC = getSymbolName(Symb, Result);
164 return errorCodeToError(EC);
168 uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const {
169 return getCOFFSymbol(Ref).getValue();
172 uint32_t COFFObjectFile::getSymbolAlignment(DataRefImpl Ref) const {
173 // MSVC/link.exe seems to align symbols to the next-power-of-2
175 COFFSymbolRef Symb = getCOFFSymbol(Ref);
176 return std::min(uint64_t(32), PowerOf2Ceil(Symb.getValue()));
179 Expected<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
180 uint64_t Result = getSymbolValue(Ref);
181 COFFSymbolRef Symb = getCOFFSymbol(Ref);
182 int32_t SectionNumber = Symb.getSectionNumber();
184 if (Symb.isAnyUndefined() || Symb.isCommon() ||
185 COFF::isReservedSectionNumber(SectionNumber))
188 const coff_section *Section = nullptr;
189 if (std::error_code EC = getSection(SectionNumber, Section))
190 return errorCodeToError(EC);
191 Result += Section->VirtualAddress;
193 // The section VirtualAddress does not include ImageBase, and we want to
194 // return virtual addresses.
195 Result += getImageBase();
200 Expected<SymbolRef::Type> COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
201 COFFSymbolRef Symb = getCOFFSymbol(Ref);
202 int32_t SectionNumber = Symb.getSectionNumber();
204 if (Symb.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION)
205 return SymbolRef::ST_Function;
206 if (Symb.isAnyUndefined())
207 return SymbolRef::ST_Unknown;
209 return SymbolRef::ST_Data;
210 if (Symb.isFileRecord())
211 return SymbolRef::ST_File;
213 // TODO: perhaps we need a new symbol type ST_Section.
214 if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
215 return SymbolRef::ST_Debug;
217 if (!COFF::isReservedSectionNumber(SectionNumber))
218 return SymbolRef::ST_Data;
220 return SymbolRef::ST_Other;
223 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
224 COFFSymbolRef Symb = getCOFFSymbol(Ref);
225 uint32_t Result = SymbolRef::SF_None;
227 if (Symb.isExternal() || Symb.isWeakExternal())
228 Result |= SymbolRef::SF_Global;
230 if (Symb.isWeakExternal())
231 Result |= SymbolRef::SF_Weak;
233 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
234 Result |= SymbolRef::SF_Absolute;
236 if (Symb.isFileRecord())
237 Result |= SymbolRef::SF_FormatSpecific;
239 if (Symb.isSectionDefinition())
240 Result |= SymbolRef::SF_FormatSpecific;
243 Result |= SymbolRef::SF_Common;
245 if (Symb.isAnyUndefined())
246 Result |= SymbolRef::SF_Undefined;
251 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
252 COFFSymbolRef Symb = getCOFFSymbol(Ref);
253 return Symb.getValue();
256 Expected<section_iterator>
257 COFFObjectFile::getSymbolSection(DataRefImpl Ref) const {
258 COFFSymbolRef Symb = getCOFFSymbol(Ref);
259 if (COFF::isReservedSectionNumber(Symb.getSectionNumber()))
260 return section_end();
261 const coff_section *Sec = nullptr;
262 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
263 return errorCodeToError(EC);
265 Ret.p = reinterpret_cast<uintptr_t>(Sec);
266 return section_iterator(SectionRef(Ret, this));
269 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
270 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
271 return Symb.getSectionNumber();
274 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
275 const coff_section *Sec = toSec(Ref);
277 Ref.p = reinterpret_cast<uintptr_t>(Sec);
280 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
281 StringRef &Result) const {
282 const coff_section *Sec = toSec(Ref);
283 return getSectionName(Sec, Result);
286 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
287 const coff_section *Sec = toSec(Ref);
288 uint64_t Result = Sec->VirtualAddress;
290 // The section VirtualAddress does not include ImageBase, and we want to
291 // return virtual addresses.
292 Result += getImageBase();
296 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
297 return getSectionSize(toSec(Ref));
300 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
301 StringRef &Result) const {
302 const coff_section *Sec = toSec(Ref);
303 ArrayRef<uint8_t> Res;
304 std::error_code EC = getSectionContents(Sec, Res);
305 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
309 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
310 const coff_section *Sec = toSec(Ref);
311 return Sec->getAlignment();
314 bool COFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
318 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
319 const coff_section *Sec = toSec(Ref);
320 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
323 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
324 const coff_section *Sec = toSec(Ref);
325 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
328 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
329 const coff_section *Sec = toSec(Ref);
330 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
331 COFF::IMAGE_SCN_MEM_READ |
332 COFF::IMAGE_SCN_MEM_WRITE;
333 return (Sec->Characteristics & BssFlags) == BssFlags;
336 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
338 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
339 assert((Offset % sizeof(coff_section)) == 0);
340 return (Offset / sizeof(coff_section)) + 1;
343 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
344 const coff_section *Sec = toSec(Ref);
345 // In COFF, a virtual section won't have any in-file
346 // content, so the file pointer to the content will be zero.
347 return Sec->PointerToRawData == 0;
350 static uint32_t getNumberOfRelocations(const coff_section *Sec,
351 MemoryBufferRef M, const uint8_t *base) {
352 // The field for the number of relocations in COFF section table is only
353 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
354 // NumberOfRelocations field, and the actual relocation count is stored in the
355 // VirtualAddress field in the first relocation entry.
356 if (Sec->hasExtendedRelocations()) {
357 const coff_relocation *FirstReloc;
358 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
359 base + Sec->PointerToRelocations)))
361 // -1 to exclude this first relocation entry.
362 return FirstReloc->VirtualAddress - 1;
364 return Sec->NumberOfRelocations;
367 static const coff_relocation *
368 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
369 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
372 auto begin = reinterpret_cast<const coff_relocation *>(
373 Base + Sec->PointerToRelocations);
374 if (Sec->hasExtendedRelocations()) {
375 // Skip the first relocation entry repurposed to store the number of
379 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
384 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
385 const coff_section *Sec = toSec(Ref);
386 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
387 if (begin && Sec->VirtualAddress != 0)
388 report_fatal_error("Sections with relocations should have an address of 0");
390 Ret.p = reinterpret_cast<uintptr_t>(begin);
391 return relocation_iterator(RelocationRef(Ret, this));
394 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
395 const coff_section *Sec = toSec(Ref);
396 const coff_relocation *I = getFirstReloc(Sec, Data, base());
398 I += getNumberOfRelocations(Sec, Data, base());
400 Ret.p = reinterpret_cast<uintptr_t>(I);
401 return relocation_iterator(RelocationRef(Ret, this));
404 // Initialize the pointer to the symbol table.
405 std::error_code COFFObjectFile::initSymbolTablePtr() {
407 if (std::error_code EC = getObject(
408 SymbolTable16, Data, base() + getPointerToSymbolTable(),
409 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
412 if (COFFBigObjHeader)
413 if (std::error_code EC = getObject(
414 SymbolTable32, Data, base() + getPointerToSymbolTable(),
415 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
418 // Find string table. The first four byte of the string table contains the
419 // total size of the string table, including the size field itself. If the
420 // string table is empty, the value of the first four byte would be 4.
421 uint32_t StringTableOffset = getPointerToSymbolTable() +
422 getNumberOfSymbols() * getSymbolTableEntrySize();
423 const uint8_t *StringTableAddr = base() + StringTableOffset;
424 const ulittle32_t *StringTableSizePtr;
425 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
427 StringTableSize = *StringTableSizePtr;
428 if (std::error_code EC =
429 getObject(StringTable, Data, StringTableAddr, StringTableSize))
432 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
433 // tools like cvtres write a size of 0 for an empty table instead of 4.
434 if (StringTableSize < 4)
437 // Check that the string table is null terminated if has any in it.
438 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
439 return object_error::parse_failed;
440 return std::error_code();
443 uint64_t COFFObjectFile::getImageBase() const {
445 return PE32Header->ImageBase;
446 else if (PE32PlusHeader)
447 return PE32PlusHeader->ImageBase;
448 // This actually comes up in practice.
452 // Returns the file offset for the given VA.
453 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
454 uint64_t ImageBase = getImageBase();
455 uint64_t Rva = Addr - ImageBase;
456 assert(Rva <= UINT32_MAX);
457 return getRvaPtr((uint32_t)Rva, Res);
460 // Returns the file offset for the given RVA.
461 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
462 for (const SectionRef &S : sections()) {
463 const coff_section *Section = getCOFFSection(S);
464 uint32_t SectionStart = Section->VirtualAddress;
465 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
466 if (SectionStart <= Addr && Addr < SectionEnd) {
467 uint32_t Offset = Addr - SectionStart;
468 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
469 return std::error_code();
472 return object_error::parse_failed;
476 COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
477 ArrayRef<uint8_t> &Contents) const {
478 for (const SectionRef &S : sections()) {
479 const coff_section *Section = getCOFFSection(S);
480 uint32_t SectionStart = Section->VirtualAddress;
481 // Check if this RVA is within the section bounds. Be careful about integer
483 uint32_t OffsetIntoSection = RVA - SectionStart;
484 if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize &&
485 Size <= Section->VirtualSize - OffsetIntoSection) {
487 uintptr_t(base()) + Section->PointerToRawData + OffsetIntoSection;
489 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size);
490 return std::error_code();
493 return object_error::parse_failed;
496 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
498 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
499 StringRef &Name) const {
500 uintptr_t IntPtr = 0;
501 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
503 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
504 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
505 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
506 return std::error_code();
510 COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir,
511 const codeview::DebugInfo *&PDBInfo,
512 StringRef &PDBFileName) const {
513 ArrayRef<uint8_t> InfoBytes;
514 if (std::error_code EC = getRvaAndSizeAsBytes(
515 DebugDir->AddressOfRawData, DebugDir->SizeOfData, InfoBytes))
517 if (InfoBytes.size() < sizeof(*PDBInfo) + 1)
518 return object_error::parse_failed;
519 PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data());
520 InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo));
521 PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()),
523 // Truncate the name at the first null byte. Ignore any padding.
524 PDBFileName = PDBFileName.split('\0').first;
525 return std::error_code();
529 COFFObjectFile::getDebugPDBInfo(const codeview::DebugInfo *&PDBInfo,
530 StringRef &PDBFileName) const {
531 for (const debug_directory &D : debug_directories())
532 if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW)
533 return getDebugPDBInfo(&D, PDBInfo, PDBFileName);
534 // If we get here, there is no PDB info to return.
536 PDBFileName = StringRef();
537 return std::error_code();
540 // Find the import table.
541 std::error_code COFFObjectFile::initImportTablePtr() {
542 // First, we get the RVA of the import table. If the file lacks a pointer to
543 // the import table, do nothing.
544 const data_directory *DataEntry;
545 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
546 return std::error_code();
548 // Do nothing if the pointer to import table is NULL.
549 if (DataEntry->RelativeVirtualAddress == 0)
550 return std::error_code();
552 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
554 // Find the section that contains the RVA. This is needed because the RVA is
555 // the import table's memory address which is different from its file offset.
556 uintptr_t IntPtr = 0;
557 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
559 if (std::error_code EC = checkOffset(Data, IntPtr, DataEntry->Size))
561 ImportDirectory = reinterpret_cast<
562 const coff_import_directory_table_entry *>(IntPtr);
563 return std::error_code();
566 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
567 std::error_code COFFObjectFile::initDelayImportTablePtr() {
568 const data_directory *DataEntry;
569 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
570 return std::error_code();
571 if (DataEntry->RelativeVirtualAddress == 0)
572 return std::error_code();
574 uint32_t RVA = DataEntry->RelativeVirtualAddress;
575 NumberOfDelayImportDirectory = DataEntry->Size /
576 sizeof(delay_import_directory_table_entry) - 1;
578 uintptr_t IntPtr = 0;
579 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
581 DelayImportDirectory = reinterpret_cast<
582 const delay_import_directory_table_entry *>(IntPtr);
583 return std::error_code();
586 // Find the export table.
587 std::error_code COFFObjectFile::initExportTablePtr() {
588 // First, we get the RVA of the export table. If the file lacks a pointer to
589 // the export table, do nothing.
590 const data_directory *DataEntry;
591 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
592 return std::error_code();
594 // Do nothing if the pointer to export table is NULL.
595 if (DataEntry->RelativeVirtualAddress == 0)
596 return std::error_code();
598 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
599 uintptr_t IntPtr = 0;
600 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
603 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
604 return std::error_code();
607 std::error_code COFFObjectFile::initBaseRelocPtr() {
608 const data_directory *DataEntry;
609 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
610 return std::error_code();
611 if (DataEntry->RelativeVirtualAddress == 0)
612 return std::error_code();
614 uintptr_t IntPtr = 0;
615 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
617 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
619 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
620 IntPtr + DataEntry->Size);
621 return std::error_code();
624 std::error_code COFFObjectFile::initDebugDirectoryPtr() {
625 // Get the RVA of the debug directory. Do nothing if it does not exist.
626 const data_directory *DataEntry;
627 if (getDataDirectory(COFF::DEBUG_DIRECTORY, DataEntry))
628 return std::error_code();
630 // Do nothing if the RVA is NULL.
631 if (DataEntry->RelativeVirtualAddress == 0)
632 return std::error_code();
634 // Check that the size is a multiple of the entry size.
635 if (DataEntry->Size % sizeof(debug_directory) != 0)
636 return object_error::parse_failed;
638 uintptr_t IntPtr = 0;
639 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
641 DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
642 if (std::error_code EC = getRvaPtr(
643 DataEntry->RelativeVirtualAddress + DataEntry->Size, IntPtr))
645 DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(IntPtr);
646 return std::error_code();
649 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
650 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
651 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
652 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
653 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
654 ImportDirectory(nullptr),
655 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
656 ExportDirectory(nullptr), BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
657 DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr) {
658 // Check that we at least have enough room for a header.
659 if (!checkSize(Data, EC, sizeof(coff_file_header)))
662 // The current location in the file where we are looking at.
665 // PE header is optional and is present only in executables. If it exists,
666 // it is placed right after COFF header.
667 bool HasPEHeader = false;
669 // Check if this is a PE/COFF file.
670 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
671 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
672 // PE signature to find 'normal' COFF header.
673 const auto *DH = reinterpret_cast<const dos_header *>(base());
674 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
675 CurPtr = DH->AddressOfNewExeHeader;
676 // Check the PE magic bytes. ("PE\0\0")
677 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
678 EC = object_error::parse_failed;
681 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
686 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
689 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
690 // import libraries share a common prefix but bigobj is more restrictive.
691 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
692 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
693 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
694 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
697 // Verify that we are dealing with bigobj.
698 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
699 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
700 sizeof(COFF::BigObjMagic)) == 0) {
701 COFFHeader = nullptr;
702 CurPtr += sizeof(coff_bigobj_file_header);
704 // It's not a bigobj.
705 COFFBigObjHeader = nullptr;
709 // The prior checkSize call may have failed. This isn't a hard error
710 // because we were just trying to sniff out bigobj.
711 EC = std::error_code();
712 CurPtr += sizeof(coff_file_header);
714 if (COFFHeader->isImportLibrary())
719 const pe32_header *Header;
720 if ((EC = getObject(Header, Data, base() + CurPtr)))
723 const uint8_t *DataDirAddr;
724 uint64_t DataDirSize;
725 if (Header->Magic == COFF::PE32Header::PE32) {
727 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
728 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
729 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
730 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
731 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
732 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
734 // It's neither PE32 nor PE32+.
735 EC = object_error::parse_failed;
738 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
743 CurPtr += COFFHeader->SizeOfOptionalHeader;
745 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
746 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
749 // Initialize the pointer to the symbol table.
750 if (getPointerToSymbolTable() != 0) {
751 if ((EC = initSymbolTablePtr())) {
752 SymbolTable16 = nullptr;
753 SymbolTable32 = nullptr;
754 StringTable = nullptr;
758 // We had better not have any symbols if we don't have a symbol table.
759 if (getNumberOfSymbols() != 0) {
760 EC = object_error::parse_failed;
765 // Initialize the pointer to the beginning of the import table.
766 if ((EC = initImportTablePtr()))
768 if ((EC = initDelayImportTablePtr()))
771 // Initialize the pointer to the export table.
772 if ((EC = initExportTablePtr()))
775 // Initialize the pointer to the base relocation table.
776 if ((EC = initBaseRelocPtr()))
779 // Initialize the pointer to the export table.
780 if ((EC = initDebugDirectoryPtr()))
783 EC = std::error_code();
786 basic_symbol_iterator COFFObjectFile::symbol_begin() const {
788 Ret.p = getSymbolTable();
789 return basic_symbol_iterator(SymbolRef(Ret, this));
792 basic_symbol_iterator COFFObjectFile::symbol_end() const {
793 // The symbol table ends where the string table begins.
795 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
796 return basic_symbol_iterator(SymbolRef(Ret, this));
799 import_directory_iterator COFFObjectFile::import_directory_begin() const {
800 if (!ImportDirectory)
801 return import_directory_end();
802 if (ImportDirectory->isNull())
803 return import_directory_end();
804 return import_directory_iterator(
805 ImportDirectoryEntryRef(ImportDirectory, 0, this));
808 import_directory_iterator COFFObjectFile::import_directory_end() const {
809 return import_directory_iterator(
810 ImportDirectoryEntryRef(nullptr, -1, this));
813 delay_import_directory_iterator
814 COFFObjectFile::delay_import_directory_begin() const {
815 return delay_import_directory_iterator(
816 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
819 delay_import_directory_iterator
820 COFFObjectFile::delay_import_directory_end() const {
821 return delay_import_directory_iterator(
822 DelayImportDirectoryEntryRef(
823 DelayImportDirectory, NumberOfDelayImportDirectory, this));
826 export_directory_iterator COFFObjectFile::export_directory_begin() const {
827 return export_directory_iterator(
828 ExportDirectoryEntryRef(ExportDirectory, 0, this));
831 export_directory_iterator COFFObjectFile::export_directory_end() const {
832 if (!ExportDirectory)
833 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
834 ExportDirectoryEntryRef Ref(ExportDirectory,
835 ExportDirectory->AddressTableEntries, this);
836 return export_directory_iterator(Ref);
839 section_iterator COFFObjectFile::section_begin() const {
841 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
842 return section_iterator(SectionRef(Ret, this));
845 section_iterator COFFObjectFile::section_end() const {
848 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
849 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
850 return section_iterator(SectionRef(Ret, this));
853 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
854 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
857 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
858 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
861 uint8_t COFFObjectFile::getBytesInAddress() const {
862 return getArch() == Triple::x86_64 ? 8 : 4;
865 StringRef COFFObjectFile::getFileFormatName() const {
866 switch(getMachine()) {
867 case COFF::IMAGE_FILE_MACHINE_I386:
869 case COFF::IMAGE_FILE_MACHINE_AMD64:
870 return "COFF-x86-64";
871 case COFF::IMAGE_FILE_MACHINE_ARMNT:
873 case COFF::IMAGE_FILE_MACHINE_ARM64:
876 return "COFF-<unknown arch>";
880 unsigned COFFObjectFile::getArch() const {
881 switch (getMachine()) {
882 case COFF::IMAGE_FILE_MACHINE_I386:
884 case COFF::IMAGE_FILE_MACHINE_AMD64:
885 return Triple::x86_64;
886 case COFF::IMAGE_FILE_MACHINE_ARMNT:
887 return Triple::thumb;
888 case COFF::IMAGE_FILE_MACHINE_ARM64:
889 return Triple::aarch64;
891 return Triple::UnknownArch;
895 iterator_range<import_directory_iterator>
896 COFFObjectFile::import_directories() const {
897 return make_range(import_directory_begin(), import_directory_end());
900 iterator_range<delay_import_directory_iterator>
901 COFFObjectFile::delay_import_directories() const {
902 return make_range(delay_import_directory_begin(),
903 delay_import_directory_end());
906 iterator_range<export_directory_iterator>
907 COFFObjectFile::export_directories() const {
908 return make_range(export_directory_begin(), export_directory_end());
911 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
912 return make_range(base_reloc_begin(), base_reloc_end());
915 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
917 return std::error_code();
921 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
922 Res = PE32PlusHeader;
923 return std::error_code();
927 COFFObjectFile::getDataDirectory(uint32_t Index,
928 const data_directory *&Res) const {
929 // Error if if there's no data directory or the index is out of range.
930 if (!DataDirectory) {
932 return object_error::parse_failed;
934 assert(PE32Header || PE32PlusHeader);
935 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
936 : PE32PlusHeader->NumberOfRvaAndSize;
937 if (Index >= NumEnt) {
939 return object_error::parse_failed;
941 Res = &DataDirectory[Index];
942 return std::error_code();
945 std::error_code COFFObjectFile::getSection(int32_t Index,
946 const coff_section *&Result) const {
948 if (COFF::isReservedSectionNumber(Index))
949 return std::error_code();
950 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
951 // We already verified the section table data, so no need to check again.
952 Result = SectionTable + (Index - 1);
953 return std::error_code();
955 return object_error::parse_failed;
958 std::error_code COFFObjectFile::getString(uint32_t Offset,
959 StringRef &Result) const {
960 if (StringTableSize <= 4)
961 // Tried to get a string from an empty string table.
962 return object_error::parse_failed;
963 if (Offset >= StringTableSize)
964 return object_error::unexpected_eof;
965 Result = StringRef(StringTable + Offset);
966 return std::error_code();
969 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
970 StringRef &Res) const {
971 return getSymbolName(Symbol.getGeneric(), Res);
974 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
975 StringRef &Res) const {
976 // Check for string table entry. First 4 bytes are 0.
977 if (Symbol->Name.Offset.Zeroes == 0) {
978 if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
980 return std::error_code();
983 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
984 // Null terminated, let ::strlen figure out the length.
985 Res = StringRef(Symbol->Name.ShortName);
987 // Not null terminated, use all 8 bytes.
988 Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
989 return std::error_code();
993 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
994 const uint8_t *Aux = nullptr;
996 size_t SymbolSize = getSymbolTableEntrySize();
997 if (Symbol.getNumberOfAuxSymbols() > 0) {
998 // AUX data comes immediately after the symbol in COFF
999 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
1001 // Verify that the Aux symbol points to a valid entry in the symbol table.
1002 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
1003 if (Offset < getPointerToSymbolTable() ||
1005 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
1006 report_fatal_error("Aux Symbol data was outside of symbol table.");
1008 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
1009 "Aux Symbol data did not point to the beginning of a symbol");
1012 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
1015 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
1016 StringRef &Res) const {
1018 if (Sec->Name[COFF::NameSize - 1] == 0)
1019 // Null terminated, let ::strlen figure out the length.
1022 // Not null terminated, use all 8 bytes.
1023 Name = StringRef(Sec->Name, COFF::NameSize);
1025 // Check for string table entry. First byte is '/'.
1026 if (Name.startswith("/")) {
1028 if (Name.startswith("//")) {
1029 if (decodeBase64StringEntry(Name.substr(2), Offset))
1030 return object_error::parse_failed;
1032 if (Name.substr(1).getAsInteger(10, Offset))
1033 return object_error::parse_failed;
1035 if (std::error_code EC = getString(Offset, Name))
1040 return std::error_code();
1043 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
1044 // SizeOfRawData and VirtualSize change what they represent depending on
1045 // whether or not we have an executable image.
1047 // For object files, SizeOfRawData contains the size of section's data;
1048 // VirtualSize should be zero but isn't due to buggy COFF writers.
1050 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1051 // actual section size is in VirtualSize. It is possible for VirtualSize to
1052 // be greater than SizeOfRawData; the contents past that point should be
1053 // considered to be zero.
1055 return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1056 return Sec->SizeOfRawData;
1060 COFFObjectFile::getSectionContents(const coff_section *Sec,
1061 ArrayRef<uint8_t> &Res) const {
1062 // In COFF, a virtual section won't have any in-file
1063 // content, so the file pointer to the content will be zero.
1064 if (Sec->PointerToRawData == 0)
1065 return object_error::parse_failed;
1066 // The only thing that we need to verify is that the contents is contained
1067 // within the file bounds. We don't need to make sure it doesn't cover other
1068 // data, as there's nothing that says that is not allowed.
1069 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1070 uint32_t SectionSize = getSectionSize(Sec);
1071 if (checkOffset(Data, ConStart, SectionSize))
1072 return object_error::parse_failed;
1073 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1074 return std::error_code();
1077 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1078 return reinterpret_cast<const coff_relocation*>(Rel.p);
1081 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1082 Rel.p = reinterpret_cast<uintptr_t>(
1083 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1086 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1087 const coff_relocation *R = toRel(Rel);
1088 return R->VirtualAddress;
1091 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1092 const coff_relocation *R = toRel(Rel);
1094 if (R->SymbolTableIndex >= getNumberOfSymbols())
1095 return symbol_end();
1097 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1098 else if (SymbolTable32)
1099 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1101 llvm_unreachable("no symbol table pointer!");
1102 return symbol_iterator(SymbolRef(Ref, this));
1105 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
1106 const coff_relocation* R = toRel(Rel);
1110 const coff_section *
1111 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1112 return toSec(Section.getRawDataRefImpl());
1115 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1117 return toSymb<coff_symbol16>(Ref);
1119 return toSymb<coff_symbol32>(Ref);
1120 llvm_unreachable("no symbol table pointer!");
1123 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1124 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1127 const coff_relocation *
1128 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1129 return toRel(Reloc.getRawDataRefImpl());
1132 iterator_range<const coff_relocation *>
1133 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1134 const coff_relocation *I = getFirstReloc(Sec, Data, base());
1135 const coff_relocation *E = I;
1137 E += getNumberOfRelocations(Sec, Data, base());
1138 return make_range(I, E);
1141 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1142 case COFF::reloc_type: \
1143 Res = #reloc_type; \
1146 void COFFObjectFile::getRelocationTypeName(
1147 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1148 const coff_relocation *Reloc = toRel(Rel);
1150 switch (getMachine()) {
1151 case COFF::IMAGE_FILE_MACHINE_AMD64:
1152 switch (Reloc->Type) {
1153 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1154 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1155 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1156 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1157 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1158 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1159 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1160 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1161 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1162 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1163 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1164 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1165 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1166 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1167 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1168 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1169 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1174 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1175 switch (Reloc->Type) {
1176 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1177 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1178 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1179 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1180 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1181 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1182 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1183 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1184 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1185 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1186 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1187 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1188 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1189 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1190 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1195 case COFF::IMAGE_FILE_MACHINE_I386:
1196 switch (Reloc->Type) {
1197 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1198 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1199 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1200 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1201 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1202 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1203 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1204 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1205 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1206 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1207 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1215 Result.append(Res.begin(), Res.end());
1218 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1220 bool COFFObjectFile::isRelocatableObject() const {
1221 return !DataDirectory;
1224 bool ImportDirectoryEntryRef::
1225 operator==(const ImportDirectoryEntryRef &Other) const {
1226 return ImportTable == Other.ImportTable && Index == Other.Index;
1229 void ImportDirectoryEntryRef::moveNext() {
1231 if (ImportTable[Index].isNull()) {
1233 ImportTable = nullptr;
1237 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1238 const coff_import_directory_table_entry *&Result) const {
1239 return getObject(Result, OwningObject->Data, ImportTable + Index);
1242 static imported_symbol_iterator
1243 makeImportedSymbolIterator(const COFFObjectFile *Object,
1244 uintptr_t Ptr, int Index) {
1245 if (Object->getBytesInAddress() == 4) {
1246 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1247 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1249 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1250 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1253 static imported_symbol_iterator
1254 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1255 uintptr_t IntPtr = 0;
1256 Object->getRvaPtr(RVA, IntPtr);
1257 return makeImportedSymbolIterator(Object, IntPtr, 0);
1260 static imported_symbol_iterator
1261 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1262 uintptr_t IntPtr = 0;
1263 Object->getRvaPtr(RVA, IntPtr);
1264 // Forward the pointer to the last entry which is null.
1266 if (Object->getBytesInAddress() == 4) {
1267 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1271 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1275 return makeImportedSymbolIterator(Object, IntPtr, Index);
1278 imported_symbol_iterator
1279 ImportDirectoryEntryRef::imported_symbol_begin() const {
1280 return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
1284 imported_symbol_iterator
1285 ImportDirectoryEntryRef::imported_symbol_end() const {
1286 return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
1290 iterator_range<imported_symbol_iterator>
1291 ImportDirectoryEntryRef::imported_symbols() const {
1292 return make_range(imported_symbol_begin(), imported_symbol_end());
1295 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
1296 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1300 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
1301 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1305 iterator_range<imported_symbol_iterator>
1306 ImportDirectoryEntryRef::lookup_table_symbols() const {
1307 return make_range(lookup_table_begin(), lookup_table_end());
1310 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1311 uintptr_t IntPtr = 0;
1312 if (std::error_code EC =
1313 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1315 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1316 return std::error_code();
1320 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1321 Result = ImportTable[Index].ImportLookupTableRVA;
1322 return std::error_code();
1326 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1327 Result = ImportTable[Index].ImportAddressTableRVA;
1328 return std::error_code();
1331 bool DelayImportDirectoryEntryRef::
1332 operator==(const DelayImportDirectoryEntryRef &Other) const {
1333 return Table == Other.Table && Index == Other.Index;
1336 void DelayImportDirectoryEntryRef::moveNext() {
1340 imported_symbol_iterator
1341 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1342 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1346 imported_symbol_iterator
1347 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1348 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1352 iterator_range<imported_symbol_iterator>
1353 DelayImportDirectoryEntryRef::imported_symbols() const {
1354 return make_range(imported_symbol_begin(), imported_symbol_end());
1357 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1358 uintptr_t IntPtr = 0;
1359 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1361 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1362 return std::error_code();
1365 std::error_code DelayImportDirectoryEntryRef::
1366 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1368 return std::error_code();
1371 std::error_code DelayImportDirectoryEntryRef::
1372 getImportAddress(int AddrIndex, uint64_t &Result) const {
1373 uint32_t RVA = Table[Index].DelayImportAddressTable +
1374 AddrIndex * (OwningObject->is64() ? 8 : 4);
1375 uintptr_t IntPtr = 0;
1376 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1378 if (OwningObject->is64())
1379 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1381 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1382 return std::error_code();
1385 bool ExportDirectoryEntryRef::
1386 operator==(const ExportDirectoryEntryRef &Other) const {
1387 return ExportTable == Other.ExportTable && Index == Other.Index;
1390 void ExportDirectoryEntryRef::moveNext() {
1394 // Returns the name of the current export symbol. If the symbol is exported only
1395 // by ordinal, the empty string is set as a result.
1396 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1397 uintptr_t IntPtr = 0;
1398 if (std::error_code EC =
1399 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1401 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1402 return std::error_code();
1405 // Returns the starting ordinal number.
1407 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1408 Result = ExportTable->OrdinalBase;
1409 return std::error_code();
1412 // Returns the export ordinal of the current export symbol.
1413 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1414 Result = ExportTable->OrdinalBase + Index;
1415 return std::error_code();
1418 // Returns the address of the current export symbol.
1419 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1420 uintptr_t IntPtr = 0;
1421 if (std::error_code EC =
1422 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1424 const export_address_table_entry *entry =
1425 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1426 Result = entry[Index].ExportRVA;
1427 return std::error_code();
1430 // Returns the name of the current export symbol. If the symbol is exported only
1431 // by ordinal, the empty string is set as a result.
1433 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1434 uintptr_t IntPtr = 0;
1435 if (std::error_code EC =
1436 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1438 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1440 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1442 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1443 I < E; ++I, ++Offset) {
1446 if (std::error_code EC =
1447 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1449 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1450 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1452 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1453 return std::error_code();
1456 return std::error_code();
1459 std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1460 const data_directory *DataEntry;
1461 if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
1464 if (auto EC = getExportRVA(RVA))
1466 uint32_t Begin = DataEntry->RelativeVirtualAddress;
1467 uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1468 Result = (Begin <= RVA && RVA < End);
1469 return std::error_code();
1472 std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1474 if (auto EC = getExportRVA(RVA))
1476 uintptr_t IntPtr = 0;
1477 if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1479 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1480 return std::error_code();
1483 bool ImportedSymbolRef::
1484 operator==(const ImportedSymbolRef &Other) const {
1485 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1486 && Index == Other.Index;
1489 void ImportedSymbolRef::moveNext() {
1494 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1497 // If a symbol is imported only by ordinal, it has no name.
1498 if (Entry32[Index].isOrdinal())
1499 return std::error_code();
1500 RVA = Entry32[Index].getHintNameRVA();
1502 if (Entry64[Index].isOrdinal())
1503 return std::error_code();
1504 RVA = Entry64[Index].getHintNameRVA();
1506 uintptr_t IntPtr = 0;
1507 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1509 // +2 because the first two bytes is hint.
1510 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1511 return std::error_code();
1514 std::error_code ImportedSymbolRef::isOrdinal(bool &Result) const {
1516 Result = Entry32[Index].isOrdinal();
1518 Result = Entry64[Index].isOrdinal();
1519 return std::error_code();
1522 std::error_code ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
1524 Result = Entry32[Index].getHintNameRVA();
1526 Result = Entry64[Index].getHintNameRVA();
1527 return std::error_code();
1530 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1533 if (Entry32[Index].isOrdinal()) {
1534 Result = Entry32[Index].getOrdinal();
1535 return std::error_code();
1537 RVA = Entry32[Index].getHintNameRVA();
1539 if (Entry64[Index].isOrdinal()) {
1540 Result = Entry64[Index].getOrdinal();
1541 return std::error_code();
1543 RVA = Entry64[Index].getHintNameRVA();
1545 uintptr_t IntPtr = 0;
1546 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1548 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1549 return std::error_code();
1552 ErrorOr<std::unique_ptr<COFFObjectFile>>
1553 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1555 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1558 return std::move(Ret);
1561 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1562 return Header == Other.Header && Index == Other.Index;
1565 void BaseRelocRef::moveNext() {
1566 // Header->BlockSize is the size of the current block, including the
1567 // size of the header itself.
1568 uint32_t Size = sizeof(*Header) +
1569 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1570 if (Size == Header->BlockSize) {
1571 // .reloc contains a list of base relocation blocks. Each block
1572 // consists of the header followed by entries. The header contains
1573 // how many entories will follow. When we reach the end of the
1574 // current block, proceed to the next block.
1575 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1576 reinterpret_cast<const uint8_t *>(Header) + Size);
1583 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1584 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1585 Type = Entry[Index].getType();
1586 return std::error_code();
1589 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1590 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1591 Result = Header->PageRVA + Entry[Index].getOffset();
1592 return std::error_code();