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/BinaryStreamReader.h"
23 #include "llvm/Support/COFF.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"
36 #include <system_error>
39 using namespace object;
41 using support::ulittle16_t;
42 using support::ulittle32_t;
43 using support::ulittle64_t;
44 using support::little16_t;
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;
55 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
56 const uint64_t Size) {
57 if (Addr + Size < Addr || Addr + Size < Size ||
58 Addr + Size > uintptr_t(M.getBufferEnd()) ||
59 Addr < uintptr_t(M.getBufferStart())) {
60 return object_error::unexpected_eof;
62 return std::error_code();
65 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
66 // Returns unexpected_eof if error.
68 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
70 const uint64_t Size = sizeof(T)) {
71 uintptr_t Addr = uintptr_t(Ptr);
72 if (std::error_code EC = checkOffset(M, Addr, Size))
74 Obj = reinterpret_cast<const T *>(Addr);
75 return std::error_code();
78 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
80 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
81 assert(Str.size() <= 6 && "String too long, possible overflow.");
86 while (!Str.empty()) {
88 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
89 CharVal = Str[0] - 'A';
90 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
91 CharVal = Str[0] - 'a' + 26;
92 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
93 CharVal = Str[0] - '0' + 52;
94 else if (Str[0] == '+') // 62
96 else if (Str[0] == '/') // 63
101 Value = (Value * 64) + CharVal;
105 if (Value > std::numeric_limits<uint32_t>::max())
108 Result = static_cast<uint32_t>(Value);
112 template <typename coff_symbol_type>
113 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
114 const coff_symbol_type *Addr =
115 reinterpret_cast<const coff_symbol_type *>(Ref.p);
117 assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
119 // Verify that the symbol points to a valid entry in the symbol table.
120 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
122 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
123 "Symbol did not point to the beginning of a symbol");
129 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
130 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
133 // Verify that the section points to a valid entry in the section table.
134 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
135 report_fatal_error("Section was outside of section table.");
137 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
138 assert(Offset % sizeof(coff_section) == 0 &&
139 "Section did not point to the beginning of a section");
145 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
146 auto End = reinterpret_cast<uintptr_t>(StringTable);
148 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
149 Symb += 1 + Symb->NumberOfAuxSymbols;
150 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
151 } else if (SymbolTable32) {
152 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
153 Symb += 1 + Symb->NumberOfAuxSymbols;
154 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
156 llvm_unreachable("no symbol table pointer!");
160 Expected<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
161 COFFSymbolRef Symb = getCOFFSymbol(Ref);
163 if (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::getSectionIndex(DataRefImpl Sec) const {
297 return toSec(Sec) - SectionTable;
300 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
301 return getSectionSize(toSec(Ref));
304 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
305 StringRef &Result) const {
306 const coff_section *Sec = toSec(Ref);
307 ArrayRef<uint8_t> Res;
308 std::error_code EC = getSectionContents(Sec, Res);
309 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
313 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
314 const coff_section *Sec = toSec(Ref);
315 return Sec->getAlignment();
318 bool COFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
322 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
323 const coff_section *Sec = toSec(Ref);
324 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
327 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
328 const coff_section *Sec = toSec(Ref);
329 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
332 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
333 const coff_section *Sec = toSec(Ref);
334 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
335 COFF::IMAGE_SCN_MEM_READ |
336 COFF::IMAGE_SCN_MEM_WRITE;
337 return (Sec->Characteristics & BssFlags) == BssFlags;
340 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
342 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
343 assert((Offset % sizeof(coff_section)) == 0);
344 return (Offset / sizeof(coff_section)) + 1;
347 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
348 const coff_section *Sec = toSec(Ref);
349 // In COFF, a virtual section won't have any in-file
350 // content, so the file pointer to the content will be zero.
351 return Sec->PointerToRawData == 0;
354 static uint32_t getNumberOfRelocations(const coff_section *Sec,
355 MemoryBufferRef M, const uint8_t *base) {
356 // The field for the number of relocations in COFF section table is only
357 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
358 // NumberOfRelocations field, and the actual relocation count is stored in the
359 // VirtualAddress field in the first relocation entry.
360 if (Sec->hasExtendedRelocations()) {
361 const coff_relocation *FirstReloc;
362 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
363 base + Sec->PointerToRelocations)))
365 // -1 to exclude this first relocation entry.
366 return FirstReloc->VirtualAddress - 1;
368 return Sec->NumberOfRelocations;
371 static const coff_relocation *
372 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
373 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
376 auto begin = reinterpret_cast<const coff_relocation *>(
377 Base + Sec->PointerToRelocations);
378 if (Sec->hasExtendedRelocations()) {
379 // Skip the first relocation entry repurposed to store the number of
383 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
388 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
389 const coff_section *Sec = toSec(Ref);
390 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
391 if (begin && Sec->VirtualAddress != 0)
392 report_fatal_error("Sections with relocations should have an address of 0");
394 Ret.p = reinterpret_cast<uintptr_t>(begin);
395 return relocation_iterator(RelocationRef(Ret, this));
398 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
399 const coff_section *Sec = toSec(Ref);
400 const coff_relocation *I = getFirstReloc(Sec, Data, base());
402 I += getNumberOfRelocations(Sec, Data, base());
404 Ret.p = reinterpret_cast<uintptr_t>(I);
405 return relocation_iterator(RelocationRef(Ret, this));
408 // Initialize the pointer to the symbol table.
409 std::error_code COFFObjectFile::initSymbolTablePtr() {
411 if (std::error_code EC = getObject(
412 SymbolTable16, Data, base() + getPointerToSymbolTable(),
413 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
416 if (COFFBigObjHeader)
417 if (std::error_code EC = getObject(
418 SymbolTable32, Data, base() + getPointerToSymbolTable(),
419 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
422 // Find string table. The first four byte of the string table contains the
423 // total size of the string table, including the size field itself. If the
424 // string table is empty, the value of the first four byte would be 4.
425 uint32_t StringTableOffset = getPointerToSymbolTable() +
426 getNumberOfSymbols() * getSymbolTableEntrySize();
427 const uint8_t *StringTableAddr = base() + StringTableOffset;
428 const ulittle32_t *StringTableSizePtr;
429 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
431 StringTableSize = *StringTableSizePtr;
432 if (std::error_code EC =
433 getObject(StringTable, Data, StringTableAddr, StringTableSize))
436 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
437 // tools like cvtres write a size of 0 for an empty table instead of 4.
438 if (StringTableSize < 4)
441 // Check that the string table is null terminated if has any in it.
442 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
443 return object_error::parse_failed;
444 return std::error_code();
447 uint64_t COFFObjectFile::getImageBase() const {
449 return PE32Header->ImageBase;
450 else if (PE32PlusHeader)
451 return PE32PlusHeader->ImageBase;
452 // This actually comes up in practice.
456 // Returns the file offset for the given VA.
457 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
458 uint64_t ImageBase = getImageBase();
459 uint64_t Rva = Addr - ImageBase;
460 assert(Rva <= UINT32_MAX);
461 return getRvaPtr((uint32_t)Rva, Res);
464 // Returns the file offset for the given RVA.
465 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
466 for (const SectionRef &S : sections()) {
467 const coff_section *Section = getCOFFSection(S);
468 uint32_t SectionStart = Section->VirtualAddress;
469 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
470 if (SectionStart <= Addr && Addr < SectionEnd) {
471 uint32_t Offset = Addr - SectionStart;
472 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
473 return std::error_code();
476 return object_error::parse_failed;
480 COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
481 ArrayRef<uint8_t> &Contents) const {
482 for (const SectionRef &S : sections()) {
483 const coff_section *Section = getCOFFSection(S);
484 uint32_t SectionStart = Section->VirtualAddress;
485 // Check if this RVA is within the section bounds. Be careful about integer
487 uint32_t OffsetIntoSection = RVA - SectionStart;
488 if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize &&
489 Size <= Section->VirtualSize - OffsetIntoSection) {
491 uintptr_t(base()) + Section->PointerToRawData + OffsetIntoSection;
493 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size);
494 return std::error_code();
497 return object_error::parse_failed;
500 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
502 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
503 StringRef &Name) const {
504 uintptr_t IntPtr = 0;
505 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
507 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
508 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
509 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
510 return std::error_code();
514 COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir,
515 const codeview::DebugInfo *&PDBInfo,
516 StringRef &PDBFileName) const {
517 ArrayRef<uint8_t> InfoBytes;
518 if (std::error_code EC = getRvaAndSizeAsBytes(
519 DebugDir->AddressOfRawData, DebugDir->SizeOfData, InfoBytes))
521 if (InfoBytes.size() < sizeof(*PDBInfo) + 1)
522 return object_error::parse_failed;
523 PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data());
524 InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo));
525 PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()),
527 // Truncate the name at the first null byte. Ignore any padding.
528 PDBFileName = PDBFileName.split('\0').first;
529 return std::error_code();
533 COFFObjectFile::getDebugPDBInfo(const codeview::DebugInfo *&PDBInfo,
534 StringRef &PDBFileName) const {
535 for (const debug_directory &D : debug_directories())
536 if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW)
537 return getDebugPDBInfo(&D, PDBInfo, PDBFileName);
538 // If we get here, there is no PDB info to return.
540 PDBFileName = StringRef();
541 return std::error_code();
544 // Find the import table.
545 std::error_code COFFObjectFile::initImportTablePtr() {
546 // First, we get the RVA of the import table. If the file lacks a pointer to
547 // the import table, do nothing.
548 const data_directory *DataEntry;
549 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
550 return std::error_code();
552 // Do nothing if the pointer to import table is NULL.
553 if (DataEntry->RelativeVirtualAddress == 0)
554 return std::error_code();
556 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
558 // Find the section that contains the RVA. This is needed because the RVA is
559 // the import table's memory address which is different from its file offset.
560 uintptr_t IntPtr = 0;
561 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
563 if (std::error_code EC = checkOffset(Data, IntPtr, DataEntry->Size))
565 ImportDirectory = reinterpret_cast<
566 const coff_import_directory_table_entry *>(IntPtr);
567 return std::error_code();
570 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
571 std::error_code COFFObjectFile::initDelayImportTablePtr() {
572 const data_directory *DataEntry;
573 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
574 return std::error_code();
575 if (DataEntry->RelativeVirtualAddress == 0)
576 return std::error_code();
578 uint32_t RVA = DataEntry->RelativeVirtualAddress;
579 NumberOfDelayImportDirectory = DataEntry->Size /
580 sizeof(delay_import_directory_table_entry) - 1;
582 uintptr_t IntPtr = 0;
583 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
585 DelayImportDirectory = reinterpret_cast<
586 const delay_import_directory_table_entry *>(IntPtr);
587 return std::error_code();
590 // Find the export table.
591 std::error_code COFFObjectFile::initExportTablePtr() {
592 // First, we get the RVA of the export table. If the file lacks a pointer to
593 // the export table, do nothing.
594 const data_directory *DataEntry;
595 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
596 return std::error_code();
598 // Do nothing if the pointer to export table is NULL.
599 if (DataEntry->RelativeVirtualAddress == 0)
600 return std::error_code();
602 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
603 uintptr_t IntPtr = 0;
604 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
607 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
608 return std::error_code();
611 std::error_code COFFObjectFile::initBaseRelocPtr() {
612 const data_directory *DataEntry;
613 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
614 return std::error_code();
615 if (DataEntry->RelativeVirtualAddress == 0)
616 return std::error_code();
618 uintptr_t IntPtr = 0;
619 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
621 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
623 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
624 IntPtr + DataEntry->Size);
625 return std::error_code();
628 std::error_code COFFObjectFile::initDebugDirectoryPtr() {
629 // Get the RVA of the debug directory. Do nothing if it does not exist.
630 const data_directory *DataEntry;
631 if (getDataDirectory(COFF::DEBUG_DIRECTORY, DataEntry))
632 return std::error_code();
634 // Do nothing if the RVA is NULL.
635 if (DataEntry->RelativeVirtualAddress == 0)
636 return std::error_code();
638 // Check that the size is a multiple of the entry size.
639 if (DataEntry->Size % sizeof(debug_directory) != 0)
640 return object_error::parse_failed;
642 uintptr_t IntPtr = 0;
643 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
645 DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
646 if (std::error_code EC = getRvaPtr(
647 DataEntry->RelativeVirtualAddress + DataEntry->Size, IntPtr))
649 DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(IntPtr);
650 return std::error_code();
653 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
654 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
655 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
656 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
657 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
658 ImportDirectory(nullptr),
659 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
660 ExportDirectory(nullptr), BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
661 DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr) {
662 // Check that we at least have enough room for a header.
663 if (!checkSize(Data, EC, sizeof(coff_file_header)))
666 // The current location in the file where we are looking at.
669 // PE header is optional and is present only in executables. If it exists,
670 // it is placed right after COFF header.
671 bool HasPEHeader = false;
673 // Check if this is a PE/COFF file.
674 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
675 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
676 // PE signature to find 'normal' COFF header.
677 const auto *DH = reinterpret_cast<const dos_header *>(base());
678 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
679 CurPtr = DH->AddressOfNewExeHeader;
680 // Check the PE magic bytes. ("PE\0\0")
681 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
682 EC = object_error::parse_failed;
685 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
690 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
693 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
694 // import libraries share a common prefix but bigobj is more restrictive.
695 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
696 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
697 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
698 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
701 // Verify that we are dealing with bigobj.
702 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
703 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
704 sizeof(COFF::BigObjMagic)) == 0) {
705 COFFHeader = nullptr;
706 CurPtr += sizeof(coff_bigobj_file_header);
708 // It's not a bigobj.
709 COFFBigObjHeader = nullptr;
713 // The prior checkSize call may have failed. This isn't a hard error
714 // because we were just trying to sniff out bigobj.
715 EC = std::error_code();
716 CurPtr += sizeof(coff_file_header);
718 if (COFFHeader->isImportLibrary())
723 const pe32_header *Header;
724 if ((EC = getObject(Header, Data, base() + CurPtr)))
727 const uint8_t *DataDirAddr;
728 uint64_t DataDirSize;
729 if (Header->Magic == COFF::PE32Header::PE32) {
731 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
732 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
733 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
734 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
735 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
736 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
738 // It's neither PE32 nor PE32+.
739 EC = object_error::parse_failed;
742 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
747 CurPtr += COFFHeader->SizeOfOptionalHeader;
749 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
750 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
753 // Initialize the pointer to the symbol table.
754 if (getPointerToSymbolTable() != 0) {
755 if ((EC = initSymbolTablePtr())) {
756 SymbolTable16 = nullptr;
757 SymbolTable32 = nullptr;
758 StringTable = nullptr;
762 // We had better not have any symbols if we don't have a symbol table.
763 if (getNumberOfSymbols() != 0) {
764 EC = object_error::parse_failed;
769 // Initialize the pointer to the beginning of the import table.
770 if ((EC = initImportTablePtr()))
772 if ((EC = initDelayImportTablePtr()))
775 // Initialize the pointer to the export table.
776 if ((EC = initExportTablePtr()))
779 // Initialize the pointer to the base relocation table.
780 if ((EC = initBaseRelocPtr()))
783 // Initialize the pointer to the export table.
784 if ((EC = initDebugDirectoryPtr()))
787 EC = std::error_code();
790 basic_symbol_iterator COFFObjectFile::symbol_begin() const {
792 Ret.p = getSymbolTable();
793 return basic_symbol_iterator(SymbolRef(Ret, this));
796 basic_symbol_iterator COFFObjectFile::symbol_end() const {
797 // The symbol table ends where the string table begins.
799 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
800 return basic_symbol_iterator(SymbolRef(Ret, this));
803 import_directory_iterator COFFObjectFile::import_directory_begin() const {
804 if (!ImportDirectory)
805 return import_directory_end();
806 if (ImportDirectory->isNull())
807 return import_directory_end();
808 return import_directory_iterator(
809 ImportDirectoryEntryRef(ImportDirectory, 0, this));
812 import_directory_iterator COFFObjectFile::import_directory_end() const {
813 return import_directory_iterator(
814 ImportDirectoryEntryRef(nullptr, -1, this));
817 delay_import_directory_iterator
818 COFFObjectFile::delay_import_directory_begin() const {
819 return delay_import_directory_iterator(
820 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
823 delay_import_directory_iterator
824 COFFObjectFile::delay_import_directory_end() const {
825 return delay_import_directory_iterator(
826 DelayImportDirectoryEntryRef(
827 DelayImportDirectory, NumberOfDelayImportDirectory, this));
830 export_directory_iterator COFFObjectFile::export_directory_begin() const {
831 return export_directory_iterator(
832 ExportDirectoryEntryRef(ExportDirectory, 0, this));
835 export_directory_iterator COFFObjectFile::export_directory_end() const {
836 if (!ExportDirectory)
837 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
838 ExportDirectoryEntryRef Ref(ExportDirectory,
839 ExportDirectory->AddressTableEntries, this);
840 return export_directory_iterator(Ref);
843 section_iterator COFFObjectFile::section_begin() const {
845 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
846 return section_iterator(SectionRef(Ret, this));
849 section_iterator COFFObjectFile::section_end() const {
852 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
853 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
854 return section_iterator(SectionRef(Ret, this));
857 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
858 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
861 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
862 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
865 uint8_t COFFObjectFile::getBytesInAddress() const {
866 return getArch() == Triple::x86_64 ? 8 : 4;
869 StringRef COFFObjectFile::getFileFormatName() const {
870 switch(getMachine()) {
871 case COFF::IMAGE_FILE_MACHINE_I386:
873 case COFF::IMAGE_FILE_MACHINE_AMD64:
874 return "COFF-x86-64";
875 case COFF::IMAGE_FILE_MACHINE_ARMNT:
877 case COFF::IMAGE_FILE_MACHINE_ARM64:
880 return "COFF-<unknown arch>";
884 unsigned COFFObjectFile::getArch() const {
885 switch (getMachine()) {
886 case COFF::IMAGE_FILE_MACHINE_I386:
888 case COFF::IMAGE_FILE_MACHINE_AMD64:
889 return Triple::x86_64;
890 case COFF::IMAGE_FILE_MACHINE_ARMNT:
891 return Triple::thumb;
892 case COFF::IMAGE_FILE_MACHINE_ARM64:
893 return Triple::aarch64;
895 return Triple::UnknownArch;
899 iterator_range<import_directory_iterator>
900 COFFObjectFile::import_directories() const {
901 return make_range(import_directory_begin(), import_directory_end());
904 iterator_range<delay_import_directory_iterator>
905 COFFObjectFile::delay_import_directories() const {
906 return make_range(delay_import_directory_begin(),
907 delay_import_directory_end());
910 iterator_range<export_directory_iterator>
911 COFFObjectFile::export_directories() const {
912 return make_range(export_directory_begin(), export_directory_end());
915 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
916 return make_range(base_reloc_begin(), base_reloc_end());
919 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
921 return std::error_code();
925 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
926 Res = PE32PlusHeader;
927 return std::error_code();
931 COFFObjectFile::getDataDirectory(uint32_t Index,
932 const data_directory *&Res) const {
933 // Error if if there's no data directory or the index is out of range.
934 if (!DataDirectory) {
936 return object_error::parse_failed;
938 assert(PE32Header || PE32PlusHeader);
939 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
940 : PE32PlusHeader->NumberOfRvaAndSize;
941 if (Index >= NumEnt) {
943 return object_error::parse_failed;
945 Res = &DataDirectory[Index];
946 return std::error_code();
949 std::error_code COFFObjectFile::getSection(int32_t Index,
950 const coff_section *&Result) const {
952 if (COFF::isReservedSectionNumber(Index))
953 return std::error_code();
954 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
955 // We already verified the section table data, so no need to check again.
956 Result = SectionTable + (Index - 1);
957 return std::error_code();
959 return object_error::parse_failed;
962 std::error_code COFFObjectFile::getString(uint32_t Offset,
963 StringRef &Result) const {
964 if (StringTableSize <= 4)
965 // Tried to get a string from an empty string table.
966 return object_error::parse_failed;
967 if (Offset >= StringTableSize)
968 return object_error::unexpected_eof;
969 Result = StringRef(StringTable + Offset);
970 return std::error_code();
973 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
974 StringRef &Res) const {
975 return getSymbolName(Symbol.getGeneric(), Res);
978 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
979 StringRef &Res) const {
980 // Check for string table entry. First 4 bytes are 0.
981 if (Symbol->Name.Offset.Zeroes == 0) {
982 if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
984 return std::error_code();
987 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
988 // Null terminated, let ::strlen figure out the length.
989 Res = StringRef(Symbol->Name.ShortName);
991 // Not null terminated, use all 8 bytes.
992 Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
993 return std::error_code();
997 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
998 const uint8_t *Aux = nullptr;
1000 size_t SymbolSize = getSymbolTableEntrySize();
1001 if (Symbol.getNumberOfAuxSymbols() > 0) {
1002 // AUX data comes immediately after the symbol in COFF
1003 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
1005 // Verify that the Aux symbol points to a valid entry in the symbol table.
1006 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
1007 if (Offset < getPointerToSymbolTable() ||
1009 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
1010 report_fatal_error("Aux Symbol data was outside of symbol table.");
1012 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
1013 "Aux Symbol data did not point to the beginning of a symbol");
1016 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
1019 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
1020 StringRef &Res) const {
1022 if (Sec->Name[COFF::NameSize - 1] == 0)
1023 // Null terminated, let ::strlen figure out the length.
1026 // Not null terminated, use all 8 bytes.
1027 Name = StringRef(Sec->Name, COFF::NameSize);
1029 // Check for string table entry. First byte is '/'.
1030 if (Name.startswith("/")) {
1032 if (Name.startswith("//")) {
1033 if (decodeBase64StringEntry(Name.substr(2), Offset))
1034 return object_error::parse_failed;
1036 if (Name.substr(1).getAsInteger(10, Offset))
1037 return object_error::parse_failed;
1039 if (std::error_code EC = getString(Offset, Name))
1044 return std::error_code();
1047 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
1048 // SizeOfRawData and VirtualSize change what they represent depending on
1049 // whether or not we have an executable image.
1051 // For object files, SizeOfRawData contains the size of section's data;
1052 // VirtualSize should be zero but isn't due to buggy COFF writers.
1054 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1055 // actual section size is in VirtualSize. It is possible for VirtualSize to
1056 // be greater than SizeOfRawData; the contents past that point should be
1057 // considered to be zero.
1059 return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1060 return Sec->SizeOfRawData;
1064 COFFObjectFile::getSectionContents(const coff_section *Sec,
1065 ArrayRef<uint8_t> &Res) const {
1066 // In COFF, a virtual section won't have any in-file
1067 // content, so the file pointer to the content will be zero.
1068 if (Sec->PointerToRawData == 0)
1069 return std::error_code();
1070 // The only thing that we need to verify is that the contents is contained
1071 // within the file bounds. We don't need to make sure it doesn't cover other
1072 // data, as there's nothing that says that is not allowed.
1073 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1074 uint32_t SectionSize = getSectionSize(Sec);
1075 if (checkOffset(Data, ConStart, SectionSize))
1076 return object_error::parse_failed;
1077 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1078 return std::error_code();
1081 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1082 return reinterpret_cast<const coff_relocation*>(Rel.p);
1085 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1086 Rel.p = reinterpret_cast<uintptr_t>(
1087 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1090 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1091 const coff_relocation *R = toRel(Rel);
1092 return R->VirtualAddress;
1095 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1096 const coff_relocation *R = toRel(Rel);
1098 if (R->SymbolTableIndex >= getNumberOfSymbols())
1099 return symbol_end();
1101 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1102 else if (SymbolTable32)
1103 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1105 llvm_unreachable("no symbol table pointer!");
1106 return symbol_iterator(SymbolRef(Ref, this));
1109 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
1110 const coff_relocation* R = toRel(Rel);
1114 const coff_section *
1115 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1116 return toSec(Section.getRawDataRefImpl());
1119 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1121 return toSymb<coff_symbol16>(Ref);
1123 return toSymb<coff_symbol32>(Ref);
1124 llvm_unreachable("no symbol table pointer!");
1127 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1128 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1131 const coff_relocation *
1132 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1133 return toRel(Reloc.getRawDataRefImpl());
1136 iterator_range<const coff_relocation *>
1137 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1138 const coff_relocation *I = getFirstReloc(Sec, Data, base());
1139 const coff_relocation *E = I;
1141 E += getNumberOfRelocations(Sec, Data, base());
1142 return make_range(I, E);
1145 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1146 case COFF::reloc_type: \
1147 Res = #reloc_type; \
1150 void COFFObjectFile::getRelocationTypeName(
1151 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1152 const coff_relocation *Reloc = toRel(Rel);
1154 switch (getMachine()) {
1155 case COFF::IMAGE_FILE_MACHINE_AMD64:
1156 switch (Reloc->Type) {
1157 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1158 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1159 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1160 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1161 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1162 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1163 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1164 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1165 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1166 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1167 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1168 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1169 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1170 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1171 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1172 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1173 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1178 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1179 switch (Reloc->Type) {
1180 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1181 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1182 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1183 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1184 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1185 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1186 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1187 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1188 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1189 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1190 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1191 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1192 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1193 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1194 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1199 case COFF::IMAGE_FILE_MACHINE_I386:
1200 switch (Reloc->Type) {
1201 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1202 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1203 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1204 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1205 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1206 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1207 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1208 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1209 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1210 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1211 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1219 Result.append(Res.begin(), Res.end());
1222 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1224 bool COFFObjectFile::isRelocatableObject() const {
1225 return !DataDirectory;
1228 bool ImportDirectoryEntryRef::
1229 operator==(const ImportDirectoryEntryRef &Other) const {
1230 return ImportTable == Other.ImportTable && Index == Other.Index;
1233 void ImportDirectoryEntryRef::moveNext() {
1235 if (ImportTable[Index].isNull()) {
1237 ImportTable = nullptr;
1241 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1242 const coff_import_directory_table_entry *&Result) const {
1243 return getObject(Result, OwningObject->Data, ImportTable + Index);
1246 static imported_symbol_iterator
1247 makeImportedSymbolIterator(const COFFObjectFile *Object,
1248 uintptr_t Ptr, int Index) {
1249 if (Object->getBytesInAddress() == 4) {
1250 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1251 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1253 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1254 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1257 static imported_symbol_iterator
1258 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1259 uintptr_t IntPtr = 0;
1260 Object->getRvaPtr(RVA, IntPtr);
1261 return makeImportedSymbolIterator(Object, IntPtr, 0);
1264 static imported_symbol_iterator
1265 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1266 uintptr_t IntPtr = 0;
1267 Object->getRvaPtr(RVA, IntPtr);
1268 // Forward the pointer to the last entry which is null.
1270 if (Object->getBytesInAddress() == 4) {
1271 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1275 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1279 return makeImportedSymbolIterator(Object, IntPtr, Index);
1282 imported_symbol_iterator
1283 ImportDirectoryEntryRef::imported_symbol_begin() const {
1284 return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
1288 imported_symbol_iterator
1289 ImportDirectoryEntryRef::imported_symbol_end() const {
1290 return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
1294 iterator_range<imported_symbol_iterator>
1295 ImportDirectoryEntryRef::imported_symbols() const {
1296 return make_range(imported_symbol_begin(), imported_symbol_end());
1299 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
1300 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1304 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
1305 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1309 iterator_range<imported_symbol_iterator>
1310 ImportDirectoryEntryRef::lookup_table_symbols() const {
1311 return make_range(lookup_table_begin(), lookup_table_end());
1314 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1315 uintptr_t IntPtr = 0;
1316 if (std::error_code EC =
1317 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1319 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1320 return std::error_code();
1324 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1325 Result = ImportTable[Index].ImportLookupTableRVA;
1326 return std::error_code();
1330 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1331 Result = ImportTable[Index].ImportAddressTableRVA;
1332 return std::error_code();
1335 bool DelayImportDirectoryEntryRef::
1336 operator==(const DelayImportDirectoryEntryRef &Other) const {
1337 return Table == Other.Table && Index == Other.Index;
1340 void DelayImportDirectoryEntryRef::moveNext() {
1344 imported_symbol_iterator
1345 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1346 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1350 imported_symbol_iterator
1351 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1352 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1356 iterator_range<imported_symbol_iterator>
1357 DelayImportDirectoryEntryRef::imported_symbols() const {
1358 return make_range(imported_symbol_begin(), imported_symbol_end());
1361 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1362 uintptr_t IntPtr = 0;
1363 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1365 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1366 return std::error_code();
1369 std::error_code DelayImportDirectoryEntryRef::
1370 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1372 return std::error_code();
1375 std::error_code DelayImportDirectoryEntryRef::
1376 getImportAddress(int AddrIndex, uint64_t &Result) const {
1377 uint32_t RVA = Table[Index].DelayImportAddressTable +
1378 AddrIndex * (OwningObject->is64() ? 8 : 4);
1379 uintptr_t IntPtr = 0;
1380 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1382 if (OwningObject->is64())
1383 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1385 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1386 return std::error_code();
1389 bool ExportDirectoryEntryRef::
1390 operator==(const ExportDirectoryEntryRef &Other) const {
1391 return ExportTable == Other.ExportTable && Index == Other.Index;
1394 void ExportDirectoryEntryRef::moveNext() {
1398 // Returns the name of the current export symbol. If the symbol is exported only
1399 // by ordinal, the empty string is set as a result.
1400 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1401 uintptr_t IntPtr = 0;
1402 if (std::error_code EC =
1403 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1405 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1406 return std::error_code();
1409 // Returns the starting ordinal number.
1411 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1412 Result = ExportTable->OrdinalBase;
1413 return std::error_code();
1416 // Returns the export ordinal of the current export symbol.
1417 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1418 Result = ExportTable->OrdinalBase + Index;
1419 return std::error_code();
1422 // Returns the address of the current export symbol.
1423 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1424 uintptr_t IntPtr = 0;
1425 if (std::error_code EC =
1426 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1428 const export_address_table_entry *entry =
1429 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1430 Result = entry[Index].ExportRVA;
1431 return std::error_code();
1434 // Returns the name of the current export symbol. If the symbol is exported only
1435 // by ordinal, the empty string is set as a result.
1437 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1438 uintptr_t IntPtr = 0;
1439 if (std::error_code EC =
1440 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1442 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1444 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1446 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1447 I < E; ++I, ++Offset) {
1450 if (std::error_code EC =
1451 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1453 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1454 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1456 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1457 return std::error_code();
1460 return std::error_code();
1463 std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1464 const data_directory *DataEntry;
1465 if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
1468 if (auto EC = getExportRVA(RVA))
1470 uint32_t Begin = DataEntry->RelativeVirtualAddress;
1471 uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1472 Result = (Begin <= RVA && RVA < End);
1473 return std::error_code();
1476 std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1478 if (auto EC = getExportRVA(RVA))
1480 uintptr_t IntPtr = 0;
1481 if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1483 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1484 return std::error_code();
1487 bool ImportedSymbolRef::
1488 operator==(const ImportedSymbolRef &Other) const {
1489 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1490 && Index == Other.Index;
1493 void ImportedSymbolRef::moveNext() {
1498 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1501 // If a symbol is imported only by ordinal, it has no name.
1502 if (Entry32[Index].isOrdinal())
1503 return std::error_code();
1504 RVA = Entry32[Index].getHintNameRVA();
1506 if (Entry64[Index].isOrdinal())
1507 return std::error_code();
1508 RVA = Entry64[Index].getHintNameRVA();
1510 uintptr_t IntPtr = 0;
1511 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1513 // +2 because the first two bytes is hint.
1514 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1515 return std::error_code();
1518 std::error_code ImportedSymbolRef::isOrdinal(bool &Result) const {
1520 Result = Entry32[Index].isOrdinal();
1522 Result = Entry64[Index].isOrdinal();
1523 return std::error_code();
1526 std::error_code ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
1528 Result = Entry32[Index].getHintNameRVA();
1530 Result = Entry64[Index].getHintNameRVA();
1531 return std::error_code();
1534 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1537 if (Entry32[Index].isOrdinal()) {
1538 Result = Entry32[Index].getOrdinal();
1539 return std::error_code();
1541 RVA = Entry32[Index].getHintNameRVA();
1543 if (Entry64[Index].isOrdinal()) {
1544 Result = Entry64[Index].getOrdinal();
1545 return std::error_code();
1547 RVA = Entry64[Index].getHintNameRVA();
1549 uintptr_t IntPtr = 0;
1550 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1552 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1553 return std::error_code();
1556 ErrorOr<std::unique_ptr<COFFObjectFile>>
1557 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1559 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1562 return std::move(Ret);
1565 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1566 return Header == Other.Header && Index == Other.Index;
1569 void BaseRelocRef::moveNext() {
1570 // Header->BlockSize is the size of the current block, including the
1571 // size of the header itself.
1572 uint32_t Size = sizeof(*Header) +
1573 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1574 if (Size == Header->BlockSize) {
1575 // .reloc contains a list of base relocation blocks. Each block
1576 // consists of the header followed by entries. The header contains
1577 // how many entories will follow. When we reach the end of the
1578 // current block, proceed to the next block.
1579 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1580 reinterpret_cast<const uint8_t *>(Header) + Size);
1587 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1588 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1589 Type = Entry[Index].getType();
1590 return std::error_code();
1593 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1594 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1595 Result = Header->PageRVA + Entry[Index].getOffset();
1596 return std::error_code();
1599 #define RETURN_IF_ERROR(X) \
1600 if (auto EC = errorToErrorCode(X)) \
1603 ErrorOr<ArrayRef<UTF16>> ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) {
1604 BinaryStreamReader Reader = BinaryStreamReader(BBS);
1605 Reader.setOffset(Offset);
1607 RETURN_IF_ERROR(Reader.readInteger(Length));
1608 ArrayRef<UTF16> RawDirString;
1609 RETURN_IF_ERROR(Reader.readArray(RawDirString, Length));
1610 return RawDirString;
1613 ErrorOr<ArrayRef<UTF16>>
1614 ResourceSectionRef::getEntryNameString(const coff_resource_dir_entry &Entry) {
1615 return getDirStringAtOffset(Entry.Identifier.getNameOffset());
1618 ErrorOr<const coff_resource_dir_table &>
1619 ResourceSectionRef::getTableAtOffset(uint32_t Offset) {
1620 const coff_resource_dir_table *Table = nullptr;
1622 BinaryStreamReader Reader(BBS);
1623 Reader.setOffset(Offset);
1624 RETURN_IF_ERROR(Reader.readObject(Table));
1625 assert(Table != nullptr);
1629 ErrorOr<const coff_resource_dir_table &>
1630 ResourceSectionRef::getEntrySubDir(const coff_resource_dir_entry &Entry) {
1631 return getTableAtOffset(Entry.Offset.value());
1634 ErrorOr<const coff_resource_dir_table &> ResourceSectionRef::getBaseTable() {
1635 return getTableAtOffset(0);