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/SmallString.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/Support/COFF.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
27 using namespace object;
29 using support::ulittle16_t;
30 using support::ulittle32_t;
31 using support::ulittle64_t;
32 using support::little16_t;
34 // Returns false if size is greater than the buffer size. And sets ec.
35 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
36 if (M.getBufferSize() < Size) {
37 EC = object_error::unexpected_eof;
43 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
44 const uint64_t Size) {
45 if (Addr + Size < Addr || Addr + Size < Size ||
46 Addr + Size > uintptr_t(M.getBufferEnd()) ||
47 Addr < uintptr_t(M.getBufferStart())) {
48 return object_error::unexpected_eof;
50 return std::error_code();
53 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
54 // Returns unexpected_eof if error.
56 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
58 const uint64_t Size = sizeof(T)) {
59 uintptr_t Addr = uintptr_t(Ptr);
60 if (std::error_code EC = checkOffset(M, Addr, Size))
62 Obj = reinterpret_cast<const T *>(Addr);
63 return std::error_code();
66 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
68 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
69 assert(Str.size() <= 6 && "String too long, possible overflow.");
74 while (!Str.empty()) {
76 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
77 CharVal = Str[0] - 'A';
78 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
79 CharVal = Str[0] - 'a' + 26;
80 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
81 CharVal = Str[0] - '0' + 52;
82 else if (Str[0] == '+') // 62
84 else if (Str[0] == '/') // 63
89 Value = (Value * 64) + CharVal;
93 if (Value > std::numeric_limits<uint32_t>::max())
96 Result = static_cast<uint32_t>(Value);
100 template <typename coff_symbol_type>
101 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
102 const coff_symbol_type *Addr =
103 reinterpret_cast<const coff_symbol_type *>(Ref.p);
105 assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
107 // Verify that the symbol points to a valid entry in the symbol table.
108 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
110 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
111 "Symbol did not point to the beginning of a symbol");
117 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
118 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
121 // Verify that the section points to a valid entry in the section table.
122 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
123 report_fatal_error("Section was outside of section table.");
125 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
126 assert(Offset % sizeof(coff_section) == 0 &&
127 "Section did not point to the beginning of a section");
133 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
134 auto End = reinterpret_cast<uintptr_t>(StringTable);
136 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
137 Symb += 1 + Symb->NumberOfAuxSymbols;
138 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
139 } else if (SymbolTable32) {
140 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
141 Symb += 1 + Symb->NumberOfAuxSymbols;
142 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
144 llvm_unreachable("no symbol table pointer!");
148 ErrorOr<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
149 COFFSymbolRef Symb = getCOFFSymbol(Ref);
151 std::error_code EC = getSymbolName(Symb, Result);
157 uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const {
158 return getCOFFSymbol(Ref).getValue();
161 ErrorOr<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
162 uint64_t Result = getSymbolValue(Ref);
163 COFFSymbolRef Symb = getCOFFSymbol(Ref);
164 int32_t SectionNumber = Symb.getSectionNumber();
166 if (Symb.isAnyUndefined() || Symb.isCommon() ||
167 COFF::isReservedSectionNumber(SectionNumber))
170 const coff_section *Section = nullptr;
171 if (std::error_code EC = getSection(SectionNumber, Section))
173 Result += Section->VirtualAddress;
175 // The section VirtualAddress does not include ImageBase, and we want to
176 // return virtual addresses.
177 Result += getImageBase().get();
182 SymbolRef::Type COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
183 COFFSymbolRef Symb = getCOFFSymbol(Ref);
184 int32_t SectionNumber = Symb.getSectionNumber();
186 if (Symb.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION)
187 return SymbolRef::ST_Function;
188 if (Symb.isAnyUndefined())
189 return SymbolRef::ST_Unknown;
191 return SymbolRef::ST_Data;
192 if (Symb.isFileRecord())
193 return SymbolRef::ST_File;
195 // TODO: perhaps we need a new symbol type ST_Section.
196 if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
197 return SymbolRef::ST_Debug;
199 if (!COFF::isReservedSectionNumber(SectionNumber))
200 return SymbolRef::ST_Data;
202 return SymbolRef::ST_Other;
205 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
206 COFFSymbolRef Symb = getCOFFSymbol(Ref);
207 uint32_t Result = SymbolRef::SF_None;
209 if (Symb.isExternal() || Symb.isWeakExternal())
210 Result |= SymbolRef::SF_Global;
212 if (Symb.isWeakExternal())
213 Result |= SymbolRef::SF_Weak;
215 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
216 Result |= SymbolRef::SF_Absolute;
218 if (Symb.isFileRecord())
219 Result |= SymbolRef::SF_FormatSpecific;
221 if (Symb.isSectionDefinition())
222 Result |= SymbolRef::SF_FormatSpecific;
225 Result |= SymbolRef::SF_Common;
227 if (Symb.isAnyUndefined())
228 Result |= SymbolRef::SF_Undefined;
233 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
234 COFFSymbolRef Symb = getCOFFSymbol(Ref);
235 return Symb.getValue();
238 ErrorOr<section_iterator>
239 COFFObjectFile::getSymbolSection(DataRefImpl Ref) const {
240 COFFSymbolRef Symb = getCOFFSymbol(Ref);
241 if (COFF::isReservedSectionNumber(Symb.getSectionNumber()))
242 return section_end();
243 const coff_section *Sec = nullptr;
244 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
247 Ret.p = reinterpret_cast<uintptr_t>(Sec);
248 return section_iterator(SectionRef(Ret, this));
251 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
252 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
253 return Symb.getSectionNumber();
256 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
257 const coff_section *Sec = toSec(Ref);
259 Ref.p = reinterpret_cast<uintptr_t>(Sec);
262 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
263 StringRef &Result) const {
264 const coff_section *Sec = toSec(Ref);
265 return getSectionName(Sec, Result);
268 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
269 const coff_section *Sec = toSec(Ref);
270 uint64_t Result = Sec->VirtualAddress;
272 // The section VirtualAddress does not include ImageBase, and we want to
273 // return virtual addresses.
274 Result += getImageBase().get();
278 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
279 return getSectionSize(toSec(Ref));
282 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
283 StringRef &Result) const {
284 const coff_section *Sec = toSec(Ref);
285 ArrayRef<uint8_t> Res;
286 std::error_code EC = getSectionContents(Sec, Res);
287 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
291 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
292 const coff_section *Sec = toSec(Ref);
293 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
296 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
297 const coff_section *Sec = toSec(Ref);
298 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
301 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
302 const coff_section *Sec = toSec(Ref);
303 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
306 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
307 const coff_section *Sec = toSec(Ref);
308 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
309 COFF::IMAGE_SCN_MEM_READ |
310 COFF::IMAGE_SCN_MEM_WRITE;
311 return (Sec->Characteristics & BssFlags) == BssFlags;
314 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
316 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
317 assert((Offset % sizeof(coff_section)) == 0);
318 return (Offset / sizeof(coff_section)) + 1;
321 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
322 const coff_section *Sec = toSec(Ref);
323 // In COFF, a virtual section won't have any in-file
324 // content, so the file pointer to the content will be zero.
325 return Sec->PointerToRawData == 0;
328 static uint32_t getNumberOfRelocations(const coff_section *Sec,
329 MemoryBufferRef M, const uint8_t *base) {
330 // The field for the number of relocations in COFF section table is only
331 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
332 // NumberOfRelocations field, and the actual relocation count is stored in the
333 // VirtualAddress field in the first relocation entry.
334 if (Sec->hasExtendedRelocations()) {
335 const coff_relocation *FirstReloc;
336 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
337 base + Sec->PointerToRelocations)))
339 // -1 to exclude this first relocation entry.
340 return FirstReloc->VirtualAddress - 1;
342 return Sec->NumberOfRelocations;
345 static const coff_relocation *
346 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
347 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
350 auto begin = reinterpret_cast<const coff_relocation *>(
351 Base + Sec->PointerToRelocations);
352 if (Sec->hasExtendedRelocations()) {
353 // Skip the first relocation entry repurposed to store the number of
357 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
362 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
363 const coff_section *Sec = toSec(Ref);
364 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
365 if (begin && Sec->VirtualAddress != 0)
366 report_fatal_error("Sections with relocations should have an address of 0");
368 Ret.p = reinterpret_cast<uintptr_t>(begin);
369 return relocation_iterator(RelocationRef(Ret, this));
372 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
373 const coff_section *Sec = toSec(Ref);
374 const coff_relocation *I = getFirstReloc(Sec, Data, base());
376 I += getNumberOfRelocations(Sec, Data, base());
378 Ret.p = reinterpret_cast<uintptr_t>(I);
379 return relocation_iterator(RelocationRef(Ret, this));
382 // Initialize the pointer to the symbol table.
383 std::error_code COFFObjectFile::initSymbolTablePtr() {
385 if (std::error_code EC = getObject(
386 SymbolTable16, Data, base() + getPointerToSymbolTable(),
387 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
390 if (COFFBigObjHeader)
391 if (std::error_code EC = getObject(
392 SymbolTable32, Data, base() + getPointerToSymbolTable(),
393 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
396 // Find string table. The first four byte of the string table contains the
397 // total size of the string table, including the size field itself. If the
398 // string table is empty, the value of the first four byte would be 4.
399 uint32_t StringTableOffset = getPointerToSymbolTable() +
400 getNumberOfSymbols() * getSymbolTableEntrySize();
401 const uint8_t *StringTableAddr = base() + StringTableOffset;
402 const ulittle32_t *StringTableSizePtr;
403 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
405 StringTableSize = *StringTableSizePtr;
406 if (std::error_code EC =
407 getObject(StringTable, Data, StringTableAddr, StringTableSize))
410 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
411 // tools like cvtres write a size of 0 for an empty table instead of 4.
412 if (StringTableSize < 4)
415 // Check that the string table is null terminated if has any in it.
416 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
417 return object_error::parse_failed;
418 return std::error_code();
421 ErrorOr<uint64_t> COFFObjectFile::getImageBase() const {
423 return uint64_t(PE32Header->ImageBase);
424 else if (PE32PlusHeader)
425 return uint64_t(PE32PlusHeader->ImageBase);
426 return object_error::parse_failed;
429 // Returns the file offset for the given VA.
430 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
431 uint64_t ImageBase = getImageBase().get();
432 uint64_t Rva = Addr - ImageBase;
433 assert(Rva <= UINT32_MAX);
434 return getRvaPtr((uint32_t)Rva, Res);
437 // Returns the file offset for the given RVA.
438 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
439 for (const SectionRef &S : sections()) {
440 const coff_section *Section = getCOFFSection(S);
441 uint32_t SectionStart = Section->VirtualAddress;
442 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
443 if (SectionStart <= Addr && Addr < SectionEnd) {
444 uint32_t Offset = Addr - SectionStart;
445 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
446 return std::error_code();
449 return object_error::parse_failed;
452 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
454 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
455 StringRef &Name) const {
456 uintptr_t IntPtr = 0;
457 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
459 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
460 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
461 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
462 return std::error_code();
465 // Find the import table.
466 std::error_code COFFObjectFile::initImportTablePtr() {
467 // First, we get the RVA of the import table. If the file lacks a pointer to
468 // the import table, do nothing.
469 const data_directory *DataEntry;
470 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
471 return std::error_code();
473 // Do nothing if the pointer to import table is NULL.
474 if (DataEntry->RelativeVirtualAddress == 0)
475 return std::error_code();
477 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
478 // -1 because the last entry is the null entry.
479 NumberOfImportDirectory = DataEntry->Size /
480 sizeof(import_directory_table_entry) - 1;
482 // Find the section that contains the RVA. This is needed because the RVA is
483 // the import table's memory address which is different from its file offset.
484 uintptr_t IntPtr = 0;
485 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
487 ImportDirectory = reinterpret_cast<
488 const import_directory_table_entry *>(IntPtr);
489 return std::error_code();
492 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
493 std::error_code COFFObjectFile::initDelayImportTablePtr() {
494 const data_directory *DataEntry;
495 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
496 return std::error_code();
497 if (DataEntry->RelativeVirtualAddress == 0)
498 return std::error_code();
500 uint32_t RVA = DataEntry->RelativeVirtualAddress;
501 NumberOfDelayImportDirectory = DataEntry->Size /
502 sizeof(delay_import_directory_table_entry) - 1;
504 uintptr_t IntPtr = 0;
505 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
507 DelayImportDirectory = reinterpret_cast<
508 const delay_import_directory_table_entry *>(IntPtr);
509 return std::error_code();
512 // Find the export table.
513 std::error_code COFFObjectFile::initExportTablePtr() {
514 // First, we get the RVA of the export table. If the file lacks a pointer to
515 // the export table, do nothing.
516 const data_directory *DataEntry;
517 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
518 return std::error_code();
520 // Do nothing if the pointer to export table is NULL.
521 if (DataEntry->RelativeVirtualAddress == 0)
522 return std::error_code();
524 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
525 uintptr_t IntPtr = 0;
526 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
529 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
530 return std::error_code();
533 std::error_code COFFObjectFile::initBaseRelocPtr() {
534 const data_directory *DataEntry;
535 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
536 return std::error_code();
537 if (DataEntry->RelativeVirtualAddress == 0)
538 return std::error_code();
540 uintptr_t IntPtr = 0;
541 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
543 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
545 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
546 IntPtr + DataEntry->Size);
547 return std::error_code();
550 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
551 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
552 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
553 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
554 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
555 ImportDirectory(nullptr), NumberOfImportDirectory(0),
556 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
557 ExportDirectory(nullptr), BaseRelocHeader(nullptr),
558 BaseRelocEnd(nullptr) {
559 // Check that we at least have enough room for a header.
560 if (!checkSize(Data, EC, sizeof(coff_file_header)))
563 // The current location in the file where we are looking at.
566 // PE header is optional and is present only in executables. If it exists,
567 // it is placed right after COFF header.
568 bool HasPEHeader = false;
570 // Check if this is a PE/COFF file.
571 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
572 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
573 // PE signature to find 'normal' COFF header.
574 const auto *DH = reinterpret_cast<const dos_header *>(base());
575 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
576 CurPtr = DH->AddressOfNewExeHeader;
577 // Check the PE magic bytes. ("PE\0\0")
578 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
579 EC = object_error::parse_failed;
582 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
587 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
590 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
591 // import libraries share a common prefix but bigobj is more restrictive.
592 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
593 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
594 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
595 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
598 // Verify that we are dealing with bigobj.
599 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
600 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
601 sizeof(COFF::BigObjMagic)) == 0) {
602 COFFHeader = nullptr;
603 CurPtr += sizeof(coff_bigobj_file_header);
605 // It's not a bigobj.
606 COFFBigObjHeader = nullptr;
610 // The prior checkSize call may have failed. This isn't a hard error
611 // because we were just trying to sniff out bigobj.
612 EC = std::error_code();
613 CurPtr += sizeof(coff_file_header);
615 if (COFFHeader->isImportLibrary())
620 const pe32_header *Header;
621 if ((EC = getObject(Header, Data, base() + CurPtr)))
624 const uint8_t *DataDirAddr;
625 uint64_t DataDirSize;
626 if (Header->Magic == COFF::PE32Header::PE32) {
628 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
629 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
630 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
631 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
632 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
633 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
635 // It's neither PE32 nor PE32+.
636 EC = object_error::parse_failed;
639 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
641 CurPtr += COFFHeader->SizeOfOptionalHeader;
644 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
645 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
648 // Initialize the pointer to the symbol table.
649 if (getPointerToSymbolTable() != 0) {
650 if ((EC = initSymbolTablePtr()))
653 // We had better not have any symbols if we don't have a symbol table.
654 if (getNumberOfSymbols() != 0) {
655 EC = object_error::parse_failed;
660 // Initialize the pointer to the beginning of the import table.
661 if ((EC = initImportTablePtr()))
663 if ((EC = initDelayImportTablePtr()))
666 // Initialize the pointer to the export table.
667 if ((EC = initExportTablePtr()))
670 // Initialize the pointer to the base relocation table.
671 if ((EC = initBaseRelocPtr()))
674 EC = std::error_code();
677 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
679 Ret.p = getSymbolTable();
680 return basic_symbol_iterator(SymbolRef(Ret, this));
683 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
684 // The symbol table ends where the string table begins.
686 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
687 return basic_symbol_iterator(SymbolRef(Ret, this));
690 import_directory_iterator COFFObjectFile::import_directory_begin() const {
691 return import_directory_iterator(
692 ImportDirectoryEntryRef(ImportDirectory, 0, this));
695 import_directory_iterator COFFObjectFile::import_directory_end() const {
696 return import_directory_iterator(
697 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
700 delay_import_directory_iterator
701 COFFObjectFile::delay_import_directory_begin() const {
702 return delay_import_directory_iterator(
703 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
706 delay_import_directory_iterator
707 COFFObjectFile::delay_import_directory_end() const {
708 return delay_import_directory_iterator(
709 DelayImportDirectoryEntryRef(
710 DelayImportDirectory, NumberOfDelayImportDirectory, this));
713 export_directory_iterator COFFObjectFile::export_directory_begin() const {
714 return export_directory_iterator(
715 ExportDirectoryEntryRef(ExportDirectory, 0, this));
718 export_directory_iterator COFFObjectFile::export_directory_end() const {
719 if (!ExportDirectory)
720 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
721 ExportDirectoryEntryRef Ref(ExportDirectory,
722 ExportDirectory->AddressTableEntries, this);
723 return export_directory_iterator(Ref);
726 section_iterator COFFObjectFile::section_begin() const {
728 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
729 return section_iterator(SectionRef(Ret, this));
732 section_iterator COFFObjectFile::section_end() const {
735 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
736 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
737 return section_iterator(SectionRef(Ret, this));
740 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
741 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
744 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
745 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
748 uint8_t COFFObjectFile::getBytesInAddress() const {
749 return getArch() == Triple::x86_64 ? 8 : 4;
752 StringRef COFFObjectFile::getFileFormatName() const {
753 switch(getMachine()) {
754 case COFF::IMAGE_FILE_MACHINE_I386:
756 case COFF::IMAGE_FILE_MACHINE_AMD64:
757 return "COFF-x86-64";
758 case COFF::IMAGE_FILE_MACHINE_ARMNT:
760 case COFF::IMAGE_FILE_MACHINE_ARM64:
763 return "COFF-<unknown arch>";
767 unsigned COFFObjectFile::getArch() const {
768 switch (getMachine()) {
769 case COFF::IMAGE_FILE_MACHINE_I386:
771 case COFF::IMAGE_FILE_MACHINE_AMD64:
772 return Triple::x86_64;
773 case COFF::IMAGE_FILE_MACHINE_ARMNT:
774 return Triple::thumb;
775 case COFF::IMAGE_FILE_MACHINE_ARM64:
776 return Triple::aarch64;
778 return Triple::UnknownArch;
782 iterator_range<import_directory_iterator>
783 COFFObjectFile::import_directories() const {
784 return make_range(import_directory_begin(), import_directory_end());
787 iterator_range<delay_import_directory_iterator>
788 COFFObjectFile::delay_import_directories() const {
789 return make_range(delay_import_directory_begin(),
790 delay_import_directory_end());
793 iterator_range<export_directory_iterator>
794 COFFObjectFile::export_directories() const {
795 return make_range(export_directory_begin(), export_directory_end());
798 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
799 return make_range(base_reloc_begin(), base_reloc_end());
802 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
804 return std::error_code();
808 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
809 Res = PE32PlusHeader;
810 return std::error_code();
814 COFFObjectFile::getDataDirectory(uint32_t Index,
815 const data_directory *&Res) const {
816 // Error if if there's no data directory or the index is out of range.
817 if (!DataDirectory) {
819 return object_error::parse_failed;
821 assert(PE32Header || PE32PlusHeader);
822 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
823 : PE32PlusHeader->NumberOfRvaAndSize;
824 if (Index >= NumEnt) {
826 return object_error::parse_failed;
828 Res = &DataDirectory[Index];
829 return std::error_code();
832 std::error_code COFFObjectFile::getSection(int32_t Index,
833 const coff_section *&Result) const {
835 if (COFF::isReservedSectionNumber(Index))
836 return std::error_code();
837 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
838 // We already verified the section table data, so no need to check again.
839 Result = SectionTable + (Index - 1);
840 return std::error_code();
842 return object_error::parse_failed;
845 std::error_code COFFObjectFile::getString(uint32_t Offset,
846 StringRef &Result) const {
847 if (StringTableSize <= 4)
848 // Tried to get a string from an empty string table.
849 return object_error::parse_failed;
850 if (Offset >= StringTableSize)
851 return object_error::unexpected_eof;
852 Result = StringRef(StringTable + Offset);
853 return std::error_code();
856 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
857 StringRef &Res) const {
858 return getSymbolName(Symbol.getGeneric(), Res);
861 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
862 StringRef &Res) const {
863 // Check for string table entry. First 4 bytes are 0.
864 if (Symbol->Name.Offset.Zeroes == 0) {
865 if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
867 return std::error_code();
870 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
871 // Null terminated, let ::strlen figure out the length.
872 Res = StringRef(Symbol->Name.ShortName);
874 // Not null terminated, use all 8 bytes.
875 Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
876 return std::error_code();
880 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
881 const uint8_t *Aux = nullptr;
883 size_t SymbolSize = getSymbolTableEntrySize();
884 if (Symbol.getNumberOfAuxSymbols() > 0) {
885 // AUX data comes immediately after the symbol in COFF
886 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
888 // Verify that the Aux symbol points to a valid entry in the symbol table.
889 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
890 if (Offset < getPointerToSymbolTable() ||
892 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
893 report_fatal_error("Aux Symbol data was outside of symbol table.");
895 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
896 "Aux Symbol data did not point to the beginning of a symbol");
899 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
902 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
903 StringRef &Res) const {
905 if (Sec->Name[COFF::NameSize - 1] == 0)
906 // Null terminated, let ::strlen figure out the length.
909 // Not null terminated, use all 8 bytes.
910 Name = StringRef(Sec->Name, COFF::NameSize);
912 // Check for string table entry. First byte is '/'.
913 if (Name.startswith("/")) {
915 if (Name.startswith("//")) {
916 if (decodeBase64StringEntry(Name.substr(2), Offset))
917 return object_error::parse_failed;
919 if (Name.substr(1).getAsInteger(10, Offset))
920 return object_error::parse_failed;
922 if (std::error_code EC = getString(Offset, Name))
927 return std::error_code();
930 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
931 // SizeOfRawData and VirtualSize change what they represent depending on
932 // whether or not we have an executable image.
934 // For object files, SizeOfRawData contains the size of section's data;
935 // VirtualSize should be zero but isn't due to buggy COFF writers.
937 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
938 // actual section size is in VirtualSize. It is possible for VirtualSize to
939 // be greater than SizeOfRawData; the contents past that point should be
940 // considered to be zero.
942 return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
943 return Sec->SizeOfRawData;
947 COFFObjectFile::getSectionContents(const coff_section *Sec,
948 ArrayRef<uint8_t> &Res) const {
949 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
950 // don't do anything interesting for them.
951 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
952 "BSS sections don't have contents!");
953 // The only thing that we need to verify is that the contents is contained
954 // within the file bounds. We don't need to make sure it doesn't cover other
955 // data, as there's nothing that says that is not allowed.
956 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
957 uint32_t SectionSize = getSectionSize(Sec);
958 if (checkOffset(Data, ConStart, SectionSize))
959 return object_error::parse_failed;
960 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
961 return std::error_code();
964 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
965 return reinterpret_cast<const coff_relocation*>(Rel.p);
968 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
969 Rel.p = reinterpret_cast<uintptr_t>(
970 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
973 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
974 const coff_relocation *R = toRel(Rel);
975 return R->VirtualAddress;
978 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
979 const coff_relocation *R = toRel(Rel);
981 if (R->SymbolTableIndex >= getNumberOfSymbols())
984 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
985 else if (SymbolTable32)
986 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
988 llvm_unreachable("no symbol table pointer!");
989 return symbol_iterator(SymbolRef(Ref, this));
992 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
993 const coff_relocation* R = toRel(Rel);
998 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
999 return toSec(Section.getRawDataRefImpl());
1002 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1004 return toSymb<coff_symbol16>(Ref);
1006 return toSymb<coff_symbol32>(Ref);
1007 llvm_unreachable("no symbol table pointer!");
1010 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1011 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1014 const coff_relocation *
1015 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1016 return toRel(Reloc.getRawDataRefImpl());
1019 iterator_range<const coff_relocation *>
1020 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1021 const coff_relocation *I = getFirstReloc(Sec, Data, base());
1022 const coff_relocation *E = I;
1024 E += getNumberOfRelocations(Sec, Data, base());
1025 return make_range(I, E);
1028 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1029 case COFF::reloc_type: \
1030 Res = #reloc_type; \
1033 void COFFObjectFile::getRelocationTypeName(
1034 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1035 const coff_relocation *Reloc = toRel(Rel);
1037 switch (getMachine()) {
1038 case COFF::IMAGE_FILE_MACHINE_AMD64:
1039 switch (Reloc->Type) {
1040 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1041 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1042 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1043 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1044 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1045 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1046 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1047 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1048 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1049 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1050 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1051 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1052 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1053 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1054 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1055 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1056 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1061 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1062 switch (Reloc->Type) {
1063 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1064 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1065 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1066 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1067 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1068 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1069 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1070 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1071 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1072 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1073 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1074 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1075 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1076 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1077 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1082 case COFF::IMAGE_FILE_MACHINE_I386:
1083 switch (Reloc->Type) {
1084 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1085 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1086 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1087 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1088 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1089 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1090 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1091 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1092 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1093 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1094 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1102 Result.append(Res.begin(), Res.end());
1105 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1107 bool COFFObjectFile::isRelocatableObject() const {
1108 return !DataDirectory;
1111 bool ImportDirectoryEntryRef::
1112 operator==(const ImportDirectoryEntryRef &Other) const {
1113 return ImportTable == Other.ImportTable && Index == Other.Index;
1116 void ImportDirectoryEntryRef::moveNext() {
1120 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1121 const import_directory_table_entry *&Result) const {
1122 Result = ImportTable + Index;
1123 return std::error_code();
1126 static imported_symbol_iterator
1127 makeImportedSymbolIterator(const COFFObjectFile *Object,
1128 uintptr_t Ptr, int Index) {
1129 if (Object->getBytesInAddress() == 4) {
1130 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1131 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1133 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1134 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1137 static imported_symbol_iterator
1138 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1139 uintptr_t IntPtr = 0;
1140 Object->getRvaPtr(RVA, IntPtr);
1141 return makeImportedSymbolIterator(Object, IntPtr, 0);
1144 static imported_symbol_iterator
1145 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1146 uintptr_t IntPtr = 0;
1147 Object->getRvaPtr(RVA, IntPtr);
1148 // Forward the pointer to the last entry which is null.
1150 if (Object->getBytesInAddress() == 4) {
1151 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1155 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1159 return makeImportedSymbolIterator(Object, IntPtr, Index);
1162 imported_symbol_iterator
1163 ImportDirectoryEntryRef::imported_symbol_begin() const {
1164 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1168 imported_symbol_iterator
1169 ImportDirectoryEntryRef::imported_symbol_end() const {
1170 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1174 iterator_range<imported_symbol_iterator>
1175 ImportDirectoryEntryRef::imported_symbols() const {
1176 return make_range(imported_symbol_begin(), imported_symbol_end());
1179 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1180 uintptr_t IntPtr = 0;
1181 if (std::error_code EC =
1182 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1184 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1185 return std::error_code();
1189 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1190 Result = ImportTable[Index].ImportLookupTableRVA;
1191 return std::error_code();
1195 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1196 Result = ImportTable[Index].ImportAddressTableRVA;
1197 return std::error_code();
1200 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1201 const import_lookup_table_entry32 *&Result) const {
1202 uintptr_t IntPtr = 0;
1203 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1204 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1206 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1207 return std::error_code();
1210 bool DelayImportDirectoryEntryRef::
1211 operator==(const DelayImportDirectoryEntryRef &Other) const {
1212 return Table == Other.Table && Index == Other.Index;
1215 void DelayImportDirectoryEntryRef::moveNext() {
1219 imported_symbol_iterator
1220 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1221 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1225 imported_symbol_iterator
1226 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1227 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1231 iterator_range<imported_symbol_iterator>
1232 DelayImportDirectoryEntryRef::imported_symbols() const {
1233 return make_range(imported_symbol_begin(), imported_symbol_end());
1236 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1237 uintptr_t IntPtr = 0;
1238 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1240 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1241 return std::error_code();
1244 std::error_code DelayImportDirectoryEntryRef::
1245 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1247 return std::error_code();
1250 std::error_code DelayImportDirectoryEntryRef::
1251 getImportAddress(int AddrIndex, uint64_t &Result) const {
1252 uint32_t RVA = Table[Index].DelayImportAddressTable +
1253 AddrIndex * (OwningObject->is64() ? 8 : 4);
1254 uintptr_t IntPtr = 0;
1255 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1257 if (OwningObject->is64())
1258 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1260 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1261 return std::error_code();
1264 bool ExportDirectoryEntryRef::
1265 operator==(const ExportDirectoryEntryRef &Other) const {
1266 return ExportTable == Other.ExportTable && Index == Other.Index;
1269 void ExportDirectoryEntryRef::moveNext() {
1273 // Returns the name of the current export symbol. If the symbol is exported only
1274 // by ordinal, the empty string is set as a result.
1275 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1276 uintptr_t IntPtr = 0;
1277 if (std::error_code EC =
1278 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1280 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1281 return std::error_code();
1284 // Returns the starting ordinal number.
1286 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1287 Result = ExportTable->OrdinalBase;
1288 return std::error_code();
1291 // Returns the export ordinal of the current export symbol.
1292 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1293 Result = ExportTable->OrdinalBase + Index;
1294 return std::error_code();
1297 // Returns the address of the current export symbol.
1298 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1299 uintptr_t IntPtr = 0;
1300 if (std::error_code EC =
1301 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1303 const export_address_table_entry *entry =
1304 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1305 Result = entry[Index].ExportRVA;
1306 return std::error_code();
1309 // Returns the name of the current export symbol. If the symbol is exported only
1310 // by ordinal, the empty string is set as a result.
1312 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1313 uintptr_t IntPtr = 0;
1314 if (std::error_code EC =
1315 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1317 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1319 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1321 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1322 I < E; ++I, ++Offset) {
1325 if (std::error_code EC =
1326 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1328 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1329 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1331 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1332 return std::error_code();
1335 return std::error_code();
1338 bool ImportedSymbolRef::
1339 operator==(const ImportedSymbolRef &Other) const {
1340 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1341 && Index == Other.Index;
1344 void ImportedSymbolRef::moveNext() {
1349 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1352 // If a symbol is imported only by ordinal, it has no name.
1353 if (Entry32[Index].isOrdinal())
1354 return std::error_code();
1355 RVA = Entry32[Index].getHintNameRVA();
1357 if (Entry64[Index].isOrdinal())
1358 return std::error_code();
1359 RVA = Entry64[Index].getHintNameRVA();
1361 uintptr_t IntPtr = 0;
1362 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1364 // +2 because the first two bytes is hint.
1365 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1366 return std::error_code();
1369 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1372 if (Entry32[Index].isOrdinal()) {
1373 Result = Entry32[Index].getOrdinal();
1374 return std::error_code();
1376 RVA = Entry32[Index].getHintNameRVA();
1378 if (Entry64[Index].isOrdinal()) {
1379 Result = Entry64[Index].getOrdinal();
1380 return std::error_code();
1382 RVA = Entry64[Index].getHintNameRVA();
1384 uintptr_t IntPtr = 0;
1385 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1387 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1388 return std::error_code();
1391 ErrorOr<std::unique_ptr<COFFObjectFile>>
1392 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1394 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1397 return std::move(Ret);
1400 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1401 return Header == Other.Header && Index == Other.Index;
1404 void BaseRelocRef::moveNext() {
1405 // Header->BlockSize is the size of the current block, including the
1406 // size of the header itself.
1407 uint32_t Size = sizeof(*Header) +
1408 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1409 if (Size == Header->BlockSize) {
1410 // .reloc contains a list of base relocation blocks. Each block
1411 // consists of the header followed by entries. The header contains
1412 // how many entories will follow. When we reach the end of the
1413 // current block, proceed to the next block.
1414 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1415 reinterpret_cast<const uint8_t *>(Header) + Size);
1422 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1423 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1424 Type = Entry[Index].getType();
1425 return std::error_code();
1428 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1429 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1430 Result = Header->PageRVA + Entry[Index].getOffset();
1431 return std::error_code();