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.
178 Result += PE32Header->ImageBase;
179 else if (PE32PlusHeader)
180 Result += PE32PlusHeader->ImageBase;
185 SymbolRef::Type COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
186 COFFSymbolRef Symb = getCOFFSymbol(Ref);
187 int32_t SectionNumber = Symb.getSectionNumber();
189 if (Symb.isAnyUndefined())
190 return SymbolRef::ST_Unknown;
191 if (Symb.isFunctionDefinition())
192 return SymbolRef::ST_Function;
194 return SymbolRef::ST_Data;
195 if (Symb.isFileRecord())
196 return SymbolRef::ST_File;
198 // TODO: perhaps we need a new symbol type ST_Section.
199 if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
200 return SymbolRef::ST_Debug;
202 if (!COFF::isReservedSectionNumber(SectionNumber))
203 return SymbolRef::ST_Data;
205 return SymbolRef::ST_Other;
208 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
209 COFFSymbolRef Symb = getCOFFSymbol(Ref);
210 uint32_t Result = SymbolRef::SF_None;
212 if (Symb.isExternal() || Symb.isWeakExternal())
213 Result |= SymbolRef::SF_Global;
215 if (Symb.isWeakExternal())
216 Result |= SymbolRef::SF_Weak;
218 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
219 Result |= SymbolRef::SF_Absolute;
221 if (Symb.isFileRecord())
222 Result |= SymbolRef::SF_FormatSpecific;
224 if (Symb.isSectionDefinition())
225 Result |= SymbolRef::SF_FormatSpecific;
228 Result |= SymbolRef::SF_Common;
230 if (Symb.isAnyUndefined())
231 Result |= SymbolRef::SF_Undefined;
236 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
237 COFFSymbolRef Symb = getCOFFSymbol(Ref);
238 return Symb.getValue();
242 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
243 section_iterator &Result) const {
244 COFFSymbolRef Symb = getCOFFSymbol(Ref);
245 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
246 Result = section_end();
248 const coff_section *Sec = nullptr;
249 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
252 Ref.p = reinterpret_cast<uintptr_t>(Sec);
253 Result = section_iterator(SectionRef(Ref, this));
255 return std::error_code();
258 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
259 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
260 return Symb.getSectionNumber();
263 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
264 const coff_section *Sec = toSec(Ref);
266 Ref.p = reinterpret_cast<uintptr_t>(Sec);
269 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
270 StringRef &Result) const {
271 const coff_section *Sec = toSec(Ref);
272 return getSectionName(Sec, Result);
275 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
276 const coff_section *Sec = toSec(Ref);
277 uint64_t Result = Sec->VirtualAddress;
279 // The section VirtualAddress does not include ImageBase, and we want to
280 // return virtual addresses.
282 Result += PE32Header->ImageBase;
283 else if (PE32PlusHeader)
284 Result += PE32PlusHeader->ImageBase;
288 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
289 return getSectionSize(toSec(Ref));
292 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
293 StringRef &Result) const {
294 const coff_section *Sec = toSec(Ref);
295 ArrayRef<uint8_t> Res;
296 std::error_code EC = getSectionContents(Sec, Res);
297 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
301 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
302 const coff_section *Sec = toSec(Ref);
303 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
306 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
307 const coff_section *Sec = toSec(Ref);
308 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
311 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
312 const coff_section *Sec = toSec(Ref);
313 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
316 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
317 const coff_section *Sec = toSec(Ref);
318 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
319 COFF::IMAGE_SCN_MEM_READ |
320 COFF::IMAGE_SCN_MEM_WRITE;
321 return (Sec->Characteristics & BssFlags) == BssFlags;
324 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
326 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
327 assert((Offset % sizeof(coff_section)) == 0);
328 return (Offset / sizeof(coff_section)) + 1;
331 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
332 const coff_section *Sec = toSec(Ref);
333 // In COFF, a virtual section won't have any in-file
334 // content, so the file pointer to the content will be zero.
335 return Sec->PointerToRawData == 0;
338 static uint32_t getNumberOfRelocations(const coff_section *Sec,
339 MemoryBufferRef M, const uint8_t *base) {
340 // The field for the number of relocations in COFF section table is only
341 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
342 // NumberOfRelocations field, and the actual relocation count is stored in the
343 // VirtualAddress field in the first relocation entry.
344 if (Sec->hasExtendedRelocations()) {
345 const coff_relocation *FirstReloc;
346 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
347 base + Sec->PointerToRelocations)))
349 // -1 to exclude this first relocation entry.
350 return FirstReloc->VirtualAddress - 1;
352 return Sec->NumberOfRelocations;
355 static const coff_relocation *
356 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
357 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
360 auto begin = reinterpret_cast<const coff_relocation *>(
361 Base + Sec->PointerToRelocations);
362 if (Sec->hasExtendedRelocations()) {
363 // Skip the first relocation entry repurposed to store the number of
367 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
372 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
373 const coff_section *Sec = toSec(Ref);
374 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
375 if (begin && Sec->VirtualAddress != 0)
376 report_fatal_error("Sections with relocations should have an address of 0");
378 Ret.p = reinterpret_cast<uintptr_t>(begin);
379 return relocation_iterator(RelocationRef(Ret, this));
382 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
383 const coff_section *Sec = toSec(Ref);
384 const coff_relocation *I = getFirstReloc(Sec, Data, base());
386 I += getNumberOfRelocations(Sec, Data, base());
388 Ret.p = reinterpret_cast<uintptr_t>(I);
389 return relocation_iterator(RelocationRef(Ret, this));
392 // Initialize the pointer to the symbol table.
393 std::error_code COFFObjectFile::initSymbolTablePtr() {
395 if (std::error_code EC = getObject(
396 SymbolTable16, Data, base() + getPointerToSymbolTable(),
397 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
400 if (COFFBigObjHeader)
401 if (std::error_code EC = getObject(
402 SymbolTable32, Data, base() + getPointerToSymbolTable(),
403 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
406 // Find string table. The first four byte of the string table contains the
407 // total size of the string table, including the size field itself. If the
408 // string table is empty, the value of the first four byte would be 4.
409 uint32_t StringTableOffset = getPointerToSymbolTable() +
410 getNumberOfSymbols() * getSymbolTableEntrySize();
411 const uint8_t *StringTableAddr = base() + StringTableOffset;
412 const ulittle32_t *StringTableSizePtr;
413 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
415 StringTableSize = *StringTableSizePtr;
416 if (std::error_code EC =
417 getObject(StringTable, Data, StringTableAddr, StringTableSize))
420 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
421 // tools like cvtres write a size of 0 for an empty table instead of 4.
422 if (StringTableSize < 4)
425 // Check that the string table is null terminated if has any in it.
426 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
427 return object_error::parse_failed;
428 return std::error_code();
431 // Returns the file offset for the given VA.
432 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
433 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
434 : (uint64_t)PE32PlusHeader->ImageBase;
435 uint64_t Rva = Addr - ImageBase;
436 assert(Rva <= UINT32_MAX);
437 return getRvaPtr((uint32_t)Rva, Res);
440 // Returns the file offset for the given RVA.
441 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
442 for (const SectionRef &S : sections()) {
443 const coff_section *Section = getCOFFSection(S);
444 uint32_t SectionStart = Section->VirtualAddress;
445 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
446 if (SectionStart <= Addr && Addr < SectionEnd) {
447 uint32_t Offset = Addr - SectionStart;
448 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
449 return std::error_code();
452 return object_error::parse_failed;
455 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
457 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
458 StringRef &Name) const {
459 uintptr_t IntPtr = 0;
460 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
462 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
463 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
464 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
465 return std::error_code();
468 // Find the import table.
469 std::error_code COFFObjectFile::initImportTablePtr() {
470 // First, we get the RVA of the import table. If the file lacks a pointer to
471 // the import table, do nothing.
472 const data_directory *DataEntry;
473 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
474 return std::error_code();
476 // Do nothing if the pointer to import table is NULL.
477 if (DataEntry->RelativeVirtualAddress == 0)
478 return std::error_code();
480 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
481 // -1 because the last entry is the null entry.
482 NumberOfImportDirectory = DataEntry->Size /
483 sizeof(import_directory_table_entry) - 1;
485 // Find the section that contains the RVA. This is needed because the RVA is
486 // the import table's memory address which is different from its file offset.
487 uintptr_t IntPtr = 0;
488 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
490 ImportDirectory = reinterpret_cast<
491 const import_directory_table_entry *>(IntPtr);
492 return std::error_code();
495 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
496 std::error_code COFFObjectFile::initDelayImportTablePtr() {
497 const data_directory *DataEntry;
498 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
499 return std::error_code();
500 if (DataEntry->RelativeVirtualAddress == 0)
501 return std::error_code();
503 uint32_t RVA = DataEntry->RelativeVirtualAddress;
504 NumberOfDelayImportDirectory = DataEntry->Size /
505 sizeof(delay_import_directory_table_entry) - 1;
507 uintptr_t IntPtr = 0;
508 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
510 DelayImportDirectory = reinterpret_cast<
511 const delay_import_directory_table_entry *>(IntPtr);
512 return std::error_code();
515 // Find the export table.
516 std::error_code COFFObjectFile::initExportTablePtr() {
517 // First, we get the RVA of the export table. If the file lacks a pointer to
518 // the export table, do nothing.
519 const data_directory *DataEntry;
520 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
521 return std::error_code();
523 // Do nothing if the pointer to export table is NULL.
524 if (DataEntry->RelativeVirtualAddress == 0)
525 return std::error_code();
527 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
528 uintptr_t IntPtr = 0;
529 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
532 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
533 return std::error_code();
536 std::error_code COFFObjectFile::initBaseRelocPtr() {
537 const data_directory *DataEntry;
538 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
539 return std::error_code();
540 if (DataEntry->RelativeVirtualAddress == 0)
541 return std::error_code();
543 uintptr_t IntPtr = 0;
544 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
546 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
548 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
549 IntPtr + DataEntry->Size);
550 return std::error_code();
553 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
554 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
555 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
556 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
557 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
558 ImportDirectory(nullptr), NumberOfImportDirectory(0),
559 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
560 ExportDirectory(nullptr), BaseRelocHeader(nullptr),
561 BaseRelocEnd(nullptr) {
562 // Check that we at least have enough room for a header.
563 if (!checkSize(Data, EC, sizeof(coff_file_header)))
566 // The current location in the file where we are looking at.
569 // PE header is optional and is present only in executables. If it exists,
570 // it is placed right after COFF header.
571 bool HasPEHeader = false;
573 // Check if this is a PE/COFF file.
574 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
575 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
576 // PE signature to find 'normal' COFF header.
577 const auto *DH = reinterpret_cast<const dos_header *>(base());
578 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
579 CurPtr = DH->AddressOfNewExeHeader;
580 // Check the PE magic bytes. ("PE\0\0")
581 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
582 EC = object_error::parse_failed;
585 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
590 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
593 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
594 // import libraries share a common prefix but bigobj is more restrictive.
595 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
596 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
597 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
598 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
601 // Verify that we are dealing with bigobj.
602 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
603 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
604 sizeof(COFF::BigObjMagic)) == 0) {
605 COFFHeader = nullptr;
606 CurPtr += sizeof(coff_bigobj_file_header);
608 // It's not a bigobj.
609 COFFBigObjHeader = nullptr;
613 // The prior checkSize call may have failed. This isn't a hard error
614 // because we were just trying to sniff out bigobj.
615 EC = std::error_code();
616 CurPtr += sizeof(coff_file_header);
618 if (COFFHeader->isImportLibrary())
623 const pe32_header *Header;
624 if ((EC = getObject(Header, Data, base() + CurPtr)))
627 const uint8_t *DataDirAddr;
628 uint64_t DataDirSize;
629 if (Header->Magic == COFF::PE32Header::PE32) {
631 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
632 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
633 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
634 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
635 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
636 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
638 // It's neither PE32 nor PE32+.
639 EC = object_error::parse_failed;
642 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
644 CurPtr += COFFHeader->SizeOfOptionalHeader;
647 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
648 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
651 // Initialize the pointer to the symbol table.
652 if (getPointerToSymbolTable() != 0) {
653 if ((EC = initSymbolTablePtr()))
656 // We had better not have any symbols if we don't have a symbol table.
657 if (getNumberOfSymbols() != 0) {
658 EC = object_error::parse_failed;
663 // Initialize the pointer to the beginning of the import table.
664 if ((EC = initImportTablePtr()))
666 if ((EC = initDelayImportTablePtr()))
669 // Initialize the pointer to the export table.
670 if ((EC = initExportTablePtr()))
673 // Initialize the pointer to the base relocation table.
674 if ((EC = initBaseRelocPtr()))
677 EC = std::error_code();
680 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
682 Ret.p = getSymbolTable();
683 return basic_symbol_iterator(SymbolRef(Ret, this));
686 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
687 // The symbol table ends where the string table begins.
689 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
690 return basic_symbol_iterator(SymbolRef(Ret, this));
693 import_directory_iterator COFFObjectFile::import_directory_begin() const {
694 return import_directory_iterator(
695 ImportDirectoryEntryRef(ImportDirectory, 0, this));
698 import_directory_iterator COFFObjectFile::import_directory_end() const {
699 return import_directory_iterator(
700 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
703 delay_import_directory_iterator
704 COFFObjectFile::delay_import_directory_begin() const {
705 return delay_import_directory_iterator(
706 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
709 delay_import_directory_iterator
710 COFFObjectFile::delay_import_directory_end() const {
711 return delay_import_directory_iterator(
712 DelayImportDirectoryEntryRef(
713 DelayImportDirectory, NumberOfDelayImportDirectory, this));
716 export_directory_iterator COFFObjectFile::export_directory_begin() const {
717 return export_directory_iterator(
718 ExportDirectoryEntryRef(ExportDirectory, 0, this));
721 export_directory_iterator COFFObjectFile::export_directory_end() const {
722 if (!ExportDirectory)
723 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
724 ExportDirectoryEntryRef Ref(ExportDirectory,
725 ExportDirectory->AddressTableEntries, this);
726 return export_directory_iterator(Ref);
729 section_iterator COFFObjectFile::section_begin() const {
731 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
732 return section_iterator(SectionRef(Ret, this));
735 section_iterator COFFObjectFile::section_end() const {
738 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
739 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
740 return section_iterator(SectionRef(Ret, this));
743 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
744 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
747 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
748 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
751 uint8_t COFFObjectFile::getBytesInAddress() const {
752 return getArch() == Triple::x86_64 ? 8 : 4;
755 StringRef COFFObjectFile::getFileFormatName() const {
756 switch(getMachine()) {
757 case COFF::IMAGE_FILE_MACHINE_I386:
759 case COFF::IMAGE_FILE_MACHINE_AMD64:
760 return "COFF-x86-64";
761 case COFF::IMAGE_FILE_MACHINE_ARMNT:
763 case COFF::IMAGE_FILE_MACHINE_ARM64:
766 return "COFF-<unknown arch>";
770 unsigned COFFObjectFile::getArch() const {
771 switch (getMachine()) {
772 case COFF::IMAGE_FILE_MACHINE_I386:
774 case COFF::IMAGE_FILE_MACHINE_AMD64:
775 return Triple::x86_64;
776 case COFF::IMAGE_FILE_MACHINE_ARMNT:
777 return Triple::thumb;
778 case COFF::IMAGE_FILE_MACHINE_ARM64:
779 return Triple::aarch64;
781 return Triple::UnknownArch;
785 iterator_range<import_directory_iterator>
786 COFFObjectFile::import_directories() const {
787 return make_range(import_directory_begin(), import_directory_end());
790 iterator_range<delay_import_directory_iterator>
791 COFFObjectFile::delay_import_directories() const {
792 return make_range(delay_import_directory_begin(),
793 delay_import_directory_end());
796 iterator_range<export_directory_iterator>
797 COFFObjectFile::export_directories() const {
798 return make_range(export_directory_begin(), export_directory_end());
801 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
802 return make_range(base_reloc_begin(), base_reloc_end());
805 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
807 return std::error_code();
811 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
812 Res = PE32PlusHeader;
813 return std::error_code();
817 COFFObjectFile::getDataDirectory(uint32_t Index,
818 const data_directory *&Res) const {
819 // Error if if there's no data directory or the index is out of range.
820 if (!DataDirectory) {
822 return object_error::parse_failed;
824 assert(PE32Header || PE32PlusHeader);
825 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
826 : PE32PlusHeader->NumberOfRvaAndSize;
827 if (Index >= NumEnt) {
829 return object_error::parse_failed;
831 Res = &DataDirectory[Index];
832 return std::error_code();
835 std::error_code COFFObjectFile::getSection(int32_t Index,
836 const coff_section *&Result) const {
838 if (COFF::isReservedSectionNumber(Index))
839 return std::error_code();
840 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
841 // We already verified the section table data, so no need to check again.
842 Result = SectionTable + (Index - 1);
843 return std::error_code();
845 return object_error::parse_failed;
848 std::error_code COFFObjectFile::getString(uint32_t Offset,
849 StringRef &Result) const {
850 if (StringTableSize <= 4)
851 // Tried to get a string from an empty string table.
852 return object_error::parse_failed;
853 if (Offset >= StringTableSize)
854 return object_error::unexpected_eof;
855 Result = StringRef(StringTable + Offset);
856 return std::error_code();
859 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
860 StringRef &Res) const {
861 return getSymbolName(Symbol.getGeneric(), Res);
864 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
865 StringRef &Res) const {
866 // Check for string table entry. First 4 bytes are 0.
867 if (Symbol->Name.Offset.Zeroes == 0) {
868 if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
870 return std::error_code();
873 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
874 // Null terminated, let ::strlen figure out the length.
875 Res = StringRef(Symbol->Name.ShortName);
877 // Not null terminated, use all 8 bytes.
878 Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
879 return std::error_code();
883 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
884 const uint8_t *Aux = nullptr;
886 size_t SymbolSize = getSymbolTableEntrySize();
887 if (Symbol.getNumberOfAuxSymbols() > 0) {
888 // AUX data comes immediately after the symbol in COFF
889 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
891 // Verify that the Aux symbol points to a valid entry in the symbol table.
892 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
893 if (Offset < getPointerToSymbolTable() ||
895 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
896 report_fatal_error("Aux Symbol data was outside of symbol table.");
898 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
899 "Aux Symbol data did not point to the beginning of a symbol");
902 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
905 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
906 StringRef &Res) const {
908 if (Sec->Name[COFF::NameSize - 1] == 0)
909 // Null terminated, let ::strlen figure out the length.
912 // Not null terminated, use all 8 bytes.
913 Name = StringRef(Sec->Name, COFF::NameSize);
915 // Check for string table entry. First byte is '/'.
916 if (Name.startswith("/")) {
918 if (Name.startswith("//")) {
919 if (decodeBase64StringEntry(Name.substr(2), Offset))
920 return object_error::parse_failed;
922 if (Name.substr(1).getAsInteger(10, Offset))
923 return object_error::parse_failed;
925 if (std::error_code EC = getString(Offset, Name))
930 return std::error_code();
933 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
934 // SizeOfRawData and VirtualSize change what they represent depending on
935 // whether or not we have an executable image.
937 // For object files, SizeOfRawData contains the size of section's data;
938 // VirtualSize should be zero but isn't due to buggy COFF writers.
940 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
941 // actual section size is in VirtualSize. It is possible for VirtualSize to
942 // be greater than SizeOfRawData; the contents past that point should be
943 // considered to be zero.
945 return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
946 return Sec->SizeOfRawData;
950 COFFObjectFile::getSectionContents(const coff_section *Sec,
951 ArrayRef<uint8_t> &Res) const {
952 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
953 // don't do anything interesting for them.
954 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
955 "BSS sections don't have contents!");
956 // The only thing that we need to verify is that the contents is contained
957 // within the file bounds. We don't need to make sure it doesn't cover other
958 // data, as there's nothing that says that is not allowed.
959 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
960 uint32_t SectionSize = getSectionSize(Sec);
961 if (checkOffset(Data, ConStart, SectionSize))
962 return object_error::parse_failed;
963 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
964 return std::error_code();
967 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
968 return reinterpret_cast<const coff_relocation*>(Rel.p);
971 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
972 Rel.p = reinterpret_cast<uintptr_t>(
973 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
976 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
977 const coff_relocation *R = toRel(Rel);
978 return R->VirtualAddress;
981 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
982 const coff_relocation *R = toRel(Rel);
984 if (R->SymbolTableIndex >= getNumberOfSymbols())
987 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
988 else if (SymbolTable32)
989 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
991 llvm_unreachable("no symbol table pointer!");
992 return symbol_iterator(SymbolRef(Ref, this));
995 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
996 const coff_relocation* R = toRel(Rel);
1000 const coff_section *
1001 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1002 return toSec(Section.getRawDataRefImpl());
1005 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1007 return toSymb<coff_symbol16>(Ref);
1009 return toSymb<coff_symbol32>(Ref);
1010 llvm_unreachable("no symbol table pointer!");
1013 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1014 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1017 const coff_relocation *
1018 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1019 return toRel(Reloc.getRawDataRefImpl());
1022 iterator_range<const coff_relocation *>
1023 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1024 const coff_relocation *I = getFirstReloc(Sec, Data, base());
1025 const coff_relocation *E = I;
1027 E += getNumberOfRelocations(Sec, Data, base());
1028 return make_range(I, E);
1031 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1032 case COFF::reloc_type: \
1033 Res = #reloc_type; \
1036 void COFFObjectFile::getRelocationTypeName(
1037 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1038 const coff_relocation *Reloc = toRel(Rel);
1040 switch (getMachine()) {
1041 case COFF::IMAGE_FILE_MACHINE_AMD64:
1042 switch (Reloc->Type) {
1043 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1044 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1045 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1046 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1047 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1048 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1049 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1050 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1051 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1052 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1053 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1054 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1055 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1056 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1057 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1058 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1059 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1064 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1065 switch (Reloc->Type) {
1066 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1067 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1068 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1069 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1070 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1071 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1072 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1073 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1074 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1075 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1076 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1077 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1078 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1079 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1080 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1085 case COFF::IMAGE_FILE_MACHINE_I386:
1086 switch (Reloc->Type) {
1087 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1088 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1089 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1090 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1091 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1092 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1093 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1094 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1095 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1096 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1097 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1105 Result.append(Res.begin(), Res.end());
1108 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1110 bool COFFObjectFile::isRelocatableObject() const {
1111 return !DataDirectory;
1114 bool ImportDirectoryEntryRef::
1115 operator==(const ImportDirectoryEntryRef &Other) const {
1116 return ImportTable == Other.ImportTable && Index == Other.Index;
1119 void ImportDirectoryEntryRef::moveNext() {
1123 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1124 const import_directory_table_entry *&Result) const {
1125 Result = ImportTable + Index;
1126 return std::error_code();
1129 static imported_symbol_iterator
1130 makeImportedSymbolIterator(const COFFObjectFile *Object,
1131 uintptr_t Ptr, int Index) {
1132 if (Object->getBytesInAddress() == 4) {
1133 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1134 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1136 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1137 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1140 static imported_symbol_iterator
1141 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1142 uintptr_t IntPtr = 0;
1143 Object->getRvaPtr(RVA, IntPtr);
1144 return makeImportedSymbolIterator(Object, IntPtr, 0);
1147 static imported_symbol_iterator
1148 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1149 uintptr_t IntPtr = 0;
1150 Object->getRvaPtr(RVA, IntPtr);
1151 // Forward the pointer to the last entry which is null.
1153 if (Object->getBytesInAddress() == 4) {
1154 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1158 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1162 return makeImportedSymbolIterator(Object, IntPtr, Index);
1165 imported_symbol_iterator
1166 ImportDirectoryEntryRef::imported_symbol_begin() const {
1167 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1171 imported_symbol_iterator
1172 ImportDirectoryEntryRef::imported_symbol_end() const {
1173 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1177 iterator_range<imported_symbol_iterator>
1178 ImportDirectoryEntryRef::imported_symbols() const {
1179 return make_range(imported_symbol_begin(), imported_symbol_end());
1182 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1183 uintptr_t IntPtr = 0;
1184 if (std::error_code EC =
1185 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1187 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1188 return std::error_code();
1192 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1193 Result = ImportTable[Index].ImportLookupTableRVA;
1194 return std::error_code();
1198 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1199 Result = ImportTable[Index].ImportAddressTableRVA;
1200 return std::error_code();
1203 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1204 const import_lookup_table_entry32 *&Result) const {
1205 uintptr_t IntPtr = 0;
1206 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1207 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1209 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1210 return std::error_code();
1213 bool DelayImportDirectoryEntryRef::
1214 operator==(const DelayImportDirectoryEntryRef &Other) const {
1215 return Table == Other.Table && Index == Other.Index;
1218 void DelayImportDirectoryEntryRef::moveNext() {
1222 imported_symbol_iterator
1223 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1224 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1228 imported_symbol_iterator
1229 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1230 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1234 iterator_range<imported_symbol_iterator>
1235 DelayImportDirectoryEntryRef::imported_symbols() const {
1236 return make_range(imported_symbol_begin(), imported_symbol_end());
1239 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1240 uintptr_t IntPtr = 0;
1241 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1243 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1244 return std::error_code();
1247 std::error_code DelayImportDirectoryEntryRef::
1248 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1250 return std::error_code();
1253 std::error_code DelayImportDirectoryEntryRef::
1254 getImportAddress(int AddrIndex, uint64_t &Result) const {
1255 uint32_t RVA = Table[Index].DelayImportAddressTable +
1256 AddrIndex * (OwningObject->is64() ? 8 : 4);
1257 uintptr_t IntPtr = 0;
1258 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1260 if (OwningObject->is64())
1261 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1263 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1264 return std::error_code();
1267 bool ExportDirectoryEntryRef::
1268 operator==(const ExportDirectoryEntryRef &Other) const {
1269 return ExportTable == Other.ExportTable && Index == Other.Index;
1272 void ExportDirectoryEntryRef::moveNext() {
1276 // Returns the name of the current export symbol. If the symbol is exported only
1277 // by ordinal, the empty string is set as a result.
1278 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1279 uintptr_t IntPtr = 0;
1280 if (std::error_code EC =
1281 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1283 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1284 return std::error_code();
1287 // Returns the starting ordinal number.
1289 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1290 Result = ExportTable->OrdinalBase;
1291 return std::error_code();
1294 // Returns the export ordinal of the current export symbol.
1295 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1296 Result = ExportTable->OrdinalBase + Index;
1297 return std::error_code();
1300 // Returns the address of the current export symbol.
1301 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1302 uintptr_t IntPtr = 0;
1303 if (std::error_code EC =
1304 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1306 const export_address_table_entry *entry =
1307 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1308 Result = entry[Index].ExportRVA;
1309 return std::error_code();
1312 // Returns the name of the current export symbol. If the symbol is exported only
1313 // by ordinal, the empty string is set as a result.
1315 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1316 uintptr_t IntPtr = 0;
1317 if (std::error_code EC =
1318 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1320 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1322 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1324 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1325 I < E; ++I, ++Offset) {
1328 if (std::error_code EC =
1329 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1331 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1332 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1334 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1335 return std::error_code();
1338 return std::error_code();
1341 bool ImportedSymbolRef::
1342 operator==(const ImportedSymbolRef &Other) const {
1343 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1344 && Index == Other.Index;
1347 void ImportedSymbolRef::moveNext() {
1352 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1355 // If a symbol is imported only by ordinal, it has no name.
1356 if (Entry32[Index].isOrdinal())
1357 return std::error_code();
1358 RVA = Entry32[Index].getHintNameRVA();
1360 if (Entry64[Index].isOrdinal())
1361 return std::error_code();
1362 RVA = Entry64[Index].getHintNameRVA();
1364 uintptr_t IntPtr = 0;
1365 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1367 // +2 because the first two bytes is hint.
1368 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1369 return std::error_code();
1372 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1375 if (Entry32[Index].isOrdinal()) {
1376 Result = Entry32[Index].getOrdinal();
1377 return std::error_code();
1379 RVA = Entry32[Index].getHintNameRVA();
1381 if (Entry64[Index].isOrdinal()) {
1382 Result = Entry64[Index].getOrdinal();
1383 return std::error_code();
1385 RVA = Entry64[Index].getHintNameRVA();
1387 uintptr_t IntPtr = 0;
1388 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1390 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1391 return std::error_code();
1394 ErrorOr<std::unique_ptr<COFFObjectFile>>
1395 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1397 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1400 return std::move(Ret);
1403 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1404 return Header == Other.Header && Index == Other.Index;
1407 void BaseRelocRef::moveNext() {
1408 // Header->BlockSize is the size of the current block, including the
1409 // size of the header itself.
1410 uint32_t Size = sizeof(*Header) +
1411 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1412 if (Size == Header->BlockSize) {
1413 // .reloc contains a list of base relocation blocks. Each block
1414 // consists of the header followed by entries. The header contains
1415 // how many entories will follow. When we reach the end of the
1416 // current block, proceed to the next block.
1417 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1418 reinterpret_cast<const uint8_t *>(Header) + Size);
1425 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1426 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1427 Type = Entry[Index].getType();
1428 return std::error_code();
1431 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1432 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1433 Result = Header->PageRVA + Entry[Index].getOffset();
1434 return std::error_code();