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 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
149 StringRef &Result) const {
150 COFFSymbolRef Symb = getCOFFSymbol(Ref);
151 return getSymbolName(Symb, Result);
154 uint64_t COFFObjectFile::getSymbolValue(DataRefImpl Ref) const {
155 COFFSymbolRef Sym = getCOFFSymbol(Ref);
157 if (Sym.isAnyUndefined() || Sym.isCommon())
158 return UnknownAddress;
160 return Sym.getValue();
163 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
164 uint64_t &Result) const {
165 Result = getSymbolValue(Ref);
166 COFFSymbolRef Symb = getCOFFSymbol(Ref);
167 int32_t SectionNumber = Symb.getSectionNumber();
169 if (Symb.isAnyUndefined() || Symb.isCommon() ||
170 COFF::isReservedSectionNumber(SectionNumber))
171 return std::error_code();
173 const coff_section *Section = nullptr;
174 if (std::error_code EC = getSection(SectionNumber, Section))
176 Result += Section->VirtualAddress;
177 return std::error_code();
180 SymbolRef::Type COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
181 COFFSymbolRef Symb = getCOFFSymbol(Ref);
182 int32_t SectionNumber = Symb.getSectionNumber();
184 if (Symb.isAnyUndefined())
185 return SymbolRef::ST_Unknown;
186 if (Symb.isFunctionDefinition())
187 return SymbolRef::ST_Function;
189 return SymbolRef::ST_Data;
190 if (Symb.isFileRecord())
191 return SymbolRef::ST_File;
193 // TODO: perhaps we need a new symbol type ST_Section.
194 if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
195 return SymbolRef::ST_Debug;
197 if (!COFF::isReservedSectionNumber(SectionNumber))
198 return SymbolRef::ST_Data;
200 return SymbolRef::ST_Other;
203 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
204 COFFSymbolRef Symb = getCOFFSymbol(Ref);
205 uint32_t Result = SymbolRef::SF_None;
207 if (Symb.isExternal() || Symb.isWeakExternal())
208 Result |= SymbolRef::SF_Global;
210 if (Symb.isWeakExternal())
211 Result |= SymbolRef::SF_Weak;
213 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
214 Result |= SymbolRef::SF_Absolute;
216 if (Symb.isFileRecord())
217 Result |= SymbolRef::SF_FormatSpecific;
219 if (Symb.isSectionDefinition())
220 Result |= SymbolRef::SF_FormatSpecific;
223 Result |= SymbolRef::SF_Common;
225 if (Symb.isAnyUndefined())
226 Result |= SymbolRef::SF_Undefined;
231 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
232 COFFSymbolRef Symb = getCOFFSymbol(Ref);
233 return Symb.getValue();
237 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
238 section_iterator &Result) const {
239 COFFSymbolRef Symb = getCOFFSymbol(Ref);
240 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
241 Result = section_end();
243 const coff_section *Sec = nullptr;
244 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
247 Ref.p = reinterpret_cast<uintptr_t>(Sec);
248 Result = section_iterator(SectionRef(Ref, this));
250 return std::error_code();
253 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
254 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
255 return Symb.getSectionNumber();
258 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
259 const coff_section *Sec = toSec(Ref);
261 Ref.p = reinterpret_cast<uintptr_t>(Sec);
264 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
265 StringRef &Result) const {
266 const coff_section *Sec = toSec(Ref);
267 return getSectionName(Sec, Result);
270 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
271 const coff_section *Sec = toSec(Ref);
272 return Sec->VirtualAddress;
275 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
276 return getSectionSize(toSec(Ref));
279 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
280 StringRef &Result) const {
281 const coff_section *Sec = toSec(Ref);
282 ArrayRef<uint8_t> Res;
283 std::error_code EC = getSectionContents(Sec, Res);
284 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
288 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
289 const coff_section *Sec = toSec(Ref);
290 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
293 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
294 const coff_section *Sec = toSec(Ref);
295 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
298 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
299 const coff_section *Sec = toSec(Ref);
300 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
303 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
304 const coff_section *Sec = toSec(Ref);
305 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
306 COFF::IMAGE_SCN_MEM_READ |
307 COFF::IMAGE_SCN_MEM_WRITE;
308 return (Sec->Characteristics & BssFlags) == BssFlags;
311 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
313 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
314 assert((Offset % sizeof(coff_section)) == 0);
315 return (Offset / sizeof(coff_section)) + 1;
318 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
319 const coff_section *Sec = toSec(Ref);
320 // In COFF, a virtual section won't have any in-file
321 // content, so the file pointer to the content will be zero.
322 return Sec->PointerToRawData == 0;
325 bool COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
326 DataRefImpl SymbRef) const {
327 const coff_section *Sec = toSec(SecRef);
328 COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
329 int32_t SecNumber = (Sec - SectionTable) + 1;
330 return SecNumber == Symb.getSectionNumber();
333 static uint32_t getNumberOfRelocations(const coff_section *Sec,
334 MemoryBufferRef M, const uint8_t *base) {
335 // The field for the number of relocations in COFF section table is only
336 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
337 // NumberOfRelocations field, and the actual relocation count is stored in the
338 // VirtualAddress field in the first relocation entry.
339 if (Sec->hasExtendedRelocations()) {
340 const coff_relocation *FirstReloc;
341 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
342 base + Sec->PointerToRelocations)))
344 // -1 to exclude this first relocation entry.
345 return FirstReloc->VirtualAddress - 1;
347 return Sec->NumberOfRelocations;
350 static const coff_relocation *
351 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
352 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
355 auto begin = reinterpret_cast<const coff_relocation *>(
356 Base + Sec->PointerToRelocations);
357 if (Sec->hasExtendedRelocations()) {
358 // Skip the first relocation entry repurposed to store the number of
362 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
367 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
368 const coff_section *Sec = toSec(Ref);
369 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
371 Ret.p = reinterpret_cast<uintptr_t>(begin);
372 return relocation_iterator(RelocationRef(Ret, this));
375 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
376 const coff_section *Sec = toSec(Ref);
377 const coff_relocation *I = getFirstReloc(Sec, Data, base());
379 I += getNumberOfRelocations(Sec, Data, base());
381 Ret.p = reinterpret_cast<uintptr_t>(I);
382 return relocation_iterator(RelocationRef(Ret, this));
385 // Initialize the pointer to the symbol table.
386 std::error_code COFFObjectFile::initSymbolTablePtr() {
388 if (std::error_code EC = getObject(
389 SymbolTable16, Data, base() + getPointerToSymbolTable(),
390 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
393 if (COFFBigObjHeader)
394 if (std::error_code EC = getObject(
395 SymbolTable32, Data, base() + getPointerToSymbolTable(),
396 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
399 // Find string table. The first four byte of the string table contains the
400 // total size of the string table, including the size field itself. If the
401 // string table is empty, the value of the first four byte would be 4.
402 uint32_t StringTableOffset = getPointerToSymbolTable() +
403 getNumberOfSymbols() * getSymbolTableEntrySize();
404 const uint8_t *StringTableAddr = base() + StringTableOffset;
405 const ulittle32_t *StringTableSizePtr;
406 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
408 StringTableSize = *StringTableSizePtr;
409 if (std::error_code EC =
410 getObject(StringTable, Data, StringTableAddr, StringTableSize))
413 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
414 // tools like cvtres write a size of 0 for an empty table instead of 4.
415 if (StringTableSize < 4)
418 // Check that the string table is null terminated if has any in it.
419 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
420 return object_error::parse_failed;
421 return std::error_code();
424 // Returns the file offset for the given VA.
425 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
426 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
427 : (uint64_t)PE32PlusHeader->ImageBase;
428 uint64_t Rva = Addr - ImageBase;
429 assert(Rva <= UINT32_MAX);
430 return getRvaPtr((uint32_t)Rva, Res);
433 // Returns the file offset for the given RVA.
434 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
435 for (const SectionRef &S : sections()) {
436 const coff_section *Section = getCOFFSection(S);
437 uint32_t SectionStart = Section->VirtualAddress;
438 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
439 if (SectionStart <= Addr && Addr < SectionEnd) {
440 uint32_t Offset = Addr - SectionStart;
441 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
442 return std::error_code();
445 return object_error::parse_failed;
448 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
450 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
451 StringRef &Name) const {
452 uintptr_t IntPtr = 0;
453 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
455 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
456 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
457 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
458 return std::error_code();
461 // Find the import table.
462 std::error_code COFFObjectFile::initImportTablePtr() {
463 // First, we get the RVA of the import table. If the file lacks a pointer to
464 // the import table, do nothing.
465 const data_directory *DataEntry;
466 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
467 return std::error_code();
469 // Do nothing if the pointer to import table is NULL.
470 if (DataEntry->RelativeVirtualAddress == 0)
471 return std::error_code();
473 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
474 // -1 because the last entry is the null entry.
475 NumberOfImportDirectory = DataEntry->Size /
476 sizeof(import_directory_table_entry) - 1;
478 // Find the section that contains the RVA. This is needed because the RVA is
479 // the import table's memory address which is different from its file offset.
480 uintptr_t IntPtr = 0;
481 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
483 ImportDirectory = reinterpret_cast<
484 const import_directory_table_entry *>(IntPtr);
485 return std::error_code();
488 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
489 std::error_code COFFObjectFile::initDelayImportTablePtr() {
490 const data_directory *DataEntry;
491 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
492 return std::error_code();
493 if (DataEntry->RelativeVirtualAddress == 0)
494 return std::error_code();
496 uint32_t RVA = DataEntry->RelativeVirtualAddress;
497 NumberOfDelayImportDirectory = DataEntry->Size /
498 sizeof(delay_import_directory_table_entry) - 1;
500 uintptr_t IntPtr = 0;
501 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
503 DelayImportDirectory = reinterpret_cast<
504 const delay_import_directory_table_entry *>(IntPtr);
505 return std::error_code();
508 // Find the export table.
509 std::error_code COFFObjectFile::initExportTablePtr() {
510 // First, we get the RVA of the export table. If the file lacks a pointer to
511 // the export table, do nothing.
512 const data_directory *DataEntry;
513 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
514 return std::error_code();
516 // Do nothing if the pointer to export table is NULL.
517 if (DataEntry->RelativeVirtualAddress == 0)
518 return std::error_code();
520 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
521 uintptr_t IntPtr = 0;
522 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
525 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
526 return std::error_code();
529 std::error_code COFFObjectFile::initBaseRelocPtr() {
530 const data_directory *DataEntry;
531 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
532 return std::error_code();
533 if (DataEntry->RelativeVirtualAddress == 0)
534 return std::error_code();
536 uintptr_t IntPtr = 0;
537 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
539 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
541 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
542 IntPtr + DataEntry->Size);
543 return std::error_code();
546 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
547 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
548 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
549 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
550 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
551 ImportDirectory(nullptr), NumberOfImportDirectory(0),
552 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
553 ExportDirectory(nullptr), BaseRelocHeader(nullptr),
554 BaseRelocEnd(nullptr) {
555 // Check that we at least have enough room for a header.
556 if (!checkSize(Data, EC, sizeof(coff_file_header)))
559 // The current location in the file where we are looking at.
562 // PE header is optional and is present only in executables. If it exists,
563 // it is placed right after COFF header.
564 bool HasPEHeader = false;
566 // Check if this is a PE/COFF file.
567 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
568 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
569 // PE signature to find 'normal' COFF header.
570 const auto *DH = reinterpret_cast<const dos_header *>(base());
571 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
572 CurPtr = DH->AddressOfNewExeHeader;
573 // Check the PE magic bytes. ("PE\0\0")
574 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
575 EC = object_error::parse_failed;
578 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
583 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
586 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
587 // import libraries share a common prefix but bigobj is more restrictive.
588 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
589 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
590 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
591 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
594 // Verify that we are dealing with bigobj.
595 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
596 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
597 sizeof(COFF::BigObjMagic)) == 0) {
598 COFFHeader = nullptr;
599 CurPtr += sizeof(coff_bigobj_file_header);
601 // It's not a bigobj.
602 COFFBigObjHeader = nullptr;
606 // The prior checkSize call may have failed. This isn't a hard error
607 // because we were just trying to sniff out bigobj.
608 EC = std::error_code();
609 CurPtr += sizeof(coff_file_header);
611 if (COFFHeader->isImportLibrary())
616 const pe32_header *Header;
617 if ((EC = getObject(Header, Data, base() + CurPtr)))
620 const uint8_t *DataDirAddr;
621 uint64_t DataDirSize;
622 if (Header->Magic == COFF::PE32Header::PE32) {
624 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
625 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
626 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
627 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
628 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
629 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
631 // It's neither PE32 nor PE32+.
632 EC = object_error::parse_failed;
635 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
637 CurPtr += COFFHeader->SizeOfOptionalHeader;
640 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
641 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
644 // Initialize the pointer to the symbol table.
645 if (getPointerToSymbolTable() != 0) {
646 if ((EC = initSymbolTablePtr()))
649 // We had better not have any symbols if we don't have a symbol table.
650 if (getNumberOfSymbols() != 0) {
651 EC = object_error::parse_failed;
656 // Initialize the pointer to the beginning of the import table.
657 if ((EC = initImportTablePtr()))
659 if ((EC = initDelayImportTablePtr()))
662 // Initialize the pointer to the export table.
663 if ((EC = initExportTablePtr()))
666 // Initialize the pointer to the base relocation table.
667 if ((EC = initBaseRelocPtr()))
670 EC = std::error_code();
673 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
675 Ret.p = getSymbolTable();
676 return basic_symbol_iterator(SymbolRef(Ret, this));
679 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
680 // The symbol table ends where the string table begins.
682 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
683 return basic_symbol_iterator(SymbolRef(Ret, this));
686 import_directory_iterator COFFObjectFile::import_directory_begin() const {
687 return import_directory_iterator(
688 ImportDirectoryEntryRef(ImportDirectory, 0, this));
691 import_directory_iterator COFFObjectFile::import_directory_end() const {
692 return import_directory_iterator(
693 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
696 delay_import_directory_iterator
697 COFFObjectFile::delay_import_directory_begin() const {
698 return delay_import_directory_iterator(
699 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
702 delay_import_directory_iterator
703 COFFObjectFile::delay_import_directory_end() const {
704 return delay_import_directory_iterator(
705 DelayImportDirectoryEntryRef(
706 DelayImportDirectory, NumberOfDelayImportDirectory, this));
709 export_directory_iterator COFFObjectFile::export_directory_begin() const {
710 return export_directory_iterator(
711 ExportDirectoryEntryRef(ExportDirectory, 0, this));
714 export_directory_iterator COFFObjectFile::export_directory_end() const {
715 if (!ExportDirectory)
716 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
717 ExportDirectoryEntryRef Ref(ExportDirectory,
718 ExportDirectory->AddressTableEntries, this);
719 return export_directory_iterator(Ref);
722 section_iterator COFFObjectFile::section_begin() const {
724 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
725 return section_iterator(SectionRef(Ret, this));
728 section_iterator COFFObjectFile::section_end() const {
731 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
732 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
733 return section_iterator(SectionRef(Ret, this));
736 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
737 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
740 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
741 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
744 uint8_t COFFObjectFile::getBytesInAddress() const {
745 return getArch() == Triple::x86_64 ? 8 : 4;
748 StringRef COFFObjectFile::getFileFormatName() const {
749 switch(getMachine()) {
750 case COFF::IMAGE_FILE_MACHINE_I386:
752 case COFF::IMAGE_FILE_MACHINE_AMD64:
753 return "COFF-x86-64";
754 case COFF::IMAGE_FILE_MACHINE_ARMNT:
757 return "COFF-<unknown arch>";
761 unsigned COFFObjectFile::getArch() const {
762 switch (getMachine()) {
763 case COFF::IMAGE_FILE_MACHINE_I386:
765 case COFF::IMAGE_FILE_MACHINE_AMD64:
766 return Triple::x86_64;
767 case COFF::IMAGE_FILE_MACHINE_ARMNT:
768 return Triple::thumb;
770 return Triple::UnknownArch;
774 iterator_range<import_directory_iterator>
775 COFFObjectFile::import_directories() const {
776 return make_range(import_directory_begin(), import_directory_end());
779 iterator_range<delay_import_directory_iterator>
780 COFFObjectFile::delay_import_directories() const {
781 return make_range(delay_import_directory_begin(),
782 delay_import_directory_end());
785 iterator_range<export_directory_iterator>
786 COFFObjectFile::export_directories() const {
787 return make_range(export_directory_begin(), export_directory_end());
790 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
791 return make_range(base_reloc_begin(), base_reloc_end());
794 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
796 return std::error_code();
800 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
801 Res = PE32PlusHeader;
802 return std::error_code();
806 COFFObjectFile::getDataDirectory(uint32_t Index,
807 const data_directory *&Res) const {
808 // Error if if there's no data directory or the index is out of range.
809 if (!DataDirectory) {
811 return object_error::parse_failed;
813 assert(PE32Header || PE32PlusHeader);
814 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
815 : PE32PlusHeader->NumberOfRvaAndSize;
816 if (Index >= NumEnt) {
818 return object_error::parse_failed;
820 Res = &DataDirectory[Index];
821 return std::error_code();
824 std::error_code COFFObjectFile::getSection(int32_t Index,
825 const coff_section *&Result) const {
827 if (COFF::isReservedSectionNumber(Index))
828 return std::error_code();
829 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
830 // We already verified the section table data, so no need to check again.
831 Result = SectionTable + (Index - 1);
832 return std::error_code();
834 return object_error::parse_failed;
837 std::error_code COFFObjectFile::getString(uint32_t Offset,
838 StringRef &Result) const {
839 if (StringTableSize <= 4)
840 // Tried to get a string from an empty string table.
841 return object_error::parse_failed;
842 if (Offset >= StringTableSize)
843 return object_error::unexpected_eof;
844 Result = StringRef(StringTable + Offset);
845 return std::error_code();
848 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
849 StringRef &Res) const {
850 // Check for string table entry. First 4 bytes are 0.
851 if (Symbol.getStringTableOffset().Zeroes == 0) {
852 uint32_t Offset = Symbol.getStringTableOffset().Offset;
853 if (std::error_code EC = getString(Offset, Res))
855 return std::error_code();
858 if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
859 // Null terminated, let ::strlen figure out the length.
860 Res = StringRef(Symbol.getShortName());
862 // Not null terminated, use all 8 bytes.
863 Res = StringRef(Symbol.getShortName(), COFF::NameSize);
864 return std::error_code();
868 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
869 const uint8_t *Aux = nullptr;
871 size_t SymbolSize = getSymbolTableEntrySize();
872 if (Symbol.getNumberOfAuxSymbols() > 0) {
873 // AUX data comes immediately after the symbol in COFF
874 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
876 // Verify that the Aux symbol points to a valid entry in the symbol table.
877 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
878 if (Offset < getPointerToSymbolTable() ||
880 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
881 report_fatal_error("Aux Symbol data was outside of symbol table.");
883 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
884 "Aux Symbol data did not point to the beginning of a symbol");
887 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
890 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
891 StringRef &Res) const {
893 if (Sec->Name[COFF::NameSize - 1] == 0)
894 // Null terminated, let ::strlen figure out the length.
897 // Not null terminated, use all 8 bytes.
898 Name = StringRef(Sec->Name, COFF::NameSize);
900 // Check for string table entry. First byte is '/'.
901 if (Name.startswith("/")) {
903 if (Name.startswith("//")) {
904 if (decodeBase64StringEntry(Name.substr(2), Offset))
905 return object_error::parse_failed;
907 if (Name.substr(1).getAsInteger(10, Offset))
908 return object_error::parse_failed;
910 if (std::error_code EC = getString(Offset, Name))
915 return std::error_code();
918 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
919 // SizeOfRawData and VirtualSize change what they represent depending on
920 // whether or not we have an executable image.
922 // For object files, SizeOfRawData contains the size of section's data;
923 // VirtualSize is always zero.
925 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
926 // actual section size is in VirtualSize. It is possible for VirtualSize to
927 // be greater than SizeOfRawData; the contents past that point should be
928 // considered to be zero.
929 uint32_t SectionSize;
930 if (Sec->VirtualSize)
931 SectionSize = std::min(Sec->VirtualSize, Sec->SizeOfRawData);
933 SectionSize = Sec->SizeOfRawData;
939 COFFObjectFile::getSectionContents(const coff_section *Sec,
940 ArrayRef<uint8_t> &Res) const {
941 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
942 // don't do anything interesting for them.
943 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
944 "BSS sections don't have contents!");
945 // The only thing that we need to verify is that the contents is contained
946 // within the file bounds. We don't need to make sure it doesn't cover other
947 // data, as there's nothing that says that is not allowed.
948 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
949 uint32_t SectionSize = getSectionSize(Sec);
950 if (checkOffset(Data, ConStart, SectionSize))
951 return object_error::parse_failed;
952 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
953 return std::error_code();
956 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
957 return reinterpret_cast<const coff_relocation*>(Rel.p);
960 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
961 Rel.p = reinterpret_cast<uintptr_t>(
962 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
965 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
966 uint64_t &Res) const {
967 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
970 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
971 const coff_relocation *R = toRel(Rel);
972 return R->VirtualAddress;
975 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
976 const coff_relocation *R = toRel(Rel);
978 if (R->SymbolTableIndex >= getNumberOfSymbols())
981 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
982 else if (SymbolTable32)
983 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
985 llvm_unreachable("no symbol table pointer!");
986 return symbol_iterator(SymbolRef(Ref, this));
989 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
990 uint64_t &Res) const {
991 const coff_relocation* R = toRel(Rel);
993 return std::error_code();
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; \
1033 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
1034 SmallVectorImpl<char> &Result) const {
1035 const coff_relocation *Reloc = toRel(Rel);
1037 switch (getMachine()) {
1038 case COFF::IMAGE_FILE_MACHINE_AMD64:
1039 switch (Reloc->Type) {
1040 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1041 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1042 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1043 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1044 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1045 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1046 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1047 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1048 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1049 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1050 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1051 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1052 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1053 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1054 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1055 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1056 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1061 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1062 switch (Reloc->Type) {
1063 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1064 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1065 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1066 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1067 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1068 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1069 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1070 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1071 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1072 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1073 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1074 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1075 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1076 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1077 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1082 case COFF::IMAGE_FILE_MACHINE_I386:
1083 switch (Reloc->Type) {
1084 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1085 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1086 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1087 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1088 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1089 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1090 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1091 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1092 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1093 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1094 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1102 Result.append(Res.begin(), Res.end());
1103 return std::error_code();
1106 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1108 bool COFFObjectFile::isRelocatableObject() const {
1109 return !DataDirectory;
1112 bool ImportDirectoryEntryRef::
1113 operator==(const ImportDirectoryEntryRef &Other) const {
1114 return ImportTable == Other.ImportTable && Index == Other.Index;
1117 void ImportDirectoryEntryRef::moveNext() {
1121 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1122 const import_directory_table_entry *&Result) const {
1123 Result = ImportTable + Index;
1124 return std::error_code();
1127 static imported_symbol_iterator
1128 makeImportedSymbolIterator(const COFFObjectFile *Object,
1129 uintptr_t Ptr, int Index) {
1130 if (Object->getBytesInAddress() == 4) {
1131 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1132 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1134 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1135 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1138 static imported_symbol_iterator
1139 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1140 uintptr_t IntPtr = 0;
1141 Object->getRvaPtr(RVA, IntPtr);
1142 return makeImportedSymbolIterator(Object, IntPtr, 0);
1145 static imported_symbol_iterator
1146 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1147 uintptr_t IntPtr = 0;
1148 Object->getRvaPtr(RVA, IntPtr);
1149 // Forward the pointer to the last entry which is null.
1151 if (Object->getBytesInAddress() == 4) {
1152 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1156 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1160 return makeImportedSymbolIterator(Object, IntPtr, Index);
1163 imported_symbol_iterator
1164 ImportDirectoryEntryRef::imported_symbol_begin() const {
1165 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1169 imported_symbol_iterator
1170 ImportDirectoryEntryRef::imported_symbol_end() const {
1171 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1175 iterator_range<imported_symbol_iterator>
1176 ImportDirectoryEntryRef::imported_symbols() const {
1177 return make_range(imported_symbol_begin(), imported_symbol_end());
1180 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1181 uintptr_t IntPtr = 0;
1182 if (std::error_code EC =
1183 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1185 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1186 return std::error_code();
1190 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1191 Result = ImportTable[Index].ImportLookupTableRVA;
1192 return std::error_code();
1196 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1197 Result = ImportTable[Index].ImportAddressTableRVA;
1198 return std::error_code();
1201 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1202 const import_lookup_table_entry32 *&Result) const {
1203 uintptr_t IntPtr = 0;
1204 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1205 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1207 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1208 return std::error_code();
1211 bool DelayImportDirectoryEntryRef::
1212 operator==(const DelayImportDirectoryEntryRef &Other) const {
1213 return Table == Other.Table && Index == Other.Index;
1216 void DelayImportDirectoryEntryRef::moveNext() {
1220 imported_symbol_iterator
1221 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1222 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1226 imported_symbol_iterator
1227 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1228 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1232 iterator_range<imported_symbol_iterator>
1233 DelayImportDirectoryEntryRef::imported_symbols() const {
1234 return make_range(imported_symbol_begin(), imported_symbol_end());
1237 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1238 uintptr_t IntPtr = 0;
1239 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1241 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1242 return std::error_code();
1245 std::error_code DelayImportDirectoryEntryRef::
1246 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1248 return std::error_code();
1251 std::error_code DelayImportDirectoryEntryRef::
1252 getImportAddress(int AddrIndex, uint64_t &Result) const {
1253 uint32_t RVA = Table[Index].DelayImportAddressTable +
1254 AddrIndex * (OwningObject->is64() ? 8 : 4);
1255 uintptr_t IntPtr = 0;
1256 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1258 if (OwningObject->is64())
1259 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1261 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1262 return std::error_code();
1265 bool ExportDirectoryEntryRef::
1266 operator==(const ExportDirectoryEntryRef &Other) const {
1267 return ExportTable == Other.ExportTable && Index == Other.Index;
1270 void ExportDirectoryEntryRef::moveNext() {
1274 // Returns the name of the current export symbol. If the symbol is exported only
1275 // by ordinal, the empty string is set as a result.
1276 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1277 uintptr_t IntPtr = 0;
1278 if (std::error_code EC =
1279 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1281 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1282 return std::error_code();
1285 // Returns the starting ordinal number.
1287 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1288 Result = ExportTable->OrdinalBase;
1289 return std::error_code();
1292 // Returns the export ordinal of the current export symbol.
1293 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1294 Result = ExportTable->OrdinalBase + Index;
1295 return std::error_code();
1298 // Returns the address of the current export symbol.
1299 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1300 uintptr_t IntPtr = 0;
1301 if (std::error_code EC =
1302 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1304 const export_address_table_entry *entry =
1305 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1306 Result = entry[Index].ExportRVA;
1307 return std::error_code();
1310 // Returns the name of the current export symbol. If the symbol is exported only
1311 // by ordinal, the empty string is set as a result.
1313 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1314 uintptr_t IntPtr = 0;
1315 if (std::error_code EC =
1316 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1318 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1320 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1322 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1323 I < E; ++I, ++Offset) {
1326 if (std::error_code EC =
1327 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1329 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1330 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1332 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1333 return std::error_code();
1336 return std::error_code();
1339 bool ImportedSymbolRef::
1340 operator==(const ImportedSymbolRef &Other) const {
1341 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1342 && Index == Other.Index;
1345 void ImportedSymbolRef::moveNext() {
1350 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1353 // If a symbol is imported only by ordinal, it has no name.
1354 if (Entry32[Index].isOrdinal())
1355 return std::error_code();
1356 RVA = Entry32[Index].getHintNameRVA();
1358 if (Entry64[Index].isOrdinal())
1359 return std::error_code();
1360 RVA = Entry64[Index].getHintNameRVA();
1362 uintptr_t IntPtr = 0;
1363 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1365 // +2 because the first two bytes is hint.
1366 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1367 return std::error_code();
1370 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1373 if (Entry32[Index].isOrdinal()) {
1374 Result = Entry32[Index].getOrdinal();
1375 return std::error_code();
1377 RVA = Entry32[Index].getHintNameRVA();
1379 if (Entry64[Index].isOrdinal()) {
1380 Result = Entry64[Index].getOrdinal();
1381 return std::error_code();
1383 RVA = Entry64[Index].getHintNameRVA();
1385 uintptr_t IntPtr = 0;
1386 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1388 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1389 return std::error_code();
1392 ErrorOr<std::unique_ptr<COFFObjectFile>>
1393 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1395 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1398 return std::move(Ret);
1401 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1402 return Header == Other.Header && Index == Other.Index;
1405 void BaseRelocRef::moveNext() {
1406 // Header->BlockSize is the size of the current block, including the
1407 // size of the header itself.
1408 uint32_t Size = sizeof(*Header) +
1409 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1410 if (Size == Header->BlockSize) {
1411 // .reloc contains a list of base relocation blocks. Each block
1412 // consists of the header followed by entries. The header contains
1413 // how many entories will follow. When we reach the end of the
1414 // current block, proceed to the next block.
1415 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1416 reinterpret_cast<const uint8_t *>(Header) + Size);
1423 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1424 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1425 Type = Entry[Index].getType();
1426 return std::error_code();
1429 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1430 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1431 Result = Header->PageRVA + Entry[Index].getOffset();
1432 return std::error_code();