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.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION)
190 return SymbolRef::ST_Function;
191 if (Symb.isAnyUndefined())
192 return SymbolRef::ST_Unknown;
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();
241 ErrorOr<section_iterator>
242 COFFObjectFile::getSymbolSection(DataRefImpl Ref) const {
243 COFFSymbolRef Symb = getCOFFSymbol(Ref);
244 if (COFF::isReservedSectionNumber(Symb.getSectionNumber()))
245 return section_end();
246 const coff_section *Sec = nullptr;
247 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
250 Ret.p = reinterpret_cast<uintptr_t>(Sec);
251 return section_iterator(SectionRef(Ret, this));
254 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
255 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
256 return Symb.getSectionNumber();
259 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
260 const coff_section *Sec = toSec(Ref);
262 Ref.p = reinterpret_cast<uintptr_t>(Sec);
265 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
266 StringRef &Result) const {
267 const coff_section *Sec = toSec(Ref);
268 return getSectionName(Sec, Result);
271 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
272 const coff_section *Sec = toSec(Ref);
273 uint64_t Result = Sec->VirtualAddress;
275 // The section VirtualAddress does not include ImageBase, and we want to
276 // return virtual addresses.
278 Result += PE32Header->ImageBase;
279 else if (PE32PlusHeader)
280 Result += PE32PlusHeader->ImageBase;
284 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
285 return getSectionSize(toSec(Ref));
288 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
289 StringRef &Result) const {
290 const coff_section *Sec = toSec(Ref);
291 ArrayRef<uint8_t> Res;
292 std::error_code EC = getSectionContents(Sec, Res);
293 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
297 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
298 const coff_section *Sec = toSec(Ref);
299 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
302 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
303 const coff_section *Sec = toSec(Ref);
304 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
307 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
308 const coff_section *Sec = toSec(Ref);
309 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
312 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
313 const coff_section *Sec = toSec(Ref);
314 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
315 COFF::IMAGE_SCN_MEM_READ |
316 COFF::IMAGE_SCN_MEM_WRITE;
317 return (Sec->Characteristics & BssFlags) == BssFlags;
320 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
322 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
323 assert((Offset % sizeof(coff_section)) == 0);
324 return (Offset / sizeof(coff_section)) + 1;
327 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
328 const coff_section *Sec = toSec(Ref);
329 // In COFF, a virtual section won't have any in-file
330 // content, so the file pointer to the content will be zero.
331 return Sec->PointerToRawData == 0;
334 static uint32_t getNumberOfRelocations(const coff_section *Sec,
335 MemoryBufferRef M, const uint8_t *base) {
336 // The field for the number of relocations in COFF section table is only
337 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
338 // NumberOfRelocations field, and the actual relocation count is stored in the
339 // VirtualAddress field in the first relocation entry.
340 if (Sec->hasExtendedRelocations()) {
341 const coff_relocation *FirstReloc;
342 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
343 base + Sec->PointerToRelocations)))
345 // -1 to exclude this first relocation entry.
346 return FirstReloc->VirtualAddress - 1;
348 return Sec->NumberOfRelocations;
351 static const coff_relocation *
352 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
353 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
356 auto begin = reinterpret_cast<const coff_relocation *>(
357 Base + Sec->PointerToRelocations);
358 if (Sec->hasExtendedRelocations()) {
359 // Skip the first relocation entry repurposed to store the number of
363 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
368 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
369 const coff_section *Sec = toSec(Ref);
370 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
371 if (begin && Sec->VirtualAddress != 0)
372 report_fatal_error("Sections with relocations should have an address of 0");
374 Ret.p = reinterpret_cast<uintptr_t>(begin);
375 return relocation_iterator(RelocationRef(Ret, this));
378 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
379 const coff_section *Sec = toSec(Ref);
380 const coff_relocation *I = getFirstReloc(Sec, Data, base());
382 I += getNumberOfRelocations(Sec, Data, base());
384 Ret.p = reinterpret_cast<uintptr_t>(I);
385 return relocation_iterator(RelocationRef(Ret, this));
388 // Initialize the pointer to the symbol table.
389 std::error_code COFFObjectFile::initSymbolTablePtr() {
391 if (std::error_code EC = getObject(
392 SymbolTable16, Data, base() + getPointerToSymbolTable(),
393 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
396 if (COFFBigObjHeader)
397 if (std::error_code EC = getObject(
398 SymbolTable32, Data, base() + getPointerToSymbolTable(),
399 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
402 // Find string table. The first four byte of the string table contains the
403 // total size of the string table, including the size field itself. If the
404 // string table is empty, the value of the first four byte would be 4.
405 uint32_t StringTableOffset = getPointerToSymbolTable() +
406 getNumberOfSymbols() * getSymbolTableEntrySize();
407 const uint8_t *StringTableAddr = base() + StringTableOffset;
408 const ulittle32_t *StringTableSizePtr;
409 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
411 StringTableSize = *StringTableSizePtr;
412 if (std::error_code EC =
413 getObject(StringTable, Data, StringTableAddr, StringTableSize))
416 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
417 // tools like cvtres write a size of 0 for an empty table instead of 4.
418 if (StringTableSize < 4)
421 // Check that the string table is null terminated if has any in it.
422 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
423 return object_error::parse_failed;
424 return std::error_code();
427 // Returns the file offset for the given VA.
428 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
429 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
430 : (uint64_t)PE32PlusHeader->ImageBase;
431 uint64_t Rva = Addr - ImageBase;
432 assert(Rva <= UINT32_MAX);
433 return getRvaPtr((uint32_t)Rva, Res);
436 // Returns the file offset for the given RVA.
437 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
438 for (const SectionRef &S : sections()) {
439 const coff_section *Section = getCOFFSection(S);
440 uint32_t SectionStart = Section->VirtualAddress;
441 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
442 if (SectionStart <= Addr && Addr < SectionEnd) {
443 uint32_t Offset = Addr - SectionStart;
444 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
445 return std::error_code();
448 return object_error::parse_failed;
451 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
453 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
454 StringRef &Name) const {
455 uintptr_t IntPtr = 0;
456 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
458 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
459 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
460 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
461 return std::error_code();
464 // Find the import table.
465 std::error_code COFFObjectFile::initImportTablePtr() {
466 // First, we get the RVA of the import table. If the file lacks a pointer to
467 // the import table, do nothing.
468 const data_directory *DataEntry;
469 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
470 return std::error_code();
472 // Do nothing if the pointer to import table is NULL.
473 if (DataEntry->RelativeVirtualAddress == 0)
474 return std::error_code();
476 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
477 // -1 because the last entry is the null entry.
478 NumberOfImportDirectory = DataEntry->Size /
479 sizeof(import_directory_table_entry) - 1;
481 // Find the section that contains the RVA. This is needed because the RVA is
482 // the import table's memory address which is different from its file offset.
483 uintptr_t IntPtr = 0;
484 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
486 ImportDirectory = reinterpret_cast<
487 const import_directory_table_entry *>(IntPtr);
488 return std::error_code();
491 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
492 std::error_code COFFObjectFile::initDelayImportTablePtr() {
493 const data_directory *DataEntry;
494 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
495 return std::error_code();
496 if (DataEntry->RelativeVirtualAddress == 0)
497 return std::error_code();
499 uint32_t RVA = DataEntry->RelativeVirtualAddress;
500 NumberOfDelayImportDirectory = DataEntry->Size /
501 sizeof(delay_import_directory_table_entry) - 1;
503 uintptr_t IntPtr = 0;
504 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
506 DelayImportDirectory = reinterpret_cast<
507 const delay_import_directory_table_entry *>(IntPtr);
508 return std::error_code();
511 // Find the export table.
512 std::error_code COFFObjectFile::initExportTablePtr() {
513 // First, we get the RVA of the export table. If the file lacks a pointer to
514 // the export table, do nothing.
515 const data_directory *DataEntry;
516 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
517 return std::error_code();
519 // Do nothing if the pointer to export table is NULL.
520 if (DataEntry->RelativeVirtualAddress == 0)
521 return std::error_code();
523 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
524 uintptr_t IntPtr = 0;
525 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
528 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
529 return std::error_code();
532 std::error_code COFFObjectFile::initBaseRelocPtr() {
533 const data_directory *DataEntry;
534 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
535 return std::error_code();
536 if (DataEntry->RelativeVirtualAddress == 0)
537 return std::error_code();
539 uintptr_t IntPtr = 0;
540 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
542 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
544 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
545 IntPtr + DataEntry->Size);
546 return std::error_code();
549 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
550 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
551 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
552 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
553 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
554 ImportDirectory(nullptr), NumberOfImportDirectory(0),
555 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
556 ExportDirectory(nullptr), BaseRelocHeader(nullptr),
557 BaseRelocEnd(nullptr) {
558 // Check that we at least have enough room for a header.
559 if (!checkSize(Data, EC, sizeof(coff_file_header)))
562 // The current location in the file where we are looking at.
565 // PE header is optional and is present only in executables. If it exists,
566 // it is placed right after COFF header.
567 bool HasPEHeader = false;
569 // Check if this is a PE/COFF file.
570 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
571 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
572 // PE signature to find 'normal' COFF header.
573 const auto *DH = reinterpret_cast<const dos_header *>(base());
574 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
575 CurPtr = DH->AddressOfNewExeHeader;
576 // Check the PE magic bytes. ("PE\0\0")
577 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
578 EC = object_error::parse_failed;
581 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
586 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
589 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
590 // import libraries share a common prefix but bigobj is more restrictive.
591 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
592 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
593 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
594 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
597 // Verify that we are dealing with bigobj.
598 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
599 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
600 sizeof(COFF::BigObjMagic)) == 0) {
601 COFFHeader = nullptr;
602 CurPtr += sizeof(coff_bigobj_file_header);
604 // It's not a bigobj.
605 COFFBigObjHeader = nullptr;
609 // The prior checkSize call may have failed. This isn't a hard error
610 // because we were just trying to sniff out bigobj.
611 EC = std::error_code();
612 CurPtr += sizeof(coff_file_header);
614 if (COFFHeader->isImportLibrary())
619 const pe32_header *Header;
620 if ((EC = getObject(Header, Data, base() + CurPtr)))
623 const uint8_t *DataDirAddr;
624 uint64_t DataDirSize;
625 if (Header->Magic == COFF::PE32Header::PE32) {
627 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
628 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
629 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
630 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
631 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
632 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
634 // It's neither PE32 nor PE32+.
635 EC = object_error::parse_failed;
638 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
640 CurPtr += COFFHeader->SizeOfOptionalHeader;
643 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
644 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
647 // Initialize the pointer to the symbol table.
648 if (getPointerToSymbolTable() != 0) {
649 if ((EC = initSymbolTablePtr()))
652 // We had better not have any symbols if we don't have a symbol table.
653 if (getNumberOfSymbols() != 0) {
654 EC = object_error::parse_failed;
659 // Initialize the pointer to the beginning of the import table.
660 if ((EC = initImportTablePtr()))
662 if ((EC = initDelayImportTablePtr()))
665 // Initialize the pointer to the export table.
666 if ((EC = initExportTablePtr()))
669 // Initialize the pointer to the base relocation table.
670 if ((EC = initBaseRelocPtr()))
673 EC = std::error_code();
676 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
678 Ret.p = getSymbolTable();
679 return basic_symbol_iterator(SymbolRef(Ret, this));
682 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
683 // The symbol table ends where the string table begins.
685 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
686 return basic_symbol_iterator(SymbolRef(Ret, this));
689 import_directory_iterator COFFObjectFile::import_directory_begin() const {
690 return import_directory_iterator(
691 ImportDirectoryEntryRef(ImportDirectory, 0, this));
694 import_directory_iterator COFFObjectFile::import_directory_end() const {
695 return import_directory_iterator(
696 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
699 delay_import_directory_iterator
700 COFFObjectFile::delay_import_directory_begin() const {
701 return delay_import_directory_iterator(
702 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
705 delay_import_directory_iterator
706 COFFObjectFile::delay_import_directory_end() const {
707 return delay_import_directory_iterator(
708 DelayImportDirectoryEntryRef(
709 DelayImportDirectory, NumberOfDelayImportDirectory, this));
712 export_directory_iterator COFFObjectFile::export_directory_begin() const {
713 return export_directory_iterator(
714 ExportDirectoryEntryRef(ExportDirectory, 0, this));
717 export_directory_iterator COFFObjectFile::export_directory_end() const {
718 if (!ExportDirectory)
719 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
720 ExportDirectoryEntryRef Ref(ExportDirectory,
721 ExportDirectory->AddressTableEntries, this);
722 return export_directory_iterator(Ref);
725 section_iterator COFFObjectFile::section_begin() const {
727 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
728 return section_iterator(SectionRef(Ret, this));
731 section_iterator COFFObjectFile::section_end() const {
734 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
735 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
736 return section_iterator(SectionRef(Ret, this));
739 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
740 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
743 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
744 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
747 uint8_t COFFObjectFile::getBytesInAddress() const {
748 return getArch() == Triple::x86_64 ? 8 : 4;
751 StringRef COFFObjectFile::getFileFormatName() const {
752 switch(getMachine()) {
753 case COFF::IMAGE_FILE_MACHINE_I386:
755 case COFF::IMAGE_FILE_MACHINE_AMD64:
756 return "COFF-x86-64";
757 case COFF::IMAGE_FILE_MACHINE_ARMNT:
759 case COFF::IMAGE_FILE_MACHINE_ARM64:
762 return "COFF-<unknown arch>";
766 unsigned COFFObjectFile::getArch() const {
767 switch (getMachine()) {
768 case COFF::IMAGE_FILE_MACHINE_I386:
770 case COFF::IMAGE_FILE_MACHINE_AMD64:
771 return Triple::x86_64;
772 case COFF::IMAGE_FILE_MACHINE_ARMNT:
773 return Triple::thumb;
774 case COFF::IMAGE_FILE_MACHINE_ARM64:
775 return Triple::aarch64;
777 return Triple::UnknownArch;
781 iterator_range<import_directory_iterator>
782 COFFObjectFile::import_directories() const {
783 return make_range(import_directory_begin(), import_directory_end());
786 iterator_range<delay_import_directory_iterator>
787 COFFObjectFile::delay_import_directories() const {
788 return make_range(delay_import_directory_begin(),
789 delay_import_directory_end());
792 iterator_range<export_directory_iterator>
793 COFFObjectFile::export_directories() const {
794 return make_range(export_directory_begin(), export_directory_end());
797 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
798 return make_range(base_reloc_begin(), base_reloc_end());
801 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
803 return std::error_code();
807 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
808 Res = PE32PlusHeader;
809 return std::error_code();
813 COFFObjectFile::getDataDirectory(uint32_t Index,
814 const data_directory *&Res) const {
815 // Error if if there's no data directory or the index is out of range.
816 if (!DataDirectory) {
818 return object_error::parse_failed;
820 assert(PE32Header || PE32PlusHeader);
821 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
822 : PE32PlusHeader->NumberOfRvaAndSize;
823 if (Index >= NumEnt) {
825 return object_error::parse_failed;
827 Res = &DataDirectory[Index];
828 return std::error_code();
831 std::error_code COFFObjectFile::getSection(int32_t Index,
832 const coff_section *&Result) const {
834 if (COFF::isReservedSectionNumber(Index))
835 return std::error_code();
836 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
837 // We already verified the section table data, so no need to check again.
838 Result = SectionTable + (Index - 1);
839 return std::error_code();
841 return object_error::parse_failed;
844 std::error_code COFFObjectFile::getString(uint32_t Offset,
845 StringRef &Result) const {
846 if (StringTableSize <= 4)
847 // Tried to get a string from an empty string table.
848 return object_error::parse_failed;
849 if (Offset >= StringTableSize)
850 return object_error::unexpected_eof;
851 Result = StringRef(StringTable + Offset);
852 return std::error_code();
855 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
856 StringRef &Res) const {
857 return getSymbolName(Symbol.getGeneric(), Res);
860 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
861 StringRef &Res) const {
862 // Check for string table entry. First 4 bytes are 0.
863 if (Symbol->Name.Offset.Zeroes == 0) {
864 if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
866 return std::error_code();
869 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
870 // Null terminated, let ::strlen figure out the length.
871 Res = StringRef(Symbol->Name.ShortName);
873 // Not null terminated, use all 8 bytes.
874 Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
875 return std::error_code();
879 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
880 const uint8_t *Aux = nullptr;
882 size_t SymbolSize = getSymbolTableEntrySize();
883 if (Symbol.getNumberOfAuxSymbols() > 0) {
884 // AUX data comes immediately after the symbol in COFF
885 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
887 // Verify that the Aux symbol points to a valid entry in the symbol table.
888 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
889 if (Offset < getPointerToSymbolTable() ||
891 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
892 report_fatal_error("Aux Symbol data was outside of symbol table.");
894 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
895 "Aux Symbol data did not point to the beginning of a symbol");
898 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
901 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
902 StringRef &Res) const {
904 if (Sec->Name[COFF::NameSize - 1] == 0)
905 // Null terminated, let ::strlen figure out the length.
908 // Not null terminated, use all 8 bytes.
909 Name = StringRef(Sec->Name, COFF::NameSize);
911 // Check for string table entry. First byte is '/'.
912 if (Name.startswith("/")) {
914 if (Name.startswith("//")) {
915 if (decodeBase64StringEntry(Name.substr(2), Offset))
916 return object_error::parse_failed;
918 if (Name.substr(1).getAsInteger(10, Offset))
919 return object_error::parse_failed;
921 if (std::error_code EC = getString(Offset, Name))
926 return std::error_code();
929 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
930 // SizeOfRawData and VirtualSize change what they represent depending on
931 // whether or not we have an executable image.
933 // For object files, SizeOfRawData contains the size of section's data;
934 // VirtualSize should be zero but isn't due to buggy COFF writers.
936 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
937 // actual section size is in VirtualSize. It is possible for VirtualSize to
938 // be greater than SizeOfRawData; the contents past that point should be
939 // considered to be zero.
941 return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
942 return Sec->SizeOfRawData;
946 COFFObjectFile::getSectionContents(const coff_section *Sec,
947 ArrayRef<uint8_t> &Res) const {
948 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
949 // don't do anything interesting for them.
950 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
951 "BSS sections don't have contents!");
952 // The only thing that we need to verify is that the contents is contained
953 // within the file bounds. We don't need to make sure it doesn't cover other
954 // data, as there's nothing that says that is not allowed.
955 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
956 uint32_t SectionSize = getSectionSize(Sec);
957 if (checkOffset(Data, ConStart, SectionSize))
958 return object_error::parse_failed;
959 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
960 return std::error_code();
963 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
964 return reinterpret_cast<const coff_relocation*>(Rel.p);
967 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
968 Rel.p = reinterpret_cast<uintptr_t>(
969 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
972 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
973 const coff_relocation *R = toRel(Rel);
974 return R->VirtualAddress;
977 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
978 const coff_relocation *R = toRel(Rel);
980 if (R->SymbolTableIndex >= getNumberOfSymbols())
983 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
984 else if (SymbolTable32)
985 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
987 llvm_unreachable("no symbol table pointer!");
988 return symbol_iterator(SymbolRef(Ref, this));
991 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
992 const coff_relocation* R = toRel(Rel);
997 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
998 return toSec(Section.getRawDataRefImpl());
1001 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1003 return toSymb<coff_symbol16>(Ref);
1005 return toSymb<coff_symbol32>(Ref);
1006 llvm_unreachable("no symbol table pointer!");
1009 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1010 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1013 const coff_relocation *
1014 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1015 return toRel(Reloc.getRawDataRefImpl());
1018 iterator_range<const coff_relocation *>
1019 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1020 const coff_relocation *I = getFirstReloc(Sec, Data, base());
1021 const coff_relocation *E = I;
1023 E += getNumberOfRelocations(Sec, Data, base());
1024 return make_range(I, E);
1027 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1028 case COFF::reloc_type: \
1029 Res = #reloc_type; \
1032 void COFFObjectFile::getRelocationTypeName(
1033 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1034 const coff_relocation *Reloc = toRel(Rel);
1036 switch (getMachine()) {
1037 case COFF::IMAGE_FILE_MACHINE_AMD64:
1038 switch (Reloc->Type) {
1039 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1040 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1041 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1042 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1043 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1044 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1045 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1046 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1047 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1048 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1049 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1050 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1051 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1052 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1053 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1054 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1055 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1060 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1061 switch (Reloc->Type) {
1062 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1063 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1064 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1065 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1066 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1067 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1068 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1069 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1070 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1071 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1072 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1073 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1074 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1075 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1076 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1081 case COFF::IMAGE_FILE_MACHINE_I386:
1082 switch (Reloc->Type) {
1083 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1084 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1085 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1086 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1087 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1088 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1089 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1090 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1091 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1092 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1093 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1101 Result.append(Res.begin(), Res.end());
1104 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1106 bool COFFObjectFile::isRelocatableObject() const {
1107 return !DataDirectory;
1110 bool ImportDirectoryEntryRef::
1111 operator==(const ImportDirectoryEntryRef &Other) const {
1112 return ImportTable == Other.ImportTable && Index == Other.Index;
1115 void ImportDirectoryEntryRef::moveNext() {
1119 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1120 const import_directory_table_entry *&Result) const {
1121 Result = ImportTable + Index;
1122 return std::error_code();
1125 static imported_symbol_iterator
1126 makeImportedSymbolIterator(const COFFObjectFile *Object,
1127 uintptr_t Ptr, int Index) {
1128 if (Object->getBytesInAddress() == 4) {
1129 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1130 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1132 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1133 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1136 static imported_symbol_iterator
1137 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1138 uintptr_t IntPtr = 0;
1139 Object->getRvaPtr(RVA, IntPtr);
1140 return makeImportedSymbolIterator(Object, IntPtr, 0);
1143 static imported_symbol_iterator
1144 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1145 uintptr_t IntPtr = 0;
1146 Object->getRvaPtr(RVA, IntPtr);
1147 // Forward the pointer to the last entry which is null.
1149 if (Object->getBytesInAddress() == 4) {
1150 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1154 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1158 return makeImportedSymbolIterator(Object, IntPtr, Index);
1161 imported_symbol_iterator
1162 ImportDirectoryEntryRef::imported_symbol_begin() const {
1163 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1167 imported_symbol_iterator
1168 ImportDirectoryEntryRef::imported_symbol_end() const {
1169 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1173 iterator_range<imported_symbol_iterator>
1174 ImportDirectoryEntryRef::imported_symbols() const {
1175 return make_range(imported_symbol_begin(), imported_symbol_end());
1178 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1179 uintptr_t IntPtr = 0;
1180 if (std::error_code EC =
1181 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1183 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1184 return std::error_code();
1188 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1189 Result = ImportTable[Index].ImportLookupTableRVA;
1190 return std::error_code();
1194 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1195 Result = ImportTable[Index].ImportAddressTableRVA;
1196 return std::error_code();
1199 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1200 const import_lookup_table_entry32 *&Result) const {
1201 uintptr_t IntPtr = 0;
1202 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1203 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1205 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1206 return std::error_code();
1209 bool DelayImportDirectoryEntryRef::
1210 operator==(const DelayImportDirectoryEntryRef &Other) const {
1211 return Table == Other.Table && Index == Other.Index;
1214 void DelayImportDirectoryEntryRef::moveNext() {
1218 imported_symbol_iterator
1219 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1220 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1224 imported_symbol_iterator
1225 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1226 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1230 iterator_range<imported_symbol_iterator>
1231 DelayImportDirectoryEntryRef::imported_symbols() const {
1232 return make_range(imported_symbol_begin(), imported_symbol_end());
1235 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1236 uintptr_t IntPtr = 0;
1237 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1239 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1240 return std::error_code();
1243 std::error_code DelayImportDirectoryEntryRef::
1244 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1246 return std::error_code();
1249 std::error_code DelayImportDirectoryEntryRef::
1250 getImportAddress(int AddrIndex, uint64_t &Result) const {
1251 uint32_t RVA = Table[Index].DelayImportAddressTable +
1252 AddrIndex * (OwningObject->is64() ? 8 : 4);
1253 uintptr_t IntPtr = 0;
1254 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1256 if (OwningObject->is64())
1257 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1259 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1260 return std::error_code();
1263 bool ExportDirectoryEntryRef::
1264 operator==(const ExportDirectoryEntryRef &Other) const {
1265 return ExportTable == Other.ExportTable && Index == Other.Index;
1268 void ExportDirectoryEntryRef::moveNext() {
1272 // Returns the name of the current export symbol. If the symbol is exported only
1273 // by ordinal, the empty string is set as a result.
1274 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1275 uintptr_t IntPtr = 0;
1276 if (std::error_code EC =
1277 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1279 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1280 return std::error_code();
1283 // Returns the starting ordinal number.
1285 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1286 Result = ExportTable->OrdinalBase;
1287 return std::error_code();
1290 // Returns the export ordinal of the current export symbol.
1291 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1292 Result = ExportTable->OrdinalBase + Index;
1293 return std::error_code();
1296 // Returns the address of the current export symbol.
1297 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1298 uintptr_t IntPtr = 0;
1299 if (std::error_code EC =
1300 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1302 const export_address_table_entry *entry =
1303 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1304 Result = entry[Index].ExportRVA;
1305 return std::error_code();
1308 // Returns the name of the current export symbol. If the symbol is exported only
1309 // by ordinal, the empty string is set as a result.
1311 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1312 uintptr_t IntPtr = 0;
1313 if (std::error_code EC =
1314 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1316 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1318 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1320 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1321 I < E; ++I, ++Offset) {
1324 if (std::error_code EC =
1325 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1327 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1328 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1330 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1331 return std::error_code();
1334 return std::error_code();
1337 bool ImportedSymbolRef::
1338 operator==(const ImportedSymbolRef &Other) const {
1339 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1340 && Index == Other.Index;
1343 void ImportedSymbolRef::moveNext() {
1348 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1351 // If a symbol is imported only by ordinal, it has no name.
1352 if (Entry32[Index].isOrdinal())
1353 return std::error_code();
1354 RVA = Entry32[Index].getHintNameRVA();
1356 if (Entry64[Index].isOrdinal())
1357 return std::error_code();
1358 RVA = Entry64[Index].getHintNameRVA();
1360 uintptr_t IntPtr = 0;
1361 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1363 // +2 because the first two bytes is hint.
1364 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1365 return std::error_code();
1368 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1371 if (Entry32[Index].isOrdinal()) {
1372 Result = Entry32[Index].getOrdinal();
1373 return std::error_code();
1375 RVA = Entry32[Index].getHintNameRVA();
1377 if (Entry64[Index].isOrdinal()) {
1378 Result = Entry64[Index].getOrdinal();
1379 return std::error_code();
1381 RVA = Entry64[Index].getHintNameRVA();
1383 uintptr_t IntPtr = 0;
1384 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1386 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1387 return std::error_code();
1390 ErrorOr<std::unique_ptr<COFFObjectFile>>
1391 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1393 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1396 return std::move(Ret);
1399 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1400 return Header == Other.Header && Index == Other.Index;
1403 void BaseRelocRef::moveNext() {
1404 // Header->BlockSize is the size of the current block, including the
1405 // size of the header itself.
1406 uint32_t Size = sizeof(*Header) +
1407 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1408 if (Size == Header->BlockSize) {
1409 // .reloc contains a list of base relocation blocks. Each block
1410 // consists of the header followed by entries. The header contains
1411 // how many entories will follow. When we reach the end of the
1412 // current block, proceed to the next block.
1413 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1414 reinterpret_cast<const uint8_t *>(Header) + Size);
1421 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1422 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1423 Type = Entry[Index].getType();
1424 return std::error_code();
1427 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1428 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1429 Result = Header->PageRVA + Entry[Index].getOffset();
1430 return std::error_code();