1 //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===//
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/Object/COFF.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/ADT/iterator_range.h"
19 #include "llvm/Support/COFF.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
26 using namespace object;
28 using support::ulittle16_t;
29 using support::ulittle32_t;
30 using support::ulittle64_t;
31 using support::little16_t;
33 // Returns false if size is greater than the buffer size. And sets ec.
34 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
35 if (M.getBufferSize() < Size) {
36 EC = object_error::unexpected_eof;
42 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
43 const uint64_t Size) {
44 if (Addr + Size < Addr || Addr + Size < Size ||
45 Addr + Size > uintptr_t(M.getBufferEnd()) ||
46 Addr < uintptr_t(M.getBufferStart())) {
47 return object_error::unexpected_eof;
49 return std::error_code();
52 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
53 // Returns unexpected_eof if error.
55 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
57 const uint64_t Size = sizeof(T)) {
58 uintptr_t Addr = uintptr_t(Ptr);
59 if (std::error_code EC = checkOffset(M, Addr, Size))
61 Obj = reinterpret_cast<const T *>(Addr);
62 return std::error_code();
65 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
67 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
68 assert(Str.size() <= 6 && "String too long, possible overflow.");
73 while (!Str.empty()) {
75 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
76 CharVal = Str[0] - 'A';
77 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
78 CharVal = Str[0] - 'a' + 26;
79 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
80 CharVal = Str[0] - '0' + 52;
81 else if (Str[0] == '+') // 62
83 else if (Str[0] == '/') // 63
88 Value = (Value * 64) + CharVal;
92 if (Value > std::numeric_limits<uint32_t>::max())
95 Result = static_cast<uint32_t>(Value);
99 template <typename coff_symbol_type>
100 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
101 const coff_symbol_type *Addr =
102 reinterpret_cast<const coff_symbol_type *>(Ref.p);
104 assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
106 // Verify that the symbol points to a valid entry in the symbol table.
107 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
109 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
110 "Symbol did not point to the beginning of a symbol");
116 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
117 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
120 // Verify that the section points to a valid entry in the section table.
121 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
122 report_fatal_error("Section was outside of section table.");
124 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
125 assert(Offset % sizeof(coff_section) == 0 &&
126 "Section did not point to the beginning of a section");
132 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
133 auto End = reinterpret_cast<uintptr_t>(StringTable);
135 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
136 Symb += 1 + Symb->NumberOfAuxSymbols;
137 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
138 } else if (SymbolTable32) {
139 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
140 Symb += 1 + Symb->NumberOfAuxSymbols;
141 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
143 llvm_unreachable("no symbol table pointer!");
147 Expected<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
148 COFFSymbolRef Symb = getCOFFSymbol(Ref);
150 std::error_code EC = getSymbolName(Symb, Result);
152 return errorCodeToError(EC);
156 uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const {
157 return getCOFFSymbol(Ref).getValue();
160 uint32_t COFFObjectFile::getSymbolAlignment(DataRefImpl Ref) const {
161 // MSVC/link.exe seems to align symbols to the next-power-of-2
163 COFFSymbolRef Symb = getCOFFSymbol(Ref);
164 return std::min(uint64_t(32), PowerOf2Ceil(Symb.getValue()));
167 Expected<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
168 uint64_t Result = getSymbolValue(Ref);
169 COFFSymbolRef Symb = getCOFFSymbol(Ref);
170 int32_t SectionNumber = Symb.getSectionNumber();
172 if (Symb.isAnyUndefined() || Symb.isCommon() ||
173 COFF::isReservedSectionNumber(SectionNumber))
176 const coff_section *Section = nullptr;
177 if (std::error_code EC = getSection(SectionNumber, Section))
178 return errorCodeToError(EC);
179 Result += Section->VirtualAddress;
181 // The section VirtualAddress does not include ImageBase, and we want to
182 // return virtual addresses.
183 Result += getImageBase();
188 Expected<SymbolRef::Type> COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
189 COFFSymbolRef Symb = getCOFFSymbol(Ref);
190 int32_t SectionNumber = Symb.getSectionNumber();
192 if (Symb.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION)
193 return SymbolRef::ST_Function;
194 if (Symb.isAnyUndefined())
195 return SymbolRef::ST_Unknown;
197 return SymbolRef::ST_Data;
198 if (Symb.isFileRecord())
199 return SymbolRef::ST_File;
201 // TODO: perhaps we need a new symbol type ST_Section.
202 if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
203 return SymbolRef::ST_Debug;
205 if (!COFF::isReservedSectionNumber(SectionNumber))
206 return SymbolRef::ST_Data;
208 return SymbolRef::ST_Other;
211 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
212 COFFSymbolRef Symb = getCOFFSymbol(Ref);
213 uint32_t Result = SymbolRef::SF_None;
215 if (Symb.isExternal() || Symb.isWeakExternal())
216 Result |= SymbolRef::SF_Global;
218 if (Symb.isWeakExternal())
219 Result |= SymbolRef::SF_Weak;
221 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
222 Result |= SymbolRef::SF_Absolute;
224 if (Symb.isFileRecord())
225 Result |= SymbolRef::SF_FormatSpecific;
227 if (Symb.isSectionDefinition())
228 Result |= SymbolRef::SF_FormatSpecific;
231 Result |= SymbolRef::SF_Common;
233 if (Symb.isAnyUndefined())
234 Result |= SymbolRef::SF_Undefined;
239 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
240 COFFSymbolRef Symb = getCOFFSymbol(Ref);
241 return Symb.getValue();
244 Expected<section_iterator>
245 COFFObjectFile::getSymbolSection(DataRefImpl Ref) const {
246 COFFSymbolRef Symb = getCOFFSymbol(Ref);
247 if (COFF::isReservedSectionNumber(Symb.getSectionNumber()))
248 return section_end();
249 const coff_section *Sec = nullptr;
250 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
251 return errorCodeToError(EC);
253 Ret.p = reinterpret_cast<uintptr_t>(Sec);
254 return section_iterator(SectionRef(Ret, this));
257 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
258 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
259 return Symb.getSectionNumber();
262 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
263 const coff_section *Sec = toSec(Ref);
265 Ref.p = reinterpret_cast<uintptr_t>(Sec);
268 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
269 StringRef &Result) const {
270 const coff_section *Sec = toSec(Ref);
271 return getSectionName(Sec, Result);
274 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
275 const coff_section *Sec = toSec(Ref);
276 uint64_t Result = Sec->VirtualAddress;
278 // The section VirtualAddress does not include ImageBase, and we want to
279 // return virtual addresses.
280 Result += getImageBase();
284 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
285 return getSectionSize(toSec(Ref));
288 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
289 StringRef &Result) const {
290 const coff_section *Sec = toSec(Ref);
291 ArrayRef<uint8_t> Res;
292 std::error_code EC = getSectionContents(Sec, Res);
293 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
297 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
298 const coff_section *Sec = toSec(Ref);
299 return Sec->getAlignment();
302 bool COFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
306 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
307 const coff_section *Sec = toSec(Ref);
308 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
311 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
312 const coff_section *Sec = toSec(Ref);
313 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
316 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
317 const coff_section *Sec = toSec(Ref);
318 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
319 COFF::IMAGE_SCN_MEM_READ |
320 COFF::IMAGE_SCN_MEM_WRITE;
321 return (Sec->Characteristics & BssFlags) == BssFlags;
324 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
326 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
327 assert((Offset % sizeof(coff_section)) == 0);
328 return (Offset / sizeof(coff_section)) + 1;
331 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
332 const coff_section *Sec = toSec(Ref);
333 // In COFF, a virtual section won't have any in-file
334 // content, so the file pointer to the content will be zero.
335 return Sec->PointerToRawData == 0;
338 static uint32_t getNumberOfRelocations(const coff_section *Sec,
339 MemoryBufferRef M, const uint8_t *base) {
340 // The field for the number of relocations in COFF section table is only
341 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
342 // NumberOfRelocations field, and the actual relocation count is stored in the
343 // VirtualAddress field in the first relocation entry.
344 if (Sec->hasExtendedRelocations()) {
345 const coff_relocation *FirstReloc;
346 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
347 base + Sec->PointerToRelocations)))
349 // -1 to exclude this first relocation entry.
350 return FirstReloc->VirtualAddress - 1;
352 return Sec->NumberOfRelocations;
355 static const coff_relocation *
356 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
357 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
360 auto begin = reinterpret_cast<const coff_relocation *>(
361 Base + Sec->PointerToRelocations);
362 if (Sec->hasExtendedRelocations()) {
363 // Skip the first relocation entry repurposed to store the number of
367 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
372 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
373 const coff_section *Sec = toSec(Ref);
374 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
375 if (begin && Sec->VirtualAddress != 0)
376 report_fatal_error("Sections with relocations should have an address of 0");
378 Ret.p = reinterpret_cast<uintptr_t>(begin);
379 return relocation_iterator(RelocationRef(Ret, this));
382 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
383 const coff_section *Sec = toSec(Ref);
384 const coff_relocation *I = getFirstReloc(Sec, Data, base());
386 I += getNumberOfRelocations(Sec, Data, base());
388 Ret.p = reinterpret_cast<uintptr_t>(I);
389 return relocation_iterator(RelocationRef(Ret, this));
392 // Initialize the pointer to the symbol table.
393 std::error_code COFFObjectFile::initSymbolTablePtr() {
395 if (std::error_code EC = getObject(
396 SymbolTable16, Data, base() + getPointerToSymbolTable(),
397 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
400 if (COFFBigObjHeader)
401 if (std::error_code EC = getObject(
402 SymbolTable32, Data, base() + getPointerToSymbolTable(),
403 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
406 // Find string table. The first four byte of the string table contains the
407 // total size of the string table, including the size field itself. If the
408 // string table is empty, the value of the first four byte would be 4.
409 uint32_t StringTableOffset = getPointerToSymbolTable() +
410 getNumberOfSymbols() * getSymbolTableEntrySize();
411 const uint8_t *StringTableAddr = base() + StringTableOffset;
412 const ulittle32_t *StringTableSizePtr;
413 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
415 StringTableSize = *StringTableSizePtr;
416 if (std::error_code EC =
417 getObject(StringTable, Data, StringTableAddr, StringTableSize))
420 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
421 // tools like cvtres write a size of 0 for an empty table instead of 4.
422 if (StringTableSize < 4)
425 // Check that the string table is null terminated if has any in it.
426 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
427 return object_error::parse_failed;
428 return std::error_code();
431 uint64_t COFFObjectFile::getImageBase() const {
433 return PE32Header->ImageBase;
434 else if (PE32PlusHeader)
435 return PE32PlusHeader->ImageBase;
436 // This actually comes up in practice.
440 // Returns the file offset for the given VA.
441 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
442 uint64_t ImageBase = getImageBase();
443 uint64_t Rva = Addr - ImageBase;
444 assert(Rva <= UINT32_MAX);
445 return getRvaPtr((uint32_t)Rva, Res);
448 // Returns the file offset for the given RVA.
449 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
450 for (const SectionRef &S : sections()) {
451 const coff_section *Section = getCOFFSection(S);
452 uint32_t SectionStart = Section->VirtualAddress;
453 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
454 if (SectionStart <= Addr && Addr < SectionEnd) {
455 uint32_t Offset = Addr - SectionStart;
456 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
457 return std::error_code();
460 return object_error::parse_failed;
464 COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
465 ArrayRef<uint8_t> &Contents) const {
466 for (const SectionRef &S : sections()) {
467 const coff_section *Section = getCOFFSection(S);
468 uint32_t SectionStart = Section->VirtualAddress;
469 // Check if this RVA is within the section bounds. Be careful about integer
471 uint32_t OffsetIntoSection = RVA - SectionStart;
472 if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize &&
473 Size <= Section->VirtualSize - OffsetIntoSection) {
475 uintptr_t(base()) + Section->PointerToRawData + OffsetIntoSection;
477 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size);
478 return std::error_code();
481 return object_error::parse_failed;
484 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
486 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
487 StringRef &Name) const {
488 uintptr_t IntPtr = 0;
489 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
491 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
492 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
493 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
494 return std::error_code();
498 COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir,
499 const codeview::DebugInfo *&PDBInfo,
500 StringRef &PDBFileName) const {
501 ArrayRef<uint8_t> InfoBytes;
502 if (std::error_code EC = getRvaAndSizeAsBytes(
503 DebugDir->AddressOfRawData, DebugDir->SizeOfData, InfoBytes))
505 if (InfoBytes.size() < sizeof(*PDBInfo) + 1)
506 return object_error::parse_failed;
507 PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data());
508 InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo));
509 PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()),
511 // Truncate the name at the first null byte. Ignore any padding.
512 PDBFileName = PDBFileName.split('\0').first;
513 return std::error_code();
517 COFFObjectFile::getDebugPDBInfo(const codeview::DebugInfo *&PDBInfo,
518 StringRef &PDBFileName) const {
519 for (const debug_directory &D : debug_directories())
520 if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW)
521 return getDebugPDBInfo(&D, PDBInfo, PDBFileName);
522 // If we get here, there is no PDB info to return.
524 PDBFileName = StringRef();
525 return std::error_code();
528 // Find the import table.
529 std::error_code COFFObjectFile::initImportTablePtr() {
530 // First, we get the RVA of the import table. If the file lacks a pointer to
531 // the import table, do nothing.
532 const data_directory *DataEntry;
533 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
534 return std::error_code();
536 // Do nothing if the pointer to import table is NULL.
537 if (DataEntry->RelativeVirtualAddress == 0)
538 return std::error_code();
540 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
542 // Find the section that contains the RVA. This is needed because the RVA is
543 // the import table's memory address which is different from its file offset.
544 uintptr_t IntPtr = 0;
545 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
547 if (std::error_code EC = checkOffset(Data, IntPtr, DataEntry->Size))
549 ImportDirectory = reinterpret_cast<
550 const coff_import_directory_table_entry *>(IntPtr);
551 return std::error_code();
554 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
555 std::error_code COFFObjectFile::initDelayImportTablePtr() {
556 const data_directory *DataEntry;
557 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
558 return std::error_code();
559 if (DataEntry->RelativeVirtualAddress == 0)
560 return std::error_code();
562 uint32_t RVA = DataEntry->RelativeVirtualAddress;
563 NumberOfDelayImportDirectory = DataEntry->Size /
564 sizeof(delay_import_directory_table_entry) - 1;
566 uintptr_t IntPtr = 0;
567 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
569 DelayImportDirectory = reinterpret_cast<
570 const delay_import_directory_table_entry *>(IntPtr);
571 return std::error_code();
574 // Find the export table.
575 std::error_code COFFObjectFile::initExportTablePtr() {
576 // First, we get the RVA of the export table. If the file lacks a pointer to
577 // the export table, do nothing.
578 const data_directory *DataEntry;
579 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
580 return std::error_code();
582 // Do nothing if the pointer to export table is NULL.
583 if (DataEntry->RelativeVirtualAddress == 0)
584 return std::error_code();
586 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
587 uintptr_t IntPtr = 0;
588 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
591 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
592 return std::error_code();
595 std::error_code COFFObjectFile::initBaseRelocPtr() {
596 const data_directory *DataEntry;
597 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
598 return std::error_code();
599 if (DataEntry->RelativeVirtualAddress == 0)
600 return std::error_code();
602 uintptr_t IntPtr = 0;
603 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
605 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
607 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
608 IntPtr + DataEntry->Size);
609 return std::error_code();
612 std::error_code COFFObjectFile::initDebugDirectoryPtr() {
613 // Get the RVA of the debug directory. Do nothing if it does not exist.
614 const data_directory *DataEntry;
615 if (getDataDirectory(COFF::DEBUG_DIRECTORY, DataEntry))
616 return std::error_code();
618 // Do nothing if the RVA is NULL.
619 if (DataEntry->RelativeVirtualAddress == 0)
620 return std::error_code();
622 // Check that the size is a multiple of the entry size.
623 if (DataEntry->Size % sizeof(debug_directory) != 0)
624 return object_error::parse_failed;
626 uintptr_t IntPtr = 0;
627 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
629 DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
630 if (std::error_code EC = getRvaPtr(
631 DataEntry->RelativeVirtualAddress + DataEntry->Size, IntPtr))
633 DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(IntPtr);
634 return std::error_code();
637 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
638 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
639 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
640 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
641 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
642 ImportDirectory(nullptr),
643 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
644 ExportDirectory(nullptr), BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
645 DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr) {
646 // Check that we at least have enough room for a header.
647 if (!checkSize(Data, EC, sizeof(coff_file_header)))
650 // The current location in the file where we are looking at.
653 // PE header is optional and is present only in executables. If it exists,
654 // it is placed right after COFF header.
655 bool HasPEHeader = false;
657 // Check if this is a PE/COFF file.
658 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
659 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
660 // PE signature to find 'normal' COFF header.
661 const auto *DH = reinterpret_cast<const dos_header *>(base());
662 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
663 CurPtr = DH->AddressOfNewExeHeader;
664 // Check the PE magic bytes. ("PE\0\0")
665 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
666 EC = object_error::parse_failed;
669 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
674 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
677 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
678 // import libraries share a common prefix but bigobj is more restrictive.
679 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
680 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
681 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
682 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
685 // Verify that we are dealing with bigobj.
686 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
687 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
688 sizeof(COFF::BigObjMagic)) == 0) {
689 COFFHeader = nullptr;
690 CurPtr += sizeof(coff_bigobj_file_header);
692 // It's not a bigobj.
693 COFFBigObjHeader = nullptr;
697 // The prior checkSize call may have failed. This isn't a hard error
698 // because we were just trying to sniff out bigobj.
699 EC = std::error_code();
700 CurPtr += sizeof(coff_file_header);
702 if (COFFHeader->isImportLibrary())
707 const pe32_header *Header;
708 if ((EC = getObject(Header, Data, base() + CurPtr)))
711 const uint8_t *DataDirAddr;
712 uint64_t DataDirSize;
713 if (Header->Magic == COFF::PE32Header::PE32) {
715 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
716 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
717 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
718 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
719 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
720 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
722 // It's neither PE32 nor PE32+.
723 EC = object_error::parse_failed;
726 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
731 CurPtr += COFFHeader->SizeOfOptionalHeader;
733 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
734 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
737 // Initialize the pointer to the symbol table.
738 if (getPointerToSymbolTable() != 0) {
739 if ((EC = initSymbolTablePtr())) {
740 SymbolTable16 = nullptr;
741 SymbolTable32 = nullptr;
742 StringTable = nullptr;
746 // We had better not have any symbols if we don't have a symbol table.
747 if (getNumberOfSymbols() != 0) {
748 EC = object_error::parse_failed;
753 // Initialize the pointer to the beginning of the import table.
754 if ((EC = initImportTablePtr()))
756 if ((EC = initDelayImportTablePtr()))
759 // Initialize the pointer to the export table.
760 if ((EC = initExportTablePtr()))
763 // Initialize the pointer to the base relocation table.
764 if ((EC = initBaseRelocPtr()))
767 // Initialize the pointer to the export table.
768 if ((EC = initDebugDirectoryPtr()))
771 EC = std::error_code();
774 basic_symbol_iterator COFFObjectFile::symbol_begin() const {
776 Ret.p = getSymbolTable();
777 return basic_symbol_iterator(SymbolRef(Ret, this));
780 basic_symbol_iterator COFFObjectFile::symbol_end() const {
781 // The symbol table ends where the string table begins.
783 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
784 return basic_symbol_iterator(SymbolRef(Ret, this));
787 import_directory_iterator COFFObjectFile::import_directory_begin() const {
788 if (!ImportDirectory)
789 return import_directory_end();
790 if (ImportDirectory->isNull())
791 return import_directory_end();
792 return import_directory_iterator(
793 ImportDirectoryEntryRef(ImportDirectory, 0, this));
796 import_directory_iterator COFFObjectFile::import_directory_end() const {
797 return import_directory_iterator(
798 ImportDirectoryEntryRef(nullptr, -1, this));
801 delay_import_directory_iterator
802 COFFObjectFile::delay_import_directory_begin() const {
803 return delay_import_directory_iterator(
804 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
807 delay_import_directory_iterator
808 COFFObjectFile::delay_import_directory_end() const {
809 return delay_import_directory_iterator(
810 DelayImportDirectoryEntryRef(
811 DelayImportDirectory, NumberOfDelayImportDirectory, this));
814 export_directory_iterator COFFObjectFile::export_directory_begin() const {
815 return export_directory_iterator(
816 ExportDirectoryEntryRef(ExportDirectory, 0, this));
819 export_directory_iterator COFFObjectFile::export_directory_end() const {
820 if (!ExportDirectory)
821 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
822 ExportDirectoryEntryRef Ref(ExportDirectory,
823 ExportDirectory->AddressTableEntries, this);
824 return export_directory_iterator(Ref);
827 section_iterator COFFObjectFile::section_begin() const {
829 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
830 return section_iterator(SectionRef(Ret, this));
833 section_iterator COFFObjectFile::section_end() const {
836 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
837 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
838 return section_iterator(SectionRef(Ret, this));
841 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
842 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
845 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
846 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
849 uint8_t COFFObjectFile::getBytesInAddress() const {
850 return getArch() == Triple::x86_64 ? 8 : 4;
853 StringRef COFFObjectFile::getFileFormatName() const {
854 switch(getMachine()) {
855 case COFF::IMAGE_FILE_MACHINE_I386:
857 case COFF::IMAGE_FILE_MACHINE_AMD64:
858 return "COFF-x86-64";
859 case COFF::IMAGE_FILE_MACHINE_ARMNT:
861 case COFF::IMAGE_FILE_MACHINE_ARM64:
864 return "COFF-<unknown arch>";
868 unsigned COFFObjectFile::getArch() const {
869 switch (getMachine()) {
870 case COFF::IMAGE_FILE_MACHINE_I386:
872 case COFF::IMAGE_FILE_MACHINE_AMD64:
873 return Triple::x86_64;
874 case COFF::IMAGE_FILE_MACHINE_ARMNT:
875 return Triple::thumb;
876 case COFF::IMAGE_FILE_MACHINE_ARM64:
877 return Triple::aarch64;
879 return Triple::UnknownArch;
883 iterator_range<import_directory_iterator>
884 COFFObjectFile::import_directories() const {
885 return make_range(import_directory_begin(), import_directory_end());
888 iterator_range<delay_import_directory_iterator>
889 COFFObjectFile::delay_import_directories() const {
890 return make_range(delay_import_directory_begin(),
891 delay_import_directory_end());
894 iterator_range<export_directory_iterator>
895 COFFObjectFile::export_directories() const {
896 return make_range(export_directory_begin(), export_directory_end());
899 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
900 return make_range(base_reloc_begin(), base_reloc_end());
903 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
905 return std::error_code();
909 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
910 Res = PE32PlusHeader;
911 return std::error_code();
915 COFFObjectFile::getDataDirectory(uint32_t Index,
916 const data_directory *&Res) const {
917 // Error if if there's no data directory or the index is out of range.
918 if (!DataDirectory) {
920 return object_error::parse_failed;
922 assert(PE32Header || PE32PlusHeader);
923 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
924 : PE32PlusHeader->NumberOfRvaAndSize;
925 if (Index >= NumEnt) {
927 return object_error::parse_failed;
929 Res = &DataDirectory[Index];
930 return std::error_code();
933 std::error_code COFFObjectFile::getSection(int32_t Index,
934 const coff_section *&Result) const {
936 if (COFF::isReservedSectionNumber(Index))
937 return std::error_code();
938 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
939 // We already verified the section table data, so no need to check again.
940 Result = SectionTable + (Index - 1);
941 return std::error_code();
943 return object_error::parse_failed;
946 std::error_code COFFObjectFile::getString(uint32_t Offset,
947 StringRef &Result) const {
948 if (StringTableSize <= 4)
949 // Tried to get a string from an empty string table.
950 return object_error::parse_failed;
951 if (Offset >= StringTableSize)
952 return object_error::unexpected_eof;
953 Result = StringRef(StringTable + Offset);
954 return std::error_code();
957 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
958 StringRef &Res) const {
959 return getSymbolName(Symbol.getGeneric(), Res);
962 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
963 StringRef &Res) const {
964 // Check for string table entry. First 4 bytes are 0.
965 if (Symbol->Name.Offset.Zeroes == 0) {
966 if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
968 return std::error_code();
971 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
972 // Null terminated, let ::strlen figure out the length.
973 Res = StringRef(Symbol->Name.ShortName);
975 // Not null terminated, use all 8 bytes.
976 Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
977 return std::error_code();
981 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
982 const uint8_t *Aux = nullptr;
984 size_t SymbolSize = getSymbolTableEntrySize();
985 if (Symbol.getNumberOfAuxSymbols() > 0) {
986 // AUX data comes immediately after the symbol in COFF
987 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
989 // Verify that the Aux symbol points to a valid entry in the symbol table.
990 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
991 if (Offset < getPointerToSymbolTable() ||
993 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
994 report_fatal_error("Aux Symbol data was outside of symbol table.");
996 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
997 "Aux Symbol data did not point to the beginning of a symbol");
1000 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
1003 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
1004 StringRef &Res) const {
1006 if (Sec->Name[COFF::NameSize - 1] == 0)
1007 // Null terminated, let ::strlen figure out the length.
1010 // Not null terminated, use all 8 bytes.
1011 Name = StringRef(Sec->Name, COFF::NameSize);
1013 // Check for string table entry. First byte is '/'.
1014 if (Name.startswith("/")) {
1016 if (Name.startswith("//")) {
1017 if (decodeBase64StringEntry(Name.substr(2), Offset))
1018 return object_error::parse_failed;
1020 if (Name.substr(1).getAsInteger(10, Offset))
1021 return object_error::parse_failed;
1023 if (std::error_code EC = getString(Offset, Name))
1028 return std::error_code();
1031 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
1032 // SizeOfRawData and VirtualSize change what they represent depending on
1033 // whether or not we have an executable image.
1035 // For object files, SizeOfRawData contains the size of section's data;
1036 // VirtualSize should be zero but isn't due to buggy COFF writers.
1038 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1039 // actual section size is in VirtualSize. It is possible for VirtualSize to
1040 // be greater than SizeOfRawData; the contents past that point should be
1041 // considered to be zero.
1043 return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1044 return Sec->SizeOfRawData;
1048 COFFObjectFile::getSectionContents(const coff_section *Sec,
1049 ArrayRef<uint8_t> &Res) const {
1050 // In COFF, a virtual section won't have any in-file
1051 // content, so the file pointer to the content will be zero.
1052 if (Sec->PointerToRawData == 0)
1053 return object_error::parse_failed;
1054 // The only thing that we need to verify is that the contents is contained
1055 // within the file bounds. We don't need to make sure it doesn't cover other
1056 // data, as there's nothing that says that is not allowed.
1057 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1058 uint32_t SectionSize = getSectionSize(Sec);
1059 if (checkOffset(Data, ConStart, SectionSize))
1060 return object_error::parse_failed;
1061 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1062 return std::error_code();
1065 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1066 return reinterpret_cast<const coff_relocation*>(Rel.p);
1069 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1070 Rel.p = reinterpret_cast<uintptr_t>(
1071 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1074 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1075 const coff_relocation *R = toRel(Rel);
1076 return R->VirtualAddress;
1079 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1080 const coff_relocation *R = toRel(Rel);
1082 if (R->SymbolTableIndex >= getNumberOfSymbols())
1083 return symbol_end();
1085 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1086 else if (SymbolTable32)
1087 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1089 llvm_unreachable("no symbol table pointer!");
1090 return symbol_iterator(SymbolRef(Ref, this));
1093 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
1094 const coff_relocation* R = toRel(Rel);
1098 const coff_section *
1099 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1100 return toSec(Section.getRawDataRefImpl());
1103 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1105 return toSymb<coff_symbol16>(Ref);
1107 return toSymb<coff_symbol32>(Ref);
1108 llvm_unreachable("no symbol table pointer!");
1111 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1112 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1115 const coff_relocation *
1116 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1117 return toRel(Reloc.getRawDataRefImpl());
1120 iterator_range<const coff_relocation *>
1121 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1122 const coff_relocation *I = getFirstReloc(Sec, Data, base());
1123 const coff_relocation *E = I;
1125 E += getNumberOfRelocations(Sec, Data, base());
1126 return make_range(I, E);
1129 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1130 case COFF::reloc_type: \
1131 Res = #reloc_type; \
1134 void COFFObjectFile::getRelocationTypeName(
1135 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1136 const coff_relocation *Reloc = toRel(Rel);
1138 switch (getMachine()) {
1139 case COFF::IMAGE_FILE_MACHINE_AMD64:
1140 switch (Reloc->Type) {
1141 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1142 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1143 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1144 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1145 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1146 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1147 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1148 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1149 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1150 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1151 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1152 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1153 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1154 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1155 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1156 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1157 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1162 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1163 switch (Reloc->Type) {
1164 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1165 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1166 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1167 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1168 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1169 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1170 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1171 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1172 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1173 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1174 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1175 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1176 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1177 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1178 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1183 case COFF::IMAGE_FILE_MACHINE_I386:
1184 switch (Reloc->Type) {
1185 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1186 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1187 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1188 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1189 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1190 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1191 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1192 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1193 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1194 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1195 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1203 Result.append(Res.begin(), Res.end());
1206 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1208 bool COFFObjectFile::isRelocatableObject() const {
1209 return !DataDirectory;
1212 bool ImportDirectoryEntryRef::
1213 operator==(const ImportDirectoryEntryRef &Other) const {
1214 return ImportTable == Other.ImportTable && Index == Other.Index;
1217 void ImportDirectoryEntryRef::moveNext() {
1219 if (ImportTable[Index].isNull()) {
1221 ImportTable = nullptr;
1225 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1226 const coff_import_directory_table_entry *&Result) const {
1227 return getObject(Result, OwningObject->Data, ImportTable + Index);
1230 static imported_symbol_iterator
1231 makeImportedSymbolIterator(const COFFObjectFile *Object,
1232 uintptr_t Ptr, int Index) {
1233 if (Object->getBytesInAddress() == 4) {
1234 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1235 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1237 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1238 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1241 static imported_symbol_iterator
1242 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1243 uintptr_t IntPtr = 0;
1244 Object->getRvaPtr(RVA, IntPtr);
1245 return makeImportedSymbolIterator(Object, IntPtr, 0);
1248 static imported_symbol_iterator
1249 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1250 uintptr_t IntPtr = 0;
1251 Object->getRvaPtr(RVA, IntPtr);
1252 // Forward the pointer to the last entry which is null.
1254 if (Object->getBytesInAddress() == 4) {
1255 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1259 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1263 return makeImportedSymbolIterator(Object, IntPtr, Index);
1266 imported_symbol_iterator
1267 ImportDirectoryEntryRef::imported_symbol_begin() const {
1268 return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
1272 imported_symbol_iterator
1273 ImportDirectoryEntryRef::imported_symbol_end() const {
1274 return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
1278 iterator_range<imported_symbol_iterator>
1279 ImportDirectoryEntryRef::imported_symbols() const {
1280 return make_range(imported_symbol_begin(), imported_symbol_end());
1283 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
1284 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1288 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
1289 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1293 iterator_range<imported_symbol_iterator>
1294 ImportDirectoryEntryRef::lookup_table_symbols() const {
1295 return make_range(lookup_table_begin(), lookup_table_end());
1298 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1299 uintptr_t IntPtr = 0;
1300 if (std::error_code EC =
1301 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1303 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1304 return std::error_code();
1308 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1309 Result = ImportTable[Index].ImportLookupTableRVA;
1310 return std::error_code();
1314 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1315 Result = ImportTable[Index].ImportAddressTableRVA;
1316 return std::error_code();
1319 bool DelayImportDirectoryEntryRef::
1320 operator==(const DelayImportDirectoryEntryRef &Other) const {
1321 return Table == Other.Table && Index == Other.Index;
1324 void DelayImportDirectoryEntryRef::moveNext() {
1328 imported_symbol_iterator
1329 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1330 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1334 imported_symbol_iterator
1335 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1336 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1340 iterator_range<imported_symbol_iterator>
1341 DelayImportDirectoryEntryRef::imported_symbols() const {
1342 return make_range(imported_symbol_begin(), imported_symbol_end());
1345 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1346 uintptr_t IntPtr = 0;
1347 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1349 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1350 return std::error_code();
1353 std::error_code DelayImportDirectoryEntryRef::
1354 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1356 return std::error_code();
1359 std::error_code DelayImportDirectoryEntryRef::
1360 getImportAddress(int AddrIndex, uint64_t &Result) const {
1361 uint32_t RVA = Table[Index].DelayImportAddressTable +
1362 AddrIndex * (OwningObject->is64() ? 8 : 4);
1363 uintptr_t IntPtr = 0;
1364 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1366 if (OwningObject->is64())
1367 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1369 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1370 return std::error_code();
1373 bool ExportDirectoryEntryRef::
1374 operator==(const ExportDirectoryEntryRef &Other) const {
1375 return ExportTable == Other.ExportTable && Index == Other.Index;
1378 void ExportDirectoryEntryRef::moveNext() {
1382 // Returns the name of the current export symbol. If the symbol is exported only
1383 // by ordinal, the empty string is set as a result.
1384 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1385 uintptr_t IntPtr = 0;
1386 if (std::error_code EC =
1387 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1389 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1390 return std::error_code();
1393 // Returns the starting ordinal number.
1395 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1396 Result = ExportTable->OrdinalBase;
1397 return std::error_code();
1400 // Returns the export ordinal of the current export symbol.
1401 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1402 Result = ExportTable->OrdinalBase + Index;
1403 return std::error_code();
1406 // Returns the address of the current export symbol.
1407 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1408 uintptr_t IntPtr = 0;
1409 if (std::error_code EC =
1410 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1412 const export_address_table_entry *entry =
1413 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1414 Result = entry[Index].ExportRVA;
1415 return std::error_code();
1418 // Returns the name of the current export symbol. If the symbol is exported only
1419 // by ordinal, the empty string is set as a result.
1421 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1422 uintptr_t IntPtr = 0;
1423 if (std::error_code EC =
1424 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1426 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1428 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1430 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1431 I < E; ++I, ++Offset) {
1434 if (std::error_code EC =
1435 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1437 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1438 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1440 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1441 return std::error_code();
1444 return std::error_code();
1447 std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1448 const data_directory *DataEntry;
1449 if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
1452 if (auto EC = getExportRVA(RVA))
1454 uint32_t Begin = DataEntry->RelativeVirtualAddress;
1455 uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1456 Result = (Begin <= RVA && RVA < End);
1457 return std::error_code();
1460 std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1462 if (auto EC = getExportRVA(RVA))
1464 uintptr_t IntPtr = 0;
1465 if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1467 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1468 return std::error_code();
1471 bool ImportedSymbolRef::
1472 operator==(const ImportedSymbolRef &Other) const {
1473 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1474 && Index == Other.Index;
1477 void ImportedSymbolRef::moveNext() {
1482 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1485 // If a symbol is imported only by ordinal, it has no name.
1486 if (Entry32[Index].isOrdinal())
1487 return std::error_code();
1488 RVA = Entry32[Index].getHintNameRVA();
1490 if (Entry64[Index].isOrdinal())
1491 return std::error_code();
1492 RVA = Entry64[Index].getHintNameRVA();
1494 uintptr_t IntPtr = 0;
1495 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1497 // +2 because the first two bytes is hint.
1498 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1499 return std::error_code();
1502 std::error_code ImportedSymbolRef::isOrdinal(bool &Result) const {
1504 Result = Entry32[Index].isOrdinal();
1506 Result = Entry64[Index].isOrdinal();
1507 return std::error_code();
1510 std::error_code ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
1512 Result = Entry32[Index].getHintNameRVA();
1514 Result = Entry64[Index].getHintNameRVA();
1515 return std::error_code();
1518 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1521 if (Entry32[Index].isOrdinal()) {
1522 Result = Entry32[Index].getOrdinal();
1523 return std::error_code();
1525 RVA = Entry32[Index].getHintNameRVA();
1527 if (Entry64[Index].isOrdinal()) {
1528 Result = Entry64[Index].getOrdinal();
1529 return std::error_code();
1531 RVA = Entry64[Index].getHintNameRVA();
1533 uintptr_t IntPtr = 0;
1534 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1536 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1537 return std::error_code();
1540 ErrorOr<std::unique_ptr<COFFObjectFile>>
1541 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1543 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1546 return std::move(Ret);
1549 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1550 return Header == Other.Header && Index == Other.Index;
1553 void BaseRelocRef::moveNext() {
1554 // Header->BlockSize is the size of the current block, including the
1555 // size of the header itself.
1556 uint32_t Size = sizeof(*Header) +
1557 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1558 if (Size == Header->BlockSize) {
1559 // .reloc contains a list of base relocation blocks. Each block
1560 // consists of the header followed by entries. The header contains
1561 // how many entories will follow. When we reach the end of the
1562 // current block, proceed to the next block.
1563 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1564 reinterpret_cast<const uint8_t *>(Header) + Size);
1571 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1572 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1573 Type = Entry[Index].getType();
1574 return std::error_code();
1577 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1578 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1579 Result = Header->PageRVA + Entry[Index].getOffset();
1580 return std::error_code();