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::getSymbolValue(DataRefImpl Ref) const {
158 COFFSymbolRef Sym = getCOFFSymbol(Ref);
160 if (Sym.isAnyUndefined() || Sym.isCommon())
161 return UnknownAddress;
163 return Sym.getValue();
166 ErrorOr<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
167 uint64_t Result = getSymbolValue(Ref);
168 COFFSymbolRef Symb = getCOFFSymbol(Ref);
169 int32_t SectionNumber = Symb.getSectionNumber();
171 if (Symb.isAnyUndefined() || Symb.isCommon() ||
172 COFF::isReservedSectionNumber(SectionNumber))
175 const coff_section *Section = nullptr;
176 if (std::error_code EC = getSection(SectionNumber, Section))
178 Result += Section->VirtualAddress;
182 SymbolRef::Type COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
183 COFFSymbolRef Symb = getCOFFSymbol(Ref);
184 int32_t SectionNumber = Symb.getSectionNumber();
186 if (Symb.isAnyUndefined())
187 return SymbolRef::ST_Unknown;
188 if (Symb.isFunctionDefinition())
189 return SymbolRef::ST_Function;
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();
239 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
240 section_iterator &Result) const {
241 COFFSymbolRef Symb = getCOFFSymbol(Ref);
242 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
243 Result = section_end();
245 const coff_section *Sec = nullptr;
246 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
249 Ref.p = reinterpret_cast<uintptr_t>(Sec);
250 Result = section_iterator(SectionRef(Ref, this));
252 return std::error_code();
255 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
256 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
257 return Symb.getSectionNumber();
260 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
261 const coff_section *Sec = toSec(Ref);
263 Ref.p = reinterpret_cast<uintptr_t>(Sec);
266 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
267 StringRef &Result) const {
268 const coff_section *Sec = toSec(Ref);
269 return getSectionName(Sec, Result);
272 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
273 const coff_section *Sec = toSec(Ref);
274 return Sec->VirtualAddress;
277 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
278 return getSectionSize(toSec(Ref));
281 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
282 StringRef &Result) const {
283 const coff_section *Sec = toSec(Ref);
284 ArrayRef<uint8_t> Res;
285 std::error_code EC = getSectionContents(Sec, Res);
286 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
290 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
291 const coff_section *Sec = toSec(Ref);
292 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
295 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
296 const coff_section *Sec = toSec(Ref);
297 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
300 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
301 const coff_section *Sec = toSec(Ref);
302 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
305 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
306 const coff_section *Sec = toSec(Ref);
307 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
308 COFF::IMAGE_SCN_MEM_READ |
309 COFF::IMAGE_SCN_MEM_WRITE;
310 return (Sec->Characteristics & BssFlags) == BssFlags;
313 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
315 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
316 assert((Offset % sizeof(coff_section)) == 0);
317 return (Offset / sizeof(coff_section)) + 1;
320 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
321 const coff_section *Sec = toSec(Ref);
322 // In COFF, a virtual section won't have any in-file
323 // content, so the file pointer to the content will be zero.
324 return Sec->PointerToRawData == 0;
327 static uint32_t getNumberOfRelocations(const coff_section *Sec,
328 MemoryBufferRef M, const uint8_t *base) {
329 // The field for the number of relocations in COFF section table is only
330 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
331 // NumberOfRelocations field, and the actual relocation count is stored in the
332 // VirtualAddress field in the first relocation entry.
333 if (Sec->hasExtendedRelocations()) {
334 const coff_relocation *FirstReloc;
335 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
336 base + Sec->PointerToRelocations)))
338 // -1 to exclude this first relocation entry.
339 return FirstReloc->VirtualAddress - 1;
341 return Sec->NumberOfRelocations;
344 static const coff_relocation *
345 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
346 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
349 auto begin = reinterpret_cast<const coff_relocation *>(
350 Base + Sec->PointerToRelocations);
351 if (Sec->hasExtendedRelocations()) {
352 // Skip the first relocation entry repurposed to store the number of
356 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
361 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
362 const coff_section *Sec = toSec(Ref);
363 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
364 if (begin && Sec->VirtualAddress != 0)
365 report_fatal_error("Sections with relocations should have an address of 0");
367 Ret.p = reinterpret_cast<uintptr_t>(begin);
368 return relocation_iterator(RelocationRef(Ret, this));
371 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
372 const coff_section *Sec = toSec(Ref);
373 const coff_relocation *I = getFirstReloc(Sec, Data, base());
375 I += getNumberOfRelocations(Sec, Data, base());
377 Ret.p = reinterpret_cast<uintptr_t>(I);
378 return relocation_iterator(RelocationRef(Ret, this));
381 // Initialize the pointer to the symbol table.
382 std::error_code COFFObjectFile::initSymbolTablePtr() {
384 if (std::error_code EC = getObject(
385 SymbolTable16, Data, base() + getPointerToSymbolTable(),
386 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
389 if (COFFBigObjHeader)
390 if (std::error_code EC = getObject(
391 SymbolTable32, Data, base() + getPointerToSymbolTable(),
392 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
395 // Find string table. The first four byte of the string table contains the
396 // total size of the string table, including the size field itself. If the
397 // string table is empty, the value of the first four byte would be 4.
398 uint32_t StringTableOffset = getPointerToSymbolTable() +
399 getNumberOfSymbols() * getSymbolTableEntrySize();
400 const uint8_t *StringTableAddr = base() + StringTableOffset;
401 const ulittle32_t *StringTableSizePtr;
402 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
404 StringTableSize = *StringTableSizePtr;
405 if (std::error_code EC =
406 getObject(StringTable, Data, StringTableAddr, StringTableSize))
409 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
410 // tools like cvtres write a size of 0 for an empty table instead of 4.
411 if (StringTableSize < 4)
414 // Check that the string table is null terminated if has any in it.
415 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
416 return object_error::parse_failed;
417 return std::error_code();
420 // Returns the file offset for the given VA.
421 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
422 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
423 : (uint64_t)PE32PlusHeader->ImageBase;
424 uint64_t Rva = Addr - ImageBase;
425 assert(Rva <= UINT32_MAX);
426 return getRvaPtr((uint32_t)Rva, Res);
429 // Returns the file offset for the given RVA.
430 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
431 for (const SectionRef &S : sections()) {
432 const coff_section *Section = getCOFFSection(S);
433 uint32_t SectionStart = Section->VirtualAddress;
434 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
435 if (SectionStart <= Addr && Addr < SectionEnd) {
436 uint32_t Offset = Addr - SectionStart;
437 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
438 return std::error_code();
441 return object_error::parse_failed;
444 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
446 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
447 StringRef &Name) const {
448 uintptr_t IntPtr = 0;
449 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
451 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
452 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
453 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
454 return std::error_code();
457 // Find the import table.
458 std::error_code COFFObjectFile::initImportTablePtr() {
459 // First, we get the RVA of the import table. If the file lacks a pointer to
460 // the import table, do nothing.
461 const data_directory *DataEntry;
462 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
463 return std::error_code();
465 // Do nothing if the pointer to import table is NULL.
466 if (DataEntry->RelativeVirtualAddress == 0)
467 return std::error_code();
469 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
470 // -1 because the last entry is the null entry.
471 NumberOfImportDirectory = DataEntry->Size /
472 sizeof(import_directory_table_entry) - 1;
474 // Find the section that contains the RVA. This is needed because the RVA is
475 // the import table's memory address which is different from its file offset.
476 uintptr_t IntPtr = 0;
477 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
479 ImportDirectory = reinterpret_cast<
480 const import_directory_table_entry *>(IntPtr);
481 return std::error_code();
484 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
485 std::error_code COFFObjectFile::initDelayImportTablePtr() {
486 const data_directory *DataEntry;
487 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
488 return std::error_code();
489 if (DataEntry->RelativeVirtualAddress == 0)
490 return std::error_code();
492 uint32_t RVA = DataEntry->RelativeVirtualAddress;
493 NumberOfDelayImportDirectory = DataEntry->Size /
494 sizeof(delay_import_directory_table_entry) - 1;
496 uintptr_t IntPtr = 0;
497 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
499 DelayImportDirectory = reinterpret_cast<
500 const delay_import_directory_table_entry *>(IntPtr);
501 return std::error_code();
504 // Find the export table.
505 std::error_code COFFObjectFile::initExportTablePtr() {
506 // First, we get the RVA of the export table. If the file lacks a pointer to
507 // the export table, do nothing.
508 const data_directory *DataEntry;
509 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
510 return std::error_code();
512 // Do nothing if the pointer to export table is NULL.
513 if (DataEntry->RelativeVirtualAddress == 0)
514 return std::error_code();
516 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
517 uintptr_t IntPtr = 0;
518 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
521 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
522 return std::error_code();
525 std::error_code COFFObjectFile::initBaseRelocPtr() {
526 const data_directory *DataEntry;
527 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
528 return std::error_code();
529 if (DataEntry->RelativeVirtualAddress == 0)
530 return std::error_code();
532 uintptr_t IntPtr = 0;
533 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
535 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
537 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
538 IntPtr + DataEntry->Size);
539 return std::error_code();
542 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
543 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
544 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
545 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
546 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
547 ImportDirectory(nullptr), NumberOfImportDirectory(0),
548 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
549 ExportDirectory(nullptr), BaseRelocHeader(nullptr),
550 BaseRelocEnd(nullptr) {
551 // Check that we at least have enough room for a header.
552 if (!checkSize(Data, EC, sizeof(coff_file_header)))
555 // The current location in the file where we are looking at.
558 // PE header is optional and is present only in executables. If it exists,
559 // it is placed right after COFF header.
560 bool HasPEHeader = false;
562 // Check if this is a PE/COFF file.
563 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
564 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
565 // PE signature to find 'normal' COFF header.
566 const auto *DH = reinterpret_cast<const dos_header *>(base());
567 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
568 CurPtr = DH->AddressOfNewExeHeader;
569 // Check the PE magic bytes. ("PE\0\0")
570 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
571 EC = object_error::parse_failed;
574 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
579 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
582 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
583 // import libraries share a common prefix but bigobj is more restrictive.
584 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
585 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
586 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
587 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
590 // Verify that we are dealing with bigobj.
591 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
592 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
593 sizeof(COFF::BigObjMagic)) == 0) {
594 COFFHeader = nullptr;
595 CurPtr += sizeof(coff_bigobj_file_header);
597 // It's not a bigobj.
598 COFFBigObjHeader = nullptr;
602 // The prior checkSize call may have failed. This isn't a hard error
603 // because we were just trying to sniff out bigobj.
604 EC = std::error_code();
605 CurPtr += sizeof(coff_file_header);
607 if (COFFHeader->isImportLibrary())
612 const pe32_header *Header;
613 if ((EC = getObject(Header, Data, base() + CurPtr)))
616 const uint8_t *DataDirAddr;
617 uint64_t DataDirSize;
618 if (Header->Magic == COFF::PE32Header::PE32) {
620 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
621 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
622 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
623 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
624 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
625 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
627 // It's neither PE32 nor PE32+.
628 EC = object_error::parse_failed;
631 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
633 CurPtr += COFFHeader->SizeOfOptionalHeader;
636 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
637 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
640 // Initialize the pointer to the symbol table.
641 if (getPointerToSymbolTable() != 0) {
642 if ((EC = initSymbolTablePtr()))
645 // We had better not have any symbols if we don't have a symbol table.
646 if (getNumberOfSymbols() != 0) {
647 EC = object_error::parse_failed;
652 // Initialize the pointer to the beginning of the import table.
653 if ((EC = initImportTablePtr()))
655 if ((EC = initDelayImportTablePtr()))
658 // Initialize the pointer to the export table.
659 if ((EC = initExportTablePtr()))
662 // Initialize the pointer to the base relocation table.
663 if ((EC = initBaseRelocPtr()))
666 EC = std::error_code();
669 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
671 Ret.p = getSymbolTable();
672 return basic_symbol_iterator(SymbolRef(Ret, this));
675 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
676 // The symbol table ends where the string table begins.
678 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
679 return basic_symbol_iterator(SymbolRef(Ret, this));
682 import_directory_iterator COFFObjectFile::import_directory_begin() const {
683 return import_directory_iterator(
684 ImportDirectoryEntryRef(ImportDirectory, 0, this));
687 import_directory_iterator COFFObjectFile::import_directory_end() const {
688 return import_directory_iterator(
689 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
692 delay_import_directory_iterator
693 COFFObjectFile::delay_import_directory_begin() const {
694 return delay_import_directory_iterator(
695 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
698 delay_import_directory_iterator
699 COFFObjectFile::delay_import_directory_end() const {
700 return delay_import_directory_iterator(
701 DelayImportDirectoryEntryRef(
702 DelayImportDirectory, NumberOfDelayImportDirectory, this));
705 export_directory_iterator COFFObjectFile::export_directory_begin() const {
706 return export_directory_iterator(
707 ExportDirectoryEntryRef(ExportDirectory, 0, this));
710 export_directory_iterator COFFObjectFile::export_directory_end() const {
711 if (!ExportDirectory)
712 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
713 ExportDirectoryEntryRef Ref(ExportDirectory,
714 ExportDirectory->AddressTableEntries, this);
715 return export_directory_iterator(Ref);
718 section_iterator COFFObjectFile::section_begin() const {
720 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
721 return section_iterator(SectionRef(Ret, this));
724 section_iterator COFFObjectFile::section_end() const {
727 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
728 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
729 return section_iterator(SectionRef(Ret, this));
732 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
733 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
736 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
737 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
740 uint8_t COFFObjectFile::getBytesInAddress() const {
741 return getArch() == Triple::x86_64 ? 8 : 4;
744 StringRef COFFObjectFile::getFileFormatName() const {
745 switch(getMachine()) {
746 case COFF::IMAGE_FILE_MACHINE_I386:
748 case COFF::IMAGE_FILE_MACHINE_AMD64:
749 return "COFF-x86-64";
750 case COFF::IMAGE_FILE_MACHINE_ARMNT:
753 return "COFF-<unknown arch>";
757 unsigned COFFObjectFile::getArch() const {
758 switch (getMachine()) {
759 case COFF::IMAGE_FILE_MACHINE_I386:
761 case COFF::IMAGE_FILE_MACHINE_AMD64:
762 return Triple::x86_64;
763 case COFF::IMAGE_FILE_MACHINE_ARMNT:
764 return Triple::thumb;
766 return Triple::UnknownArch;
770 iterator_range<import_directory_iterator>
771 COFFObjectFile::import_directories() const {
772 return make_range(import_directory_begin(), import_directory_end());
775 iterator_range<delay_import_directory_iterator>
776 COFFObjectFile::delay_import_directories() const {
777 return make_range(delay_import_directory_begin(),
778 delay_import_directory_end());
781 iterator_range<export_directory_iterator>
782 COFFObjectFile::export_directories() const {
783 return make_range(export_directory_begin(), export_directory_end());
786 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
787 return make_range(base_reloc_begin(), base_reloc_end());
790 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
792 return std::error_code();
796 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
797 Res = PE32PlusHeader;
798 return std::error_code();
802 COFFObjectFile::getDataDirectory(uint32_t Index,
803 const data_directory *&Res) const {
804 // Error if if there's no data directory or the index is out of range.
805 if (!DataDirectory) {
807 return object_error::parse_failed;
809 assert(PE32Header || PE32PlusHeader);
810 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
811 : PE32PlusHeader->NumberOfRvaAndSize;
812 if (Index >= NumEnt) {
814 return object_error::parse_failed;
816 Res = &DataDirectory[Index];
817 return std::error_code();
820 std::error_code COFFObjectFile::getSection(int32_t Index,
821 const coff_section *&Result) const {
823 if (COFF::isReservedSectionNumber(Index))
824 return std::error_code();
825 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
826 // We already verified the section table data, so no need to check again.
827 Result = SectionTable + (Index - 1);
828 return std::error_code();
830 return object_error::parse_failed;
833 std::error_code COFFObjectFile::getString(uint32_t Offset,
834 StringRef &Result) const {
835 if (StringTableSize <= 4)
836 // Tried to get a string from an empty string table.
837 return object_error::parse_failed;
838 if (Offset >= StringTableSize)
839 return object_error::unexpected_eof;
840 Result = StringRef(StringTable + Offset);
841 return std::error_code();
844 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
845 StringRef &Res) const {
846 return getSymbolName(Symbol.getGeneric(), Res);
849 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
850 StringRef &Res) const {
851 // Check for string table entry. First 4 bytes are 0.
852 if (Symbol->Name.Offset.Zeroes == 0) {
853 if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
855 return std::error_code();
858 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
859 // Null terminated, let ::strlen figure out the length.
860 Res = StringRef(Symbol->Name.ShortName);
862 // Not null terminated, use all 8 bytes.
863 Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
864 return std::error_code();
868 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
869 const uint8_t *Aux = nullptr;
871 size_t SymbolSize = getSymbolTableEntrySize();
872 if (Symbol.getNumberOfAuxSymbols() > 0) {
873 // AUX data comes immediately after the symbol in COFF
874 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
876 // Verify that the Aux symbol points to a valid entry in the symbol table.
877 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
878 if (Offset < getPointerToSymbolTable() ||
880 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
881 report_fatal_error("Aux Symbol data was outside of symbol table.");
883 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
884 "Aux Symbol data did not point to the beginning of a symbol");
887 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
890 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
891 StringRef &Res) const {
893 if (Sec->Name[COFF::NameSize - 1] == 0)
894 // Null terminated, let ::strlen figure out the length.
897 // Not null terminated, use all 8 bytes.
898 Name = StringRef(Sec->Name, COFF::NameSize);
900 // Check for string table entry. First byte is '/'.
901 if (Name.startswith("/")) {
903 if (Name.startswith("//")) {
904 if (decodeBase64StringEntry(Name.substr(2), Offset))
905 return object_error::parse_failed;
907 if (Name.substr(1).getAsInteger(10, Offset))
908 return object_error::parse_failed;
910 if (std::error_code EC = getString(Offset, Name))
915 return std::error_code();
918 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
919 // SizeOfRawData and VirtualSize change what they represent depending on
920 // whether or not we have an executable image.
922 // For object files, SizeOfRawData contains the size of section's data;
923 // VirtualSize should be zero but isn't due to buggy COFF writers.
925 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
926 // actual section size is in VirtualSize. It is possible for VirtualSize to
927 // be greater than SizeOfRawData; the contents past that point should be
928 // considered to be zero.
930 return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
931 return Sec->SizeOfRawData;
935 COFFObjectFile::getSectionContents(const coff_section *Sec,
936 ArrayRef<uint8_t> &Res) const {
937 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
938 // don't do anything interesting for them.
939 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
940 "BSS sections don't have contents!");
941 // The only thing that we need to verify is that the contents is contained
942 // within the file bounds. We don't need to make sure it doesn't cover other
943 // data, as there's nothing that says that is not allowed.
944 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
945 uint32_t SectionSize = getSectionSize(Sec);
946 if (checkOffset(Data, ConStart, SectionSize))
947 return object_error::parse_failed;
948 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
949 return std::error_code();
952 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
953 return reinterpret_cast<const coff_relocation*>(Rel.p);
956 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
957 Rel.p = reinterpret_cast<uintptr_t>(
958 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
961 ErrorOr<uint64_t> COFFObjectFile::getRelocationAddress(DataRefImpl Rel) const {
962 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
965 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
966 const coff_relocation *R = toRel(Rel);
967 return R->VirtualAddress;
970 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
971 const coff_relocation *R = toRel(Rel);
973 if (R->SymbolTableIndex >= getNumberOfSymbols())
976 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
977 else if (SymbolTable32)
978 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
980 llvm_unreachable("no symbol table pointer!");
981 return symbol_iterator(SymbolRef(Ref, this));
984 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
985 const coff_relocation* R = toRel(Rel);
990 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
991 return toSec(Section.getRawDataRefImpl());
994 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
996 return toSymb<coff_symbol16>(Ref);
998 return toSymb<coff_symbol32>(Ref);
999 llvm_unreachable("no symbol table pointer!");
1002 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1003 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1006 const coff_relocation *
1007 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1008 return toRel(Reloc.getRawDataRefImpl());
1011 iterator_range<const coff_relocation *>
1012 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1013 const coff_relocation *I = getFirstReloc(Sec, Data, base());
1014 const coff_relocation *E = I;
1016 E += getNumberOfRelocations(Sec, Data, base());
1017 return make_range(I, E);
1020 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1021 case COFF::reloc_type: \
1022 Res = #reloc_type; \
1025 void COFFObjectFile::getRelocationTypeName(
1026 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1027 const coff_relocation *Reloc = toRel(Rel);
1029 switch (getMachine()) {
1030 case COFF::IMAGE_FILE_MACHINE_AMD64:
1031 switch (Reloc->Type) {
1032 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1033 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1034 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1035 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1036 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1037 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1038 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1039 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1040 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1041 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1042 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1043 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1044 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1045 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1046 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1047 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1048 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1053 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1054 switch (Reloc->Type) {
1055 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1056 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1057 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1058 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1059 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1060 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1061 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1062 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1063 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1064 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1065 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1066 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1067 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1068 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1069 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1074 case COFF::IMAGE_FILE_MACHINE_I386:
1075 switch (Reloc->Type) {
1076 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1077 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1078 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1079 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1080 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1081 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1082 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1083 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1084 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1085 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1086 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1094 Result.append(Res.begin(), Res.end());
1097 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1099 bool COFFObjectFile::isRelocatableObject() const {
1100 return !DataDirectory;
1103 bool ImportDirectoryEntryRef::
1104 operator==(const ImportDirectoryEntryRef &Other) const {
1105 return ImportTable == Other.ImportTable && Index == Other.Index;
1108 void ImportDirectoryEntryRef::moveNext() {
1112 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1113 const import_directory_table_entry *&Result) const {
1114 Result = ImportTable + Index;
1115 return std::error_code();
1118 static imported_symbol_iterator
1119 makeImportedSymbolIterator(const COFFObjectFile *Object,
1120 uintptr_t Ptr, int Index) {
1121 if (Object->getBytesInAddress() == 4) {
1122 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1123 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1125 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1126 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1129 static imported_symbol_iterator
1130 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1131 uintptr_t IntPtr = 0;
1132 Object->getRvaPtr(RVA, IntPtr);
1133 return makeImportedSymbolIterator(Object, IntPtr, 0);
1136 static imported_symbol_iterator
1137 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1138 uintptr_t IntPtr = 0;
1139 Object->getRvaPtr(RVA, IntPtr);
1140 // Forward the pointer to the last entry which is null.
1142 if (Object->getBytesInAddress() == 4) {
1143 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1147 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1151 return makeImportedSymbolIterator(Object, IntPtr, Index);
1154 imported_symbol_iterator
1155 ImportDirectoryEntryRef::imported_symbol_begin() const {
1156 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1160 imported_symbol_iterator
1161 ImportDirectoryEntryRef::imported_symbol_end() const {
1162 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1166 iterator_range<imported_symbol_iterator>
1167 ImportDirectoryEntryRef::imported_symbols() const {
1168 return make_range(imported_symbol_begin(), imported_symbol_end());
1171 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1172 uintptr_t IntPtr = 0;
1173 if (std::error_code EC =
1174 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1176 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1177 return std::error_code();
1181 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1182 Result = ImportTable[Index].ImportLookupTableRVA;
1183 return std::error_code();
1187 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1188 Result = ImportTable[Index].ImportAddressTableRVA;
1189 return std::error_code();
1192 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1193 const import_lookup_table_entry32 *&Result) const {
1194 uintptr_t IntPtr = 0;
1195 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1196 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1198 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1199 return std::error_code();
1202 bool DelayImportDirectoryEntryRef::
1203 operator==(const DelayImportDirectoryEntryRef &Other) const {
1204 return Table == Other.Table && Index == Other.Index;
1207 void DelayImportDirectoryEntryRef::moveNext() {
1211 imported_symbol_iterator
1212 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1213 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1217 imported_symbol_iterator
1218 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1219 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1223 iterator_range<imported_symbol_iterator>
1224 DelayImportDirectoryEntryRef::imported_symbols() const {
1225 return make_range(imported_symbol_begin(), imported_symbol_end());
1228 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1229 uintptr_t IntPtr = 0;
1230 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1232 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1233 return std::error_code();
1236 std::error_code DelayImportDirectoryEntryRef::
1237 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1239 return std::error_code();
1242 std::error_code DelayImportDirectoryEntryRef::
1243 getImportAddress(int AddrIndex, uint64_t &Result) const {
1244 uint32_t RVA = Table[Index].DelayImportAddressTable +
1245 AddrIndex * (OwningObject->is64() ? 8 : 4);
1246 uintptr_t IntPtr = 0;
1247 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1249 if (OwningObject->is64())
1250 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1252 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1253 return std::error_code();
1256 bool ExportDirectoryEntryRef::
1257 operator==(const ExportDirectoryEntryRef &Other) const {
1258 return ExportTable == Other.ExportTable && Index == Other.Index;
1261 void ExportDirectoryEntryRef::moveNext() {
1265 // Returns the name of the current export symbol. If the symbol is exported only
1266 // by ordinal, the empty string is set as a result.
1267 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1268 uintptr_t IntPtr = 0;
1269 if (std::error_code EC =
1270 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1272 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1273 return std::error_code();
1276 // Returns the starting ordinal number.
1278 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1279 Result = ExportTable->OrdinalBase;
1280 return std::error_code();
1283 // Returns the export ordinal of the current export symbol.
1284 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1285 Result = ExportTable->OrdinalBase + Index;
1286 return std::error_code();
1289 // Returns the address of the current export symbol.
1290 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1291 uintptr_t IntPtr = 0;
1292 if (std::error_code EC =
1293 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1295 const export_address_table_entry *entry =
1296 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1297 Result = entry[Index].ExportRVA;
1298 return std::error_code();
1301 // Returns the name of the current export symbol. If the symbol is exported only
1302 // by ordinal, the empty string is set as a result.
1304 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1305 uintptr_t IntPtr = 0;
1306 if (std::error_code EC =
1307 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1309 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1311 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1313 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1314 I < E; ++I, ++Offset) {
1317 if (std::error_code EC =
1318 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1320 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1321 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1323 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1324 return std::error_code();
1327 return std::error_code();
1330 bool ImportedSymbolRef::
1331 operator==(const ImportedSymbolRef &Other) const {
1332 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1333 && Index == Other.Index;
1336 void ImportedSymbolRef::moveNext() {
1341 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1344 // If a symbol is imported only by ordinal, it has no name.
1345 if (Entry32[Index].isOrdinal())
1346 return std::error_code();
1347 RVA = Entry32[Index].getHintNameRVA();
1349 if (Entry64[Index].isOrdinal())
1350 return std::error_code();
1351 RVA = Entry64[Index].getHintNameRVA();
1353 uintptr_t IntPtr = 0;
1354 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1356 // +2 because the first two bytes is hint.
1357 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1358 return std::error_code();
1361 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1364 if (Entry32[Index].isOrdinal()) {
1365 Result = Entry32[Index].getOrdinal();
1366 return std::error_code();
1368 RVA = Entry32[Index].getHintNameRVA();
1370 if (Entry64[Index].isOrdinal()) {
1371 Result = Entry64[Index].getOrdinal();
1372 return std::error_code();
1374 RVA = Entry64[Index].getHintNameRVA();
1376 uintptr_t IntPtr = 0;
1377 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1379 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1380 return std::error_code();
1383 ErrorOr<std::unique_ptr<COFFObjectFile>>
1384 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1386 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1389 return std::move(Ret);
1392 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1393 return Header == Other.Header && Index == Other.Index;
1396 void BaseRelocRef::moveNext() {
1397 // Header->BlockSize is the size of the current block, including the
1398 // size of the header itself.
1399 uint32_t Size = sizeof(*Header) +
1400 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1401 if (Size == Header->BlockSize) {
1402 // .reloc contains a list of base relocation blocks. Each block
1403 // consists of the header followed by entries. The header contains
1404 // how many entories will follow. When we reach the end of the
1405 // current block, proceed to the next block.
1406 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1407 reinterpret_cast<const uint8_t *>(Header) + Size);
1414 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1415 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1416 Type = Entry[Index].getType();
1417 return std::error_code();
1420 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1421 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1422 Result = Header->PageRVA + Entry[Index].getOffset();
1423 return std::error_code();