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/BinaryFormat/COFF.h"
19 #include "llvm/Object/Binary.h"
20 #include "llvm/Object/COFF.h"
21 #include "llvm/Object/Error.h"
22 #include "llvm/Object/ObjectFile.h"
23 #include "llvm/Support/BinaryStreamReader.h"
24 #include "llvm/Support/Endian.h"
25 #include "llvm/Support/Error.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/MemoryBuffer.h"
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;
232 // We use indirect to allow the archiver to write weak externs
233 Result |= SymbolRef::SF_Indirect;
236 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
237 Result |= SymbolRef::SF_Absolute;
239 if (Symb.isFileRecord())
240 Result |= SymbolRef::SF_FormatSpecific;
242 if (Symb.isSectionDefinition())
243 Result |= SymbolRef::SF_FormatSpecific;
246 Result |= SymbolRef::SF_Common;
248 if (Symb.isAnyUndefined())
249 Result |= SymbolRef::SF_Undefined;
254 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
255 COFFSymbolRef Symb = getCOFFSymbol(Ref);
256 return Symb.getValue();
259 Expected<section_iterator>
260 COFFObjectFile::getSymbolSection(DataRefImpl Ref) const {
261 COFFSymbolRef Symb = getCOFFSymbol(Ref);
262 if (COFF::isReservedSectionNumber(Symb.getSectionNumber()))
263 return section_end();
264 const coff_section *Sec = nullptr;
265 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
266 return errorCodeToError(EC);
268 Ret.p = reinterpret_cast<uintptr_t>(Sec);
269 return section_iterator(SectionRef(Ret, this));
272 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
273 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
274 return Symb.getSectionNumber();
277 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
278 const coff_section *Sec = toSec(Ref);
280 Ref.p = reinterpret_cast<uintptr_t>(Sec);
283 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
284 StringRef &Result) const {
285 const coff_section *Sec = toSec(Ref);
286 return getSectionName(Sec, Result);
289 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
290 const coff_section *Sec = toSec(Ref);
291 uint64_t Result = Sec->VirtualAddress;
293 // The section VirtualAddress does not include ImageBase, and we want to
294 // return virtual addresses.
295 Result += getImageBase();
299 uint64_t COFFObjectFile::getSectionIndex(DataRefImpl Sec) const {
300 return toSec(Sec) - SectionTable;
303 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
304 return getSectionSize(toSec(Ref));
307 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
308 StringRef &Result) const {
309 const coff_section *Sec = toSec(Ref);
310 ArrayRef<uint8_t> Res;
311 std::error_code EC = getSectionContents(Sec, Res);
312 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
316 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
317 const coff_section *Sec = toSec(Ref);
318 return Sec->getAlignment();
321 bool COFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
325 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
326 const coff_section *Sec = toSec(Ref);
327 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
330 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
331 const coff_section *Sec = toSec(Ref);
332 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
335 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
336 const coff_section *Sec = toSec(Ref);
337 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
338 COFF::IMAGE_SCN_MEM_READ |
339 COFF::IMAGE_SCN_MEM_WRITE;
340 return (Sec->Characteristics & BssFlags) == BssFlags;
343 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
345 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
346 assert((Offset % sizeof(coff_section)) == 0);
347 return (Offset / sizeof(coff_section)) + 1;
350 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
351 const coff_section *Sec = toSec(Ref);
352 // In COFF, a virtual section won't have any in-file
353 // content, so the file pointer to the content will be zero.
354 return Sec->PointerToRawData == 0;
357 static uint32_t getNumberOfRelocations(const coff_section *Sec,
358 MemoryBufferRef M, const uint8_t *base) {
359 // The field for the number of relocations in COFF section table is only
360 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
361 // NumberOfRelocations field, and the actual relocation count is stored in the
362 // VirtualAddress field in the first relocation entry.
363 if (Sec->hasExtendedRelocations()) {
364 const coff_relocation *FirstReloc;
365 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
366 base + Sec->PointerToRelocations)))
368 // -1 to exclude this first relocation entry.
369 return FirstReloc->VirtualAddress - 1;
371 return Sec->NumberOfRelocations;
374 static const coff_relocation *
375 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
376 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
379 auto begin = reinterpret_cast<const coff_relocation *>(
380 Base + Sec->PointerToRelocations);
381 if (Sec->hasExtendedRelocations()) {
382 // Skip the first relocation entry repurposed to store the number of
386 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
391 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
392 const coff_section *Sec = toSec(Ref);
393 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
394 if (begin && Sec->VirtualAddress != 0)
395 report_fatal_error("Sections with relocations should have an address of 0");
397 Ret.p = reinterpret_cast<uintptr_t>(begin);
398 return relocation_iterator(RelocationRef(Ret, this));
401 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
402 const coff_section *Sec = toSec(Ref);
403 const coff_relocation *I = getFirstReloc(Sec, Data, base());
405 I += getNumberOfRelocations(Sec, Data, base());
407 Ret.p = reinterpret_cast<uintptr_t>(I);
408 return relocation_iterator(RelocationRef(Ret, this));
411 // Initialize the pointer to the symbol table.
412 std::error_code COFFObjectFile::initSymbolTablePtr() {
414 if (std::error_code EC = getObject(
415 SymbolTable16, Data, base() + getPointerToSymbolTable(),
416 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
419 if (COFFBigObjHeader)
420 if (std::error_code EC = getObject(
421 SymbolTable32, Data, base() + getPointerToSymbolTable(),
422 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
425 // Find string table. The first four byte of the string table contains the
426 // total size of the string table, including the size field itself. If the
427 // string table is empty, the value of the first four byte would be 4.
428 uint32_t StringTableOffset = getPointerToSymbolTable() +
429 getNumberOfSymbols() * getSymbolTableEntrySize();
430 const uint8_t *StringTableAddr = base() + StringTableOffset;
431 const ulittle32_t *StringTableSizePtr;
432 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
434 StringTableSize = *StringTableSizePtr;
435 if (std::error_code EC =
436 getObject(StringTable, Data, StringTableAddr, StringTableSize))
439 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
440 // tools like cvtres write a size of 0 for an empty table instead of 4.
441 if (StringTableSize < 4)
444 // Check that the string table is null terminated if has any in it.
445 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
446 return object_error::parse_failed;
447 return std::error_code();
450 uint64_t COFFObjectFile::getImageBase() const {
452 return PE32Header->ImageBase;
453 else if (PE32PlusHeader)
454 return PE32PlusHeader->ImageBase;
455 // This actually comes up in practice.
459 // Returns the file offset for the given VA.
460 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
461 uint64_t ImageBase = getImageBase();
462 uint64_t Rva = Addr - ImageBase;
463 assert(Rva <= UINT32_MAX);
464 return getRvaPtr((uint32_t)Rva, Res);
467 // Returns the file offset for the given RVA.
468 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
469 for (const SectionRef &S : sections()) {
470 const coff_section *Section = getCOFFSection(S);
471 uint32_t SectionStart = Section->VirtualAddress;
472 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
473 if (SectionStart <= Addr && Addr < SectionEnd) {
474 uint32_t Offset = Addr - SectionStart;
475 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
476 return std::error_code();
479 return object_error::parse_failed;
483 COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
484 ArrayRef<uint8_t> &Contents) const {
485 for (const SectionRef &S : sections()) {
486 const coff_section *Section = getCOFFSection(S);
487 uint32_t SectionStart = Section->VirtualAddress;
488 // Check if this RVA is within the section bounds. Be careful about integer
490 uint32_t OffsetIntoSection = RVA - SectionStart;
491 if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize &&
492 Size <= Section->VirtualSize - OffsetIntoSection) {
494 uintptr_t(base()) + Section->PointerToRawData + OffsetIntoSection;
496 ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size);
497 return std::error_code();
500 return object_error::parse_failed;
503 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
505 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
506 StringRef &Name) const {
507 uintptr_t IntPtr = 0;
508 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
510 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
511 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
512 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
513 return std::error_code();
517 COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir,
518 const codeview::DebugInfo *&PDBInfo,
519 StringRef &PDBFileName) const {
520 ArrayRef<uint8_t> InfoBytes;
521 if (std::error_code EC = getRvaAndSizeAsBytes(
522 DebugDir->AddressOfRawData, DebugDir->SizeOfData, InfoBytes))
524 if (InfoBytes.size() < sizeof(*PDBInfo) + 1)
525 return object_error::parse_failed;
526 PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data());
527 InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo));
528 PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()),
530 // Truncate the name at the first null byte. Ignore any padding.
531 PDBFileName = PDBFileName.split('\0').first;
532 return std::error_code();
536 COFFObjectFile::getDebugPDBInfo(const codeview::DebugInfo *&PDBInfo,
537 StringRef &PDBFileName) const {
538 for (const debug_directory &D : debug_directories())
539 if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW)
540 return getDebugPDBInfo(&D, PDBInfo, PDBFileName);
541 // If we get here, there is no PDB info to return.
543 PDBFileName = StringRef();
544 return std::error_code();
547 // Find the import table.
548 std::error_code COFFObjectFile::initImportTablePtr() {
549 // First, we get the RVA of the import table. If the file lacks a pointer to
550 // the import table, do nothing.
551 const data_directory *DataEntry;
552 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
553 return std::error_code();
555 // Do nothing if the pointer to import table is NULL.
556 if (DataEntry->RelativeVirtualAddress == 0)
557 return std::error_code();
559 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
561 // Find the section that contains the RVA. This is needed because the RVA is
562 // the import table's memory address which is different from its file offset.
563 uintptr_t IntPtr = 0;
564 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
566 if (std::error_code EC = checkOffset(Data, IntPtr, DataEntry->Size))
568 ImportDirectory = reinterpret_cast<
569 const coff_import_directory_table_entry *>(IntPtr);
570 return std::error_code();
573 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
574 std::error_code COFFObjectFile::initDelayImportTablePtr() {
575 const data_directory *DataEntry;
576 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
577 return std::error_code();
578 if (DataEntry->RelativeVirtualAddress == 0)
579 return std::error_code();
581 uint32_t RVA = DataEntry->RelativeVirtualAddress;
582 NumberOfDelayImportDirectory = DataEntry->Size /
583 sizeof(delay_import_directory_table_entry) - 1;
585 uintptr_t IntPtr = 0;
586 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
588 DelayImportDirectory = reinterpret_cast<
589 const delay_import_directory_table_entry *>(IntPtr);
590 return std::error_code();
593 // Find the export table.
594 std::error_code COFFObjectFile::initExportTablePtr() {
595 // First, we get the RVA of the export table. If the file lacks a pointer to
596 // the export table, do nothing.
597 const data_directory *DataEntry;
598 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
599 return std::error_code();
601 // Do nothing if the pointer to export table is NULL.
602 if (DataEntry->RelativeVirtualAddress == 0)
603 return std::error_code();
605 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
606 uintptr_t IntPtr = 0;
607 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
610 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
611 return std::error_code();
614 std::error_code COFFObjectFile::initBaseRelocPtr() {
615 const data_directory *DataEntry;
616 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
617 return std::error_code();
618 if (DataEntry->RelativeVirtualAddress == 0)
619 return std::error_code();
621 uintptr_t IntPtr = 0;
622 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
624 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
626 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
627 IntPtr + DataEntry->Size);
628 return std::error_code();
631 std::error_code COFFObjectFile::initDebugDirectoryPtr() {
632 // Get the RVA of the debug directory. Do nothing if it does not exist.
633 const data_directory *DataEntry;
634 if (getDataDirectory(COFF::DEBUG_DIRECTORY, DataEntry))
635 return std::error_code();
637 // Do nothing if the RVA is NULL.
638 if (DataEntry->RelativeVirtualAddress == 0)
639 return std::error_code();
641 // Check that the size is a multiple of the entry size.
642 if (DataEntry->Size % sizeof(debug_directory) != 0)
643 return object_error::parse_failed;
645 uintptr_t IntPtr = 0;
646 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
648 DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
649 if (std::error_code EC = getRvaPtr(
650 DataEntry->RelativeVirtualAddress + DataEntry->Size, IntPtr))
652 DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(IntPtr);
653 return std::error_code();
656 std::error_code COFFObjectFile::initLoadConfigPtr() {
657 // Get the RVA of the debug directory. Do nothing if it does not exist.
658 const data_directory *DataEntry;
659 if (getDataDirectory(COFF::LOAD_CONFIG_TABLE, DataEntry))
660 return std::error_code();
662 // Do nothing if the RVA is NULL.
663 if (DataEntry->RelativeVirtualAddress == 0)
664 return std::error_code();
665 uintptr_t IntPtr = 0;
666 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
669 LoadConfig = (const void *)IntPtr;
670 return std::error_code();
673 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
674 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
675 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
676 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
677 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
678 ImportDirectory(nullptr),
679 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
680 ExportDirectory(nullptr), BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
681 DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr) {
682 // Check that we at least have enough room for a header.
683 if (!checkSize(Data, EC, sizeof(coff_file_header)))
686 // The current location in the file where we are looking at.
689 // PE header is optional and is present only in executables. If it exists,
690 // it is placed right after COFF header.
691 bool HasPEHeader = false;
693 // Check if this is a PE/COFF file.
694 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
695 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
696 // PE signature to find 'normal' COFF header.
697 const auto *DH = reinterpret_cast<const dos_header *>(base());
698 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
699 CurPtr = DH->AddressOfNewExeHeader;
700 // Check the PE magic bytes. ("PE\0\0")
701 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
702 EC = object_error::parse_failed;
705 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
710 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
713 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
714 // import libraries share a common prefix but bigobj is more restrictive.
715 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
716 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
717 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
718 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
721 // Verify that we are dealing with bigobj.
722 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
723 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
724 sizeof(COFF::BigObjMagic)) == 0) {
725 COFFHeader = nullptr;
726 CurPtr += sizeof(coff_bigobj_file_header);
728 // It's not a bigobj.
729 COFFBigObjHeader = nullptr;
733 // The prior checkSize call may have failed. This isn't a hard error
734 // because we were just trying to sniff out bigobj.
735 EC = std::error_code();
736 CurPtr += sizeof(coff_file_header);
738 if (COFFHeader->isImportLibrary())
743 const pe32_header *Header;
744 if ((EC = getObject(Header, Data, base() + CurPtr)))
747 const uint8_t *DataDirAddr;
748 uint64_t DataDirSize;
749 if (Header->Magic == COFF::PE32Header::PE32) {
751 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
752 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
753 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
754 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
755 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
756 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
758 // It's neither PE32 nor PE32+.
759 EC = object_error::parse_failed;
762 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
767 CurPtr += COFFHeader->SizeOfOptionalHeader;
769 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
770 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
773 // Initialize the pointer to the symbol table.
774 if (getPointerToSymbolTable() != 0) {
775 if ((EC = initSymbolTablePtr())) {
776 SymbolTable16 = nullptr;
777 SymbolTable32 = nullptr;
778 StringTable = nullptr;
782 // We had better not have any symbols if we don't have a symbol table.
783 if (getNumberOfSymbols() != 0) {
784 EC = object_error::parse_failed;
789 // Initialize the pointer to the beginning of the import table.
790 if ((EC = initImportTablePtr()))
792 if ((EC = initDelayImportTablePtr()))
795 // Initialize the pointer to the export table.
796 if ((EC = initExportTablePtr()))
799 // Initialize the pointer to the base relocation table.
800 if ((EC = initBaseRelocPtr()))
803 // Initialize the pointer to the export table.
804 if ((EC = initDebugDirectoryPtr()))
807 if ((EC = initLoadConfigPtr()))
810 EC = std::error_code();
813 basic_symbol_iterator COFFObjectFile::symbol_begin() const {
815 Ret.p = getSymbolTable();
816 return basic_symbol_iterator(SymbolRef(Ret, this));
819 basic_symbol_iterator COFFObjectFile::symbol_end() const {
820 // The symbol table ends where the string table begins.
822 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
823 return basic_symbol_iterator(SymbolRef(Ret, this));
826 import_directory_iterator COFFObjectFile::import_directory_begin() const {
827 if (!ImportDirectory)
828 return import_directory_end();
829 if (ImportDirectory->isNull())
830 return import_directory_end();
831 return import_directory_iterator(
832 ImportDirectoryEntryRef(ImportDirectory, 0, this));
835 import_directory_iterator COFFObjectFile::import_directory_end() const {
836 return import_directory_iterator(
837 ImportDirectoryEntryRef(nullptr, -1, this));
840 delay_import_directory_iterator
841 COFFObjectFile::delay_import_directory_begin() const {
842 return delay_import_directory_iterator(
843 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
846 delay_import_directory_iterator
847 COFFObjectFile::delay_import_directory_end() const {
848 return delay_import_directory_iterator(
849 DelayImportDirectoryEntryRef(
850 DelayImportDirectory, NumberOfDelayImportDirectory, this));
853 export_directory_iterator COFFObjectFile::export_directory_begin() const {
854 return export_directory_iterator(
855 ExportDirectoryEntryRef(ExportDirectory, 0, this));
858 export_directory_iterator COFFObjectFile::export_directory_end() const {
859 if (!ExportDirectory)
860 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
861 ExportDirectoryEntryRef Ref(ExportDirectory,
862 ExportDirectory->AddressTableEntries, this);
863 return export_directory_iterator(Ref);
866 section_iterator COFFObjectFile::section_begin() const {
868 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
869 return section_iterator(SectionRef(Ret, this));
872 section_iterator COFFObjectFile::section_end() const {
875 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
876 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
877 return section_iterator(SectionRef(Ret, this));
880 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
881 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
884 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
885 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
888 uint8_t COFFObjectFile::getBytesInAddress() const {
889 return getArch() == Triple::x86_64 || getArch() == Triple::aarch64 ? 8 : 4;
892 StringRef COFFObjectFile::getFileFormatName() const {
893 switch(getMachine()) {
894 case COFF::IMAGE_FILE_MACHINE_I386:
896 case COFF::IMAGE_FILE_MACHINE_AMD64:
897 return "COFF-x86-64";
898 case COFF::IMAGE_FILE_MACHINE_ARMNT:
900 case COFF::IMAGE_FILE_MACHINE_ARM64:
903 return "COFF-<unknown arch>";
907 unsigned COFFObjectFile::getArch() const {
908 switch (getMachine()) {
909 case COFF::IMAGE_FILE_MACHINE_I386:
911 case COFF::IMAGE_FILE_MACHINE_AMD64:
912 return Triple::x86_64;
913 case COFF::IMAGE_FILE_MACHINE_ARMNT:
914 return Triple::thumb;
915 case COFF::IMAGE_FILE_MACHINE_ARM64:
916 return Triple::aarch64;
918 return Triple::UnknownArch;
922 iterator_range<import_directory_iterator>
923 COFFObjectFile::import_directories() const {
924 return make_range(import_directory_begin(), import_directory_end());
927 iterator_range<delay_import_directory_iterator>
928 COFFObjectFile::delay_import_directories() const {
929 return make_range(delay_import_directory_begin(),
930 delay_import_directory_end());
933 iterator_range<export_directory_iterator>
934 COFFObjectFile::export_directories() const {
935 return make_range(export_directory_begin(), export_directory_end());
938 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
939 return make_range(base_reloc_begin(), base_reloc_end());
942 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
944 return std::error_code();
948 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
949 Res = PE32PlusHeader;
950 return std::error_code();
954 COFFObjectFile::getDataDirectory(uint32_t Index,
955 const data_directory *&Res) const {
956 // Error if if there's no data directory or the index is out of range.
957 if (!DataDirectory) {
959 return object_error::parse_failed;
961 assert(PE32Header || PE32PlusHeader);
962 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
963 : PE32PlusHeader->NumberOfRvaAndSize;
964 if (Index >= NumEnt) {
966 return object_error::parse_failed;
968 Res = &DataDirectory[Index];
969 return std::error_code();
972 std::error_code COFFObjectFile::getSection(int32_t Index,
973 const coff_section *&Result) const {
975 if (COFF::isReservedSectionNumber(Index))
976 return std::error_code();
977 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
978 // We already verified the section table data, so no need to check again.
979 Result = SectionTable + (Index - 1);
980 return std::error_code();
982 return object_error::parse_failed;
985 std::error_code COFFObjectFile::getString(uint32_t Offset,
986 StringRef &Result) const {
987 if (StringTableSize <= 4)
988 // Tried to get a string from an empty string table.
989 return object_error::parse_failed;
990 if (Offset >= StringTableSize)
991 return object_error::unexpected_eof;
992 Result = StringRef(StringTable + Offset);
993 return std::error_code();
996 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
997 StringRef &Res) const {
998 return getSymbolName(Symbol.getGeneric(), Res);
1001 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
1002 StringRef &Res) const {
1003 // Check for string table entry. First 4 bytes are 0.
1004 if (Symbol->Name.Offset.Zeroes == 0) {
1005 if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
1007 return std::error_code();
1010 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
1011 // Null terminated, let ::strlen figure out the length.
1012 Res = StringRef(Symbol->Name.ShortName);
1014 // Not null terminated, use all 8 bytes.
1015 Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
1016 return std::error_code();
1020 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
1021 const uint8_t *Aux = nullptr;
1023 size_t SymbolSize = getSymbolTableEntrySize();
1024 if (Symbol.getNumberOfAuxSymbols() > 0) {
1025 // AUX data comes immediately after the symbol in COFF
1026 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
1028 // Verify that the Aux symbol points to a valid entry in the symbol table.
1029 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
1030 if (Offset < getPointerToSymbolTable() ||
1032 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
1033 report_fatal_error("Aux Symbol data was outside of symbol table.");
1035 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
1036 "Aux Symbol data did not point to the beginning of a symbol");
1039 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
1042 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
1043 StringRef &Res) const {
1045 if (Sec->Name[COFF::NameSize - 1] == 0)
1046 // Null terminated, let ::strlen figure out the length.
1049 // Not null terminated, use all 8 bytes.
1050 Name = StringRef(Sec->Name, COFF::NameSize);
1052 // Check for string table entry. First byte is '/'.
1053 if (Name.startswith("/")) {
1055 if (Name.startswith("//")) {
1056 if (decodeBase64StringEntry(Name.substr(2), Offset))
1057 return object_error::parse_failed;
1059 if (Name.substr(1).getAsInteger(10, Offset))
1060 return object_error::parse_failed;
1062 if (std::error_code EC = getString(Offset, Name))
1067 return std::error_code();
1070 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
1071 // SizeOfRawData and VirtualSize change what they represent depending on
1072 // whether or not we have an executable image.
1074 // For object files, SizeOfRawData contains the size of section's data;
1075 // VirtualSize should be zero but isn't due to buggy COFF writers.
1077 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1078 // actual section size is in VirtualSize. It is possible for VirtualSize to
1079 // be greater than SizeOfRawData; the contents past that point should be
1080 // considered to be zero.
1082 return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1083 return Sec->SizeOfRawData;
1087 COFFObjectFile::getSectionContents(const coff_section *Sec,
1088 ArrayRef<uint8_t> &Res) const {
1089 // In COFF, a virtual section won't have any in-file
1090 // content, so the file pointer to the content will be zero.
1091 if (Sec->PointerToRawData == 0)
1092 return std::error_code();
1093 // The only thing that we need to verify is that the contents is contained
1094 // within the file bounds. We don't need to make sure it doesn't cover other
1095 // data, as there's nothing that says that is not allowed.
1096 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1097 uint32_t SectionSize = getSectionSize(Sec);
1098 if (checkOffset(Data, ConStart, SectionSize))
1099 return object_error::parse_failed;
1100 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1101 return std::error_code();
1104 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1105 return reinterpret_cast<const coff_relocation*>(Rel.p);
1108 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1109 Rel.p = reinterpret_cast<uintptr_t>(
1110 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1113 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1114 const coff_relocation *R = toRel(Rel);
1115 return R->VirtualAddress;
1118 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1119 const coff_relocation *R = toRel(Rel);
1121 if (R->SymbolTableIndex >= getNumberOfSymbols())
1122 return symbol_end();
1124 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1125 else if (SymbolTable32)
1126 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1128 llvm_unreachable("no symbol table pointer!");
1129 return symbol_iterator(SymbolRef(Ref, this));
1132 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
1133 const coff_relocation* R = toRel(Rel);
1137 const coff_section *
1138 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1139 return toSec(Section.getRawDataRefImpl());
1142 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1144 return toSymb<coff_symbol16>(Ref);
1146 return toSymb<coff_symbol32>(Ref);
1147 llvm_unreachable("no symbol table pointer!");
1150 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1151 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1154 const coff_relocation *
1155 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1156 return toRel(Reloc.getRawDataRefImpl());
1159 iterator_range<const coff_relocation *>
1160 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1161 const coff_relocation *I = getFirstReloc(Sec, Data, base());
1162 const coff_relocation *E = I;
1164 E += getNumberOfRelocations(Sec, Data, base());
1165 return make_range(I, E);
1168 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1169 case COFF::reloc_type: \
1170 Res = #reloc_type; \
1173 void COFFObjectFile::getRelocationTypeName(
1174 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1175 const coff_relocation *Reloc = toRel(Rel);
1177 switch (getMachine()) {
1178 case COFF::IMAGE_FILE_MACHINE_AMD64:
1179 switch (Reloc->Type) {
1180 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1181 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1182 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1183 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1184 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1185 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1186 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1187 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1188 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1189 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1190 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1191 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1192 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1193 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1194 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1195 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1196 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1201 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1202 switch (Reloc->Type) {
1203 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1204 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1205 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1206 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1207 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1208 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1209 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1210 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1211 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1212 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1213 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1214 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1215 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1216 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1217 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1222 case COFF::IMAGE_FILE_MACHINE_ARM64:
1223 switch (Reloc->Type) {
1224 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ABSOLUTE);
1225 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32);
1226 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32NB);
1227 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH26);
1228 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEBASE_REL21);
1229 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL21);
1230 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12A);
1231 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12L);
1232 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL);
1233 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12A);
1234 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_HIGH12A);
1235 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12L);
1236 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_TOKEN);
1237 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECTION);
1238 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR64);
1239 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH19);
1240 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH14);
1245 case COFF::IMAGE_FILE_MACHINE_I386:
1246 switch (Reloc->Type) {
1247 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1248 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1249 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1250 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1251 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1252 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1253 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1254 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1255 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1256 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1257 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1265 Result.append(Res.begin(), Res.end());
1268 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1270 bool COFFObjectFile::isRelocatableObject() const {
1271 return !DataDirectory;
1274 bool ImportDirectoryEntryRef::
1275 operator==(const ImportDirectoryEntryRef &Other) const {
1276 return ImportTable == Other.ImportTable && Index == Other.Index;
1279 void ImportDirectoryEntryRef::moveNext() {
1281 if (ImportTable[Index].isNull()) {
1283 ImportTable = nullptr;
1287 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1288 const coff_import_directory_table_entry *&Result) const {
1289 return getObject(Result, OwningObject->Data, ImportTable + Index);
1292 static imported_symbol_iterator
1293 makeImportedSymbolIterator(const COFFObjectFile *Object,
1294 uintptr_t Ptr, int Index) {
1295 if (Object->getBytesInAddress() == 4) {
1296 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1297 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1299 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1300 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1303 static imported_symbol_iterator
1304 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1305 uintptr_t IntPtr = 0;
1306 Object->getRvaPtr(RVA, IntPtr);
1307 return makeImportedSymbolIterator(Object, IntPtr, 0);
1310 static imported_symbol_iterator
1311 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1312 uintptr_t IntPtr = 0;
1313 Object->getRvaPtr(RVA, IntPtr);
1314 // Forward the pointer to the last entry which is null.
1316 if (Object->getBytesInAddress() == 4) {
1317 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1321 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1325 return makeImportedSymbolIterator(Object, IntPtr, Index);
1328 imported_symbol_iterator
1329 ImportDirectoryEntryRef::imported_symbol_begin() const {
1330 return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
1334 imported_symbol_iterator
1335 ImportDirectoryEntryRef::imported_symbol_end() const {
1336 return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
1340 iterator_range<imported_symbol_iterator>
1341 ImportDirectoryEntryRef::imported_symbols() const {
1342 return make_range(imported_symbol_begin(), imported_symbol_end());
1345 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
1346 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1350 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
1351 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1355 iterator_range<imported_symbol_iterator>
1356 ImportDirectoryEntryRef::lookup_table_symbols() const {
1357 return make_range(lookup_table_begin(), lookup_table_end());
1360 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1361 uintptr_t IntPtr = 0;
1362 if (std::error_code EC =
1363 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1365 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1366 return std::error_code();
1370 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1371 Result = ImportTable[Index].ImportLookupTableRVA;
1372 return std::error_code();
1376 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1377 Result = ImportTable[Index].ImportAddressTableRVA;
1378 return std::error_code();
1381 bool DelayImportDirectoryEntryRef::
1382 operator==(const DelayImportDirectoryEntryRef &Other) const {
1383 return Table == Other.Table && Index == Other.Index;
1386 void DelayImportDirectoryEntryRef::moveNext() {
1390 imported_symbol_iterator
1391 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1392 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1396 imported_symbol_iterator
1397 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1398 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1402 iterator_range<imported_symbol_iterator>
1403 DelayImportDirectoryEntryRef::imported_symbols() const {
1404 return make_range(imported_symbol_begin(), imported_symbol_end());
1407 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1408 uintptr_t IntPtr = 0;
1409 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1411 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1412 return std::error_code();
1415 std::error_code DelayImportDirectoryEntryRef::
1416 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1418 return std::error_code();
1421 std::error_code DelayImportDirectoryEntryRef::
1422 getImportAddress(int AddrIndex, uint64_t &Result) const {
1423 uint32_t RVA = Table[Index].DelayImportAddressTable +
1424 AddrIndex * (OwningObject->is64() ? 8 : 4);
1425 uintptr_t IntPtr = 0;
1426 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1428 if (OwningObject->is64())
1429 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1431 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1432 return std::error_code();
1435 bool ExportDirectoryEntryRef::
1436 operator==(const ExportDirectoryEntryRef &Other) const {
1437 return ExportTable == Other.ExportTable && Index == Other.Index;
1440 void ExportDirectoryEntryRef::moveNext() {
1444 // Returns the name of the current export symbol. If the symbol is exported only
1445 // by ordinal, the empty string is set as a result.
1446 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1447 uintptr_t IntPtr = 0;
1448 if (std::error_code EC =
1449 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1451 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1452 return std::error_code();
1455 // Returns the starting ordinal number.
1457 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1458 Result = ExportTable->OrdinalBase;
1459 return std::error_code();
1462 // Returns the export ordinal of the current export symbol.
1463 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1464 Result = ExportTable->OrdinalBase + Index;
1465 return std::error_code();
1468 // Returns the address of the current export symbol.
1469 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1470 uintptr_t IntPtr = 0;
1471 if (std::error_code EC =
1472 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1474 const export_address_table_entry *entry =
1475 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1476 Result = entry[Index].ExportRVA;
1477 return std::error_code();
1480 // Returns the name of the current export symbol. If the symbol is exported only
1481 // by ordinal, the empty string is set as a result.
1483 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1484 uintptr_t IntPtr = 0;
1485 if (std::error_code EC =
1486 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1488 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1490 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1492 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1493 I < E; ++I, ++Offset) {
1496 if (std::error_code EC =
1497 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1499 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1500 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1502 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1503 return std::error_code();
1506 return std::error_code();
1509 std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1510 const data_directory *DataEntry;
1511 if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
1514 if (auto EC = getExportRVA(RVA))
1516 uint32_t Begin = DataEntry->RelativeVirtualAddress;
1517 uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1518 Result = (Begin <= RVA && RVA < End);
1519 return std::error_code();
1522 std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1524 if (auto EC = getExportRVA(RVA))
1526 uintptr_t IntPtr = 0;
1527 if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1529 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1530 return std::error_code();
1533 bool ImportedSymbolRef::
1534 operator==(const ImportedSymbolRef &Other) const {
1535 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1536 && Index == Other.Index;
1539 void ImportedSymbolRef::moveNext() {
1544 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1547 // If a symbol is imported only by ordinal, it has no name.
1548 if (Entry32[Index].isOrdinal())
1549 return std::error_code();
1550 RVA = Entry32[Index].getHintNameRVA();
1552 if (Entry64[Index].isOrdinal())
1553 return std::error_code();
1554 RVA = Entry64[Index].getHintNameRVA();
1556 uintptr_t IntPtr = 0;
1557 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1559 // +2 because the first two bytes is hint.
1560 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1561 return std::error_code();
1564 std::error_code ImportedSymbolRef::isOrdinal(bool &Result) const {
1566 Result = Entry32[Index].isOrdinal();
1568 Result = Entry64[Index].isOrdinal();
1569 return std::error_code();
1572 std::error_code ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
1574 Result = Entry32[Index].getHintNameRVA();
1576 Result = Entry64[Index].getHintNameRVA();
1577 return std::error_code();
1580 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1583 if (Entry32[Index].isOrdinal()) {
1584 Result = Entry32[Index].getOrdinal();
1585 return std::error_code();
1587 RVA = Entry32[Index].getHintNameRVA();
1589 if (Entry64[Index].isOrdinal()) {
1590 Result = Entry64[Index].getOrdinal();
1591 return std::error_code();
1593 RVA = Entry64[Index].getHintNameRVA();
1595 uintptr_t IntPtr = 0;
1596 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1598 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1599 return std::error_code();
1602 ErrorOr<std::unique_ptr<COFFObjectFile>>
1603 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1605 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1608 return std::move(Ret);
1611 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1612 return Header == Other.Header && Index == Other.Index;
1615 void BaseRelocRef::moveNext() {
1616 // Header->BlockSize is the size of the current block, including the
1617 // size of the header itself.
1618 uint32_t Size = sizeof(*Header) +
1619 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1620 if (Size == Header->BlockSize) {
1621 // .reloc contains a list of base relocation blocks. Each block
1622 // consists of the header followed by entries. The header contains
1623 // how many entories will follow. When we reach the end of the
1624 // current block, proceed to the next block.
1625 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1626 reinterpret_cast<const uint8_t *>(Header) + Size);
1633 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1634 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1635 Type = Entry[Index].getType();
1636 return std::error_code();
1639 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1640 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1641 Result = Header->PageRVA + Entry[Index].getOffset();
1642 return std::error_code();
1645 #define RETURN_IF_ERROR(X) \
1646 if (auto EC = errorToErrorCode(X)) \
1649 ErrorOr<ArrayRef<UTF16>> ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) {
1650 BinaryStreamReader Reader = BinaryStreamReader(BBS);
1651 Reader.setOffset(Offset);
1653 RETURN_IF_ERROR(Reader.readInteger(Length));
1654 ArrayRef<UTF16> RawDirString;
1655 RETURN_IF_ERROR(Reader.readArray(RawDirString, Length));
1656 return RawDirString;
1659 ErrorOr<ArrayRef<UTF16>>
1660 ResourceSectionRef::getEntryNameString(const coff_resource_dir_entry &Entry) {
1661 return getDirStringAtOffset(Entry.Identifier.getNameOffset());
1664 ErrorOr<const coff_resource_dir_table &>
1665 ResourceSectionRef::getTableAtOffset(uint32_t Offset) {
1666 const coff_resource_dir_table *Table = nullptr;
1668 BinaryStreamReader Reader(BBS);
1669 Reader.setOffset(Offset);
1670 RETURN_IF_ERROR(Reader.readObject(Table));
1671 assert(Table != nullptr);
1675 ErrorOr<const coff_resource_dir_table &>
1676 ResourceSectionRef::getEntrySubDir(const coff_resource_dir_entry &Entry) {
1677 return getTableAtOffset(Entry.Offset.value());
1680 ErrorOr<const coff_resource_dir_table &> ResourceSectionRef::getBaseTable() {
1681 return getTableAtOffset(0);