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/Support/COFF.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
26 using namespace object;
28 using support::ulittle16_t;
29 using support::ulittle32_t;
30 using support::ulittle64_t;
31 using support::little16_t;
33 // Returns false if size is greater than the buffer size. And sets ec.
34 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
35 if (M.getBufferSize() < Size) {
36 EC = object_error::unexpected_eof;
42 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
43 const uint64_t Size) {
44 if (Addr + Size < Addr || Addr + Size < Size ||
45 Addr + Size > uintptr_t(M.getBufferEnd()) ||
46 Addr < uintptr_t(M.getBufferStart())) {
47 return object_error::unexpected_eof;
49 return std::error_code();
52 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
53 // Returns unexpected_eof if error.
55 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
57 const uint64_t Size = sizeof(T)) {
58 uintptr_t Addr = uintptr_t(Ptr);
59 if (std::error_code EC = checkOffset(M, Addr, Size))
61 Obj = reinterpret_cast<const T *>(Addr);
62 return std::error_code();
65 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
67 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
68 assert(Str.size() <= 6 && "String too long, possible overflow.");
73 while (!Str.empty()) {
75 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
76 CharVal = Str[0] - 'A';
77 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
78 CharVal = Str[0] - 'a' + 26;
79 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
80 CharVal = Str[0] - '0' + 52;
81 else if (Str[0] == '+') // 62
83 else if (Str[0] == '/') // 63
88 Value = (Value * 64) + CharVal;
92 if (Value > std::numeric_limits<uint32_t>::max())
95 Result = static_cast<uint32_t>(Value);
99 template <typename coff_symbol_type>
100 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
101 const coff_symbol_type *Addr =
102 reinterpret_cast<const coff_symbol_type *>(Ref.p);
104 assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
106 // Verify that the symbol points to a valid entry in the symbol table.
107 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
109 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
110 "Symbol did not point to the beginning of a symbol");
116 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
117 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
120 // Verify that the section points to a valid entry in the section table.
121 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
122 report_fatal_error("Section was outside of section table.");
124 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
125 assert(Offset % sizeof(coff_section) == 0 &&
126 "Section did not point to the beginning of a section");
132 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
133 auto End = reinterpret_cast<uintptr_t>(StringTable);
135 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
136 Symb += 1 + Symb->NumberOfAuxSymbols;
137 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
138 } else if (SymbolTable32) {
139 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
140 Symb += 1 + Symb->NumberOfAuxSymbols;
141 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
143 llvm_unreachable("no symbol table pointer!");
147 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
148 StringRef &Result) const {
149 COFFSymbolRef Symb = getCOFFSymbol(Ref);
150 return getSymbolName(Symb, Result);
153 uint64_t COFFObjectFile::getSymbolValue(DataRefImpl Ref) const {
154 COFFSymbolRef Sym = getCOFFSymbol(Ref);
156 if (Sym.isAnyUndefined() || Sym.isCommon())
157 return UnknownAddress;
159 return Sym.getValue();
162 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
163 uint64_t &Result) const {
164 Result = getSymbolValue(Ref);
165 COFFSymbolRef Symb = getCOFFSymbol(Ref);
166 int32_t SectionNumber = Symb.getSectionNumber();
168 if (Symb.isAnyUndefined() || Symb.isCommon() ||
169 COFF::isReservedSectionNumber(SectionNumber))
170 return std::error_code();
172 const coff_section *Section = nullptr;
173 if (std::error_code EC = getSection(SectionNumber, Section))
175 Result += Section->VirtualAddress;
176 return std::error_code();
179 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
180 SymbolRef::Type &Result) const {
181 COFFSymbolRef Symb = getCOFFSymbol(Ref);
182 int32_t SectionNumber = Symb.getSectionNumber();
183 Result = SymbolRef::ST_Other;
185 if (Symb.isAnyUndefined()) {
186 Result = SymbolRef::ST_Unknown;
187 } else if (Symb.isFunctionDefinition()) {
188 Result = SymbolRef::ST_Function;
189 } else if (Symb.isCommon()) {
190 Result = SymbolRef::ST_Data;
191 } else if (Symb.isFileRecord()) {
192 Result = SymbolRef::ST_File;
193 } else if (SectionNumber == COFF::IMAGE_SYM_DEBUG ||
194 Symb.isSectionDefinition()) {
195 // TODO: perhaps we need a new symbol type ST_Section.
196 Result = SymbolRef::ST_Debug;
197 } else if (!COFF::isReservedSectionNumber(SectionNumber)) {
198 const coff_section *Section = nullptr;
199 if (std::error_code EC = getSection(SectionNumber, Section))
201 uint32_t Characteristics = Section->Characteristics;
202 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
203 Result = SymbolRef::ST_Function;
204 else if (Characteristics & (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
205 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA))
206 Result = SymbolRef::ST_Data;
208 return std::error_code();
211 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
212 COFFSymbolRef Symb = getCOFFSymbol(Ref);
213 uint32_t Result = SymbolRef::SF_None;
215 if (Symb.isExternal() || Symb.isWeakExternal())
216 Result |= SymbolRef::SF_Global;
218 if (Symb.isWeakExternal())
219 Result |= SymbolRef::SF_Weak;
221 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
222 Result |= SymbolRef::SF_Absolute;
224 if (Symb.isFileRecord())
225 Result |= SymbolRef::SF_FormatSpecific;
227 if (Symb.isSectionDefinition())
228 Result |= SymbolRef::SF_FormatSpecific;
231 Result |= SymbolRef::SF_Common;
233 if (Symb.isAnyUndefined())
234 Result |= SymbolRef::SF_Undefined;
239 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
240 COFFSymbolRef Symb = getCOFFSymbol(Ref);
241 return Symb.getValue();
245 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
246 section_iterator &Result) const {
247 COFFSymbolRef Symb = getCOFFSymbol(Ref);
248 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
249 Result = section_end();
251 const coff_section *Sec = nullptr;
252 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
255 Ref.p = reinterpret_cast<uintptr_t>(Sec);
256 Result = section_iterator(SectionRef(Ref, this));
258 return std::error_code();
261 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
262 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
263 return Symb.getSectionNumber();
266 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
267 const coff_section *Sec = toSec(Ref);
269 Ref.p = reinterpret_cast<uintptr_t>(Sec);
272 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
273 StringRef &Result) const {
274 const coff_section *Sec = toSec(Ref);
275 return getSectionName(Sec, Result);
278 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
279 const coff_section *Sec = toSec(Ref);
280 return Sec->VirtualAddress;
283 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
284 return getSectionSize(toSec(Ref));
287 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
288 StringRef &Result) const {
289 const coff_section *Sec = toSec(Ref);
290 ArrayRef<uint8_t> Res;
291 std::error_code EC = getSectionContents(Sec, Res);
292 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
296 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
297 const coff_section *Sec = toSec(Ref);
298 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
301 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
302 const coff_section *Sec = toSec(Ref);
303 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
306 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
307 const coff_section *Sec = toSec(Ref);
308 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
311 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
312 const coff_section *Sec = toSec(Ref);
313 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
314 COFF::IMAGE_SCN_MEM_READ |
315 COFF::IMAGE_SCN_MEM_WRITE;
316 return (Sec->Characteristics & BssFlags) == BssFlags;
319 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
321 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
322 assert((Offset % sizeof(coff_section)) == 0);
323 return (Offset / sizeof(coff_section)) + 1;
326 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
327 const coff_section *Sec = toSec(Ref);
328 // In COFF, a virtual section won't have any in-file
329 // content, so the file pointer to the content will be zero.
330 return Sec->PointerToRawData == 0;
333 bool COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
334 DataRefImpl SymbRef) const {
335 const coff_section *Sec = toSec(SecRef);
336 COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
337 int32_t SecNumber = (Sec - SectionTable) + 1;
338 return SecNumber == Symb.getSectionNumber();
341 static uint32_t getNumberOfRelocations(const coff_section *Sec,
342 MemoryBufferRef M, const uint8_t *base) {
343 // The field for the number of relocations in COFF section table is only
344 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
345 // NumberOfRelocations field, and the actual relocation count is stored in the
346 // VirtualAddress field in the first relocation entry.
347 if (Sec->hasExtendedRelocations()) {
348 const coff_relocation *FirstReloc;
349 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
350 base + Sec->PointerToRelocations)))
352 // -1 to exclude this first relocation entry.
353 return FirstReloc->VirtualAddress - 1;
355 return Sec->NumberOfRelocations;
358 static const coff_relocation *
359 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
360 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
363 auto begin = reinterpret_cast<const coff_relocation *>(
364 Base + Sec->PointerToRelocations);
365 if (Sec->hasExtendedRelocations()) {
366 // Skip the first relocation entry repurposed to store the number of
370 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
375 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
376 const coff_section *Sec = toSec(Ref);
377 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
379 Ret.p = reinterpret_cast<uintptr_t>(begin);
380 return relocation_iterator(RelocationRef(Ret, this));
383 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
384 const coff_section *Sec = toSec(Ref);
385 const coff_relocation *I = getFirstReloc(Sec, Data, base());
387 I += getNumberOfRelocations(Sec, Data, base());
389 Ret.p = reinterpret_cast<uintptr_t>(I);
390 return relocation_iterator(RelocationRef(Ret, this));
393 // Initialize the pointer to the symbol table.
394 std::error_code COFFObjectFile::initSymbolTablePtr() {
396 if (std::error_code EC = getObject(
397 SymbolTable16, Data, base() + getPointerToSymbolTable(),
398 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
401 if (COFFBigObjHeader)
402 if (std::error_code EC = getObject(
403 SymbolTable32, Data, base() + getPointerToSymbolTable(),
404 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
407 // Find string table. The first four byte of the string table contains the
408 // total size of the string table, including the size field itself. If the
409 // string table is empty, the value of the first four byte would be 4.
410 uint32_t StringTableOffset = getPointerToSymbolTable() +
411 getNumberOfSymbols() * getSymbolTableEntrySize();
412 const uint8_t *StringTableAddr = base() + StringTableOffset;
413 const ulittle32_t *StringTableSizePtr;
414 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
416 StringTableSize = *StringTableSizePtr;
417 if (std::error_code EC =
418 getObject(StringTable, Data, StringTableAddr, StringTableSize))
421 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
422 // tools like cvtres write a size of 0 for an empty table instead of 4.
423 if (StringTableSize < 4)
426 // Check that the string table is null terminated if has any in it.
427 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
428 return object_error::parse_failed;
429 return std::error_code();
432 // Returns the file offset for the given VA.
433 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
434 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
435 : (uint64_t)PE32PlusHeader->ImageBase;
436 uint64_t Rva = Addr - ImageBase;
437 assert(Rva <= UINT32_MAX);
438 return getRvaPtr((uint32_t)Rva, Res);
441 // Returns the file offset for the given RVA.
442 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
443 for (const SectionRef &S : sections()) {
444 const coff_section *Section = getCOFFSection(S);
445 uint32_t SectionStart = Section->VirtualAddress;
446 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
447 if (SectionStart <= Addr && Addr < SectionEnd) {
448 uint32_t Offset = Addr - SectionStart;
449 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
450 return std::error_code();
453 return object_error::parse_failed;
456 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
458 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
459 StringRef &Name) const {
460 uintptr_t IntPtr = 0;
461 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
463 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
464 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
465 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
466 return std::error_code();
469 // Find the import table.
470 std::error_code COFFObjectFile::initImportTablePtr() {
471 // First, we get the RVA of the import table. If the file lacks a pointer to
472 // the import table, do nothing.
473 const data_directory *DataEntry;
474 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
475 return std::error_code();
477 // Do nothing if the pointer to import table is NULL.
478 if (DataEntry->RelativeVirtualAddress == 0)
479 return std::error_code();
481 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
482 // -1 because the last entry is the null entry.
483 NumberOfImportDirectory = DataEntry->Size /
484 sizeof(import_directory_table_entry) - 1;
486 // Find the section that contains the RVA. This is needed because the RVA is
487 // the import table's memory address which is different from its file offset.
488 uintptr_t IntPtr = 0;
489 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
491 ImportDirectory = reinterpret_cast<
492 const import_directory_table_entry *>(IntPtr);
493 return std::error_code();
496 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
497 std::error_code COFFObjectFile::initDelayImportTablePtr() {
498 const data_directory *DataEntry;
499 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
500 return std::error_code();
501 if (DataEntry->RelativeVirtualAddress == 0)
502 return std::error_code();
504 uint32_t RVA = DataEntry->RelativeVirtualAddress;
505 NumberOfDelayImportDirectory = DataEntry->Size /
506 sizeof(delay_import_directory_table_entry) - 1;
508 uintptr_t IntPtr = 0;
509 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
511 DelayImportDirectory = reinterpret_cast<
512 const delay_import_directory_table_entry *>(IntPtr);
513 return std::error_code();
516 // Find the export table.
517 std::error_code COFFObjectFile::initExportTablePtr() {
518 // First, we get the RVA of the export table. If the file lacks a pointer to
519 // the export table, do nothing.
520 const data_directory *DataEntry;
521 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
522 return std::error_code();
524 // Do nothing if the pointer to export table is NULL.
525 if (DataEntry->RelativeVirtualAddress == 0)
526 return std::error_code();
528 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
529 uintptr_t IntPtr = 0;
530 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
533 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
534 return std::error_code();
537 std::error_code COFFObjectFile::initBaseRelocPtr() {
538 const data_directory *DataEntry;
539 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
540 return std::error_code();
541 if (DataEntry->RelativeVirtualAddress == 0)
542 return std::error_code();
544 uintptr_t IntPtr = 0;
545 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
547 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
549 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
550 IntPtr + DataEntry->Size);
551 return std::error_code();
554 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
555 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
556 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
557 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
558 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
559 ImportDirectory(nullptr), NumberOfImportDirectory(0),
560 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
561 ExportDirectory(nullptr), BaseRelocHeader(nullptr),
562 BaseRelocEnd(nullptr) {
563 // Check that we at least have enough room for a header.
564 if (!checkSize(Data, EC, sizeof(coff_file_header)))
567 // The current location in the file where we are looking at.
570 // PE header is optional and is present only in executables. If it exists,
571 // it is placed right after COFF header.
572 bool HasPEHeader = false;
574 // Check if this is a PE/COFF file.
575 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
576 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
577 // PE signature to find 'normal' COFF header.
578 const auto *DH = reinterpret_cast<const dos_header *>(base());
579 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
580 CurPtr = DH->AddressOfNewExeHeader;
581 // Check the PE magic bytes. ("PE\0\0")
582 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
583 EC = object_error::parse_failed;
586 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
591 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
594 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
595 // import libraries share a common prefix but bigobj is more restrictive.
596 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
597 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
598 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
599 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
602 // Verify that we are dealing with bigobj.
603 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
604 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
605 sizeof(COFF::BigObjMagic)) == 0) {
606 COFFHeader = nullptr;
607 CurPtr += sizeof(coff_bigobj_file_header);
609 // It's not a bigobj.
610 COFFBigObjHeader = nullptr;
614 // The prior checkSize call may have failed. This isn't a hard error
615 // because we were just trying to sniff out bigobj.
616 EC = std::error_code();
617 CurPtr += sizeof(coff_file_header);
619 if (COFFHeader->isImportLibrary())
624 const pe32_header *Header;
625 if ((EC = getObject(Header, Data, base() + CurPtr)))
628 const uint8_t *DataDirAddr;
629 uint64_t DataDirSize;
630 if (Header->Magic == COFF::PE32Header::PE32) {
632 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
633 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
634 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
635 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
636 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
637 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
639 // It's neither PE32 nor PE32+.
640 EC = object_error::parse_failed;
643 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
645 CurPtr += COFFHeader->SizeOfOptionalHeader;
648 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
649 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
652 // Initialize the pointer to the symbol table.
653 if (getPointerToSymbolTable() != 0) {
654 if ((EC = initSymbolTablePtr()))
657 // We had better not have any symbols if we don't have a symbol table.
658 if (getNumberOfSymbols() != 0) {
659 EC = object_error::parse_failed;
664 // Initialize the pointer to the beginning of the import table.
665 if ((EC = initImportTablePtr()))
667 if ((EC = initDelayImportTablePtr()))
670 // Initialize the pointer to the export table.
671 if ((EC = initExportTablePtr()))
674 // Initialize the pointer to the base relocation table.
675 if ((EC = initBaseRelocPtr()))
678 EC = std::error_code();
681 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
683 Ret.p = getSymbolTable();
684 return basic_symbol_iterator(SymbolRef(Ret, this));
687 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
688 // The symbol table ends where the string table begins.
690 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
691 return basic_symbol_iterator(SymbolRef(Ret, this));
694 import_directory_iterator COFFObjectFile::import_directory_begin() const {
695 return import_directory_iterator(
696 ImportDirectoryEntryRef(ImportDirectory, 0, this));
699 import_directory_iterator COFFObjectFile::import_directory_end() const {
700 return import_directory_iterator(
701 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
704 delay_import_directory_iterator
705 COFFObjectFile::delay_import_directory_begin() const {
706 return delay_import_directory_iterator(
707 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
710 delay_import_directory_iterator
711 COFFObjectFile::delay_import_directory_end() const {
712 return delay_import_directory_iterator(
713 DelayImportDirectoryEntryRef(
714 DelayImportDirectory, NumberOfDelayImportDirectory, this));
717 export_directory_iterator COFFObjectFile::export_directory_begin() const {
718 return export_directory_iterator(
719 ExportDirectoryEntryRef(ExportDirectory, 0, this));
722 export_directory_iterator COFFObjectFile::export_directory_end() const {
723 if (!ExportDirectory)
724 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
725 ExportDirectoryEntryRef Ref(ExportDirectory,
726 ExportDirectory->AddressTableEntries, this);
727 return export_directory_iterator(Ref);
730 section_iterator COFFObjectFile::section_begin() const {
732 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
733 return section_iterator(SectionRef(Ret, this));
736 section_iterator COFFObjectFile::section_end() const {
739 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
740 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
741 return section_iterator(SectionRef(Ret, this));
744 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
745 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
748 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
749 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
752 uint8_t COFFObjectFile::getBytesInAddress() const {
753 return getArch() == Triple::x86_64 ? 8 : 4;
756 StringRef COFFObjectFile::getFileFormatName() const {
757 switch(getMachine()) {
758 case COFF::IMAGE_FILE_MACHINE_I386:
760 case COFF::IMAGE_FILE_MACHINE_AMD64:
761 return "COFF-x86-64";
762 case COFF::IMAGE_FILE_MACHINE_ARMNT:
765 return "COFF-<unknown arch>";
769 unsigned COFFObjectFile::getArch() const {
770 switch (getMachine()) {
771 case COFF::IMAGE_FILE_MACHINE_I386:
773 case COFF::IMAGE_FILE_MACHINE_AMD64:
774 return Triple::x86_64;
775 case COFF::IMAGE_FILE_MACHINE_ARMNT:
776 return Triple::thumb;
778 return Triple::UnknownArch;
782 iterator_range<import_directory_iterator>
783 COFFObjectFile::import_directories() const {
784 return make_range(import_directory_begin(), import_directory_end());
787 iterator_range<delay_import_directory_iterator>
788 COFFObjectFile::delay_import_directories() const {
789 return make_range(delay_import_directory_begin(),
790 delay_import_directory_end());
793 iterator_range<export_directory_iterator>
794 COFFObjectFile::export_directories() const {
795 return make_range(export_directory_begin(), export_directory_end());
798 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
799 return make_range(base_reloc_begin(), base_reloc_end());
802 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
804 return std::error_code();
808 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
809 Res = PE32PlusHeader;
810 return std::error_code();
814 COFFObjectFile::getDataDirectory(uint32_t Index,
815 const data_directory *&Res) const {
816 // Error if if there's no data directory or the index is out of range.
817 if (!DataDirectory) {
819 return object_error::parse_failed;
821 assert(PE32Header || PE32PlusHeader);
822 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
823 : PE32PlusHeader->NumberOfRvaAndSize;
824 if (Index >= NumEnt) {
826 return object_error::parse_failed;
828 Res = &DataDirectory[Index];
829 return std::error_code();
832 std::error_code COFFObjectFile::getSection(int32_t Index,
833 const coff_section *&Result) const {
835 if (COFF::isReservedSectionNumber(Index))
836 return std::error_code();
837 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
838 // We already verified the section table data, so no need to check again.
839 Result = SectionTable + (Index - 1);
840 return std::error_code();
842 return object_error::parse_failed;
845 std::error_code COFFObjectFile::getString(uint32_t Offset,
846 StringRef &Result) const {
847 if (StringTableSize <= 4)
848 // Tried to get a string from an empty string table.
849 return object_error::parse_failed;
850 if (Offset >= StringTableSize)
851 return object_error::unexpected_eof;
852 Result = StringRef(StringTable + Offset);
853 return std::error_code();
856 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
857 StringRef &Res) const {
858 // Check for string table entry. First 4 bytes are 0.
859 if (Symbol.getStringTableOffset().Zeroes == 0) {
860 uint32_t Offset = Symbol.getStringTableOffset().Offset;
861 if (std::error_code EC = getString(Offset, Res))
863 return std::error_code();
866 if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
867 // Null terminated, let ::strlen figure out the length.
868 Res = StringRef(Symbol.getShortName());
870 // Not null terminated, use all 8 bytes.
871 Res = StringRef(Symbol.getShortName(), COFF::NameSize);
872 return std::error_code();
876 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
877 const uint8_t *Aux = nullptr;
879 size_t SymbolSize = getSymbolTableEntrySize();
880 if (Symbol.getNumberOfAuxSymbols() > 0) {
881 // AUX data comes immediately after the symbol in COFF
882 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
884 // Verify that the Aux symbol points to a valid entry in the symbol table.
885 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
886 if (Offset < getPointerToSymbolTable() ||
888 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
889 report_fatal_error("Aux Symbol data was outside of symbol table.");
891 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
892 "Aux Symbol data did not point to the beginning of a symbol");
895 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
898 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
899 StringRef &Res) const {
901 if (Sec->Name[COFF::NameSize - 1] == 0)
902 // Null terminated, let ::strlen figure out the length.
905 // Not null terminated, use all 8 bytes.
906 Name = StringRef(Sec->Name, COFF::NameSize);
908 // Check for string table entry. First byte is '/'.
909 if (Name.startswith("/")) {
911 if (Name.startswith("//")) {
912 if (decodeBase64StringEntry(Name.substr(2), Offset))
913 return object_error::parse_failed;
915 if (Name.substr(1).getAsInteger(10, Offset))
916 return object_error::parse_failed;
918 if (std::error_code EC = getString(Offset, Name))
923 return std::error_code();
926 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
927 // SizeOfRawData and VirtualSize change what they represent depending on
928 // whether or not we have an executable image.
930 // For object files, SizeOfRawData contains the size of section's data;
931 // VirtualSize is always zero.
933 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
934 // actual section size is in VirtualSize. It is possible for VirtualSize to
935 // be greater than SizeOfRawData; the contents past that point should be
936 // considered to be zero.
937 uint32_t SectionSize;
938 if (Sec->VirtualSize)
939 SectionSize = std::min(Sec->VirtualSize, Sec->SizeOfRawData);
941 SectionSize = Sec->SizeOfRawData;
947 COFFObjectFile::getSectionContents(const coff_section *Sec,
948 ArrayRef<uint8_t> &Res) const {
949 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
950 // don't do anything interesting for them.
951 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
952 "BSS sections don't have contents!");
953 // The only thing that we need to verify is that the contents is contained
954 // within the file bounds. We don't need to make sure it doesn't cover other
955 // data, as there's nothing that says that is not allowed.
956 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
957 uint32_t SectionSize = getSectionSize(Sec);
958 if (checkOffset(Data, ConStart, SectionSize))
959 return object_error::parse_failed;
960 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
961 return std::error_code();
964 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
965 return reinterpret_cast<const coff_relocation*>(Rel.p);
968 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
969 Rel.p = reinterpret_cast<uintptr_t>(
970 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
973 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
974 uint64_t &Res) const {
975 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
978 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
979 uint64_t &Res) const {
980 const coff_relocation *R = toRel(Rel);
981 const support::ulittle32_t *VirtualAddressPtr;
982 if (std::error_code EC =
983 getObject(VirtualAddressPtr, Data, &R->VirtualAddress))
985 Res = *VirtualAddressPtr;
986 return std::error_code();
989 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
990 const coff_relocation *R = toRel(Rel);
992 if (R->SymbolTableIndex >= getNumberOfSymbols())
995 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
996 else if (SymbolTable32)
997 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
999 llvm_unreachable("no symbol table pointer!");
1000 return symbol_iterator(SymbolRef(Ref, this));
1003 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
1004 uint64_t &Res) const {
1005 const coff_relocation* R = toRel(Rel);
1007 return std::error_code();
1010 const coff_section *
1011 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1012 return toSec(Section.getRawDataRefImpl());
1015 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1017 return toSymb<coff_symbol16>(Ref);
1019 return toSymb<coff_symbol32>(Ref);
1020 llvm_unreachable("no symbol table pointer!");
1023 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1024 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1027 const coff_relocation *
1028 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1029 return toRel(Reloc.getRawDataRefImpl());
1032 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1033 case COFF::reloc_type: \
1034 Res = #reloc_type; \
1038 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
1039 SmallVectorImpl<char> &Result) const {
1040 const coff_relocation *Reloc = toRel(Rel);
1042 switch (getMachine()) {
1043 case COFF::IMAGE_FILE_MACHINE_AMD64:
1044 switch (Reloc->Type) {
1045 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1046 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1047 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1048 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1049 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1050 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1051 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1052 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1053 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1054 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1055 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1056 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1057 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1058 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1059 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1060 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1061 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1066 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1067 switch (Reloc->Type) {
1068 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1069 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1070 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1071 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1072 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1073 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1074 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1075 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1076 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1077 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1078 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1079 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1080 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1081 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1082 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1087 case COFF::IMAGE_FILE_MACHINE_I386:
1088 switch (Reloc->Type) {
1089 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1090 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1091 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1092 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1093 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1094 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1095 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1096 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1097 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1098 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1099 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1107 Result.append(Res.begin(), Res.end());
1108 return std::error_code();
1111 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1113 bool COFFObjectFile::isRelocatableObject() const {
1114 return !DataDirectory;
1117 bool ImportDirectoryEntryRef::
1118 operator==(const ImportDirectoryEntryRef &Other) const {
1119 return ImportTable == Other.ImportTable && Index == Other.Index;
1122 void ImportDirectoryEntryRef::moveNext() {
1126 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1127 const import_directory_table_entry *&Result) const {
1128 Result = ImportTable + Index;
1129 return std::error_code();
1132 static imported_symbol_iterator
1133 makeImportedSymbolIterator(const COFFObjectFile *Object,
1134 uintptr_t Ptr, int Index) {
1135 if (Object->getBytesInAddress() == 4) {
1136 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1137 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1139 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1140 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1143 static imported_symbol_iterator
1144 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1145 uintptr_t IntPtr = 0;
1146 Object->getRvaPtr(RVA, IntPtr);
1147 return makeImportedSymbolIterator(Object, IntPtr, 0);
1150 static imported_symbol_iterator
1151 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1152 uintptr_t IntPtr = 0;
1153 Object->getRvaPtr(RVA, IntPtr);
1154 // Forward the pointer to the last entry which is null.
1156 if (Object->getBytesInAddress() == 4) {
1157 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1161 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1165 return makeImportedSymbolIterator(Object, IntPtr, Index);
1168 imported_symbol_iterator
1169 ImportDirectoryEntryRef::imported_symbol_begin() const {
1170 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1174 imported_symbol_iterator
1175 ImportDirectoryEntryRef::imported_symbol_end() const {
1176 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1180 iterator_range<imported_symbol_iterator>
1181 ImportDirectoryEntryRef::imported_symbols() const {
1182 return make_range(imported_symbol_begin(), imported_symbol_end());
1185 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1186 uintptr_t IntPtr = 0;
1187 if (std::error_code EC =
1188 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1190 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1191 return std::error_code();
1195 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1196 Result = ImportTable[Index].ImportLookupTableRVA;
1197 return std::error_code();
1201 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1202 Result = ImportTable[Index].ImportAddressTableRVA;
1203 return std::error_code();
1206 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1207 const import_lookup_table_entry32 *&Result) const {
1208 uintptr_t IntPtr = 0;
1209 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1210 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1212 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1213 return std::error_code();
1216 bool DelayImportDirectoryEntryRef::
1217 operator==(const DelayImportDirectoryEntryRef &Other) const {
1218 return Table == Other.Table && Index == Other.Index;
1221 void DelayImportDirectoryEntryRef::moveNext() {
1225 imported_symbol_iterator
1226 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1227 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1231 imported_symbol_iterator
1232 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1233 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1237 iterator_range<imported_symbol_iterator>
1238 DelayImportDirectoryEntryRef::imported_symbols() const {
1239 return make_range(imported_symbol_begin(), imported_symbol_end());
1242 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1243 uintptr_t IntPtr = 0;
1244 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1246 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1247 return std::error_code();
1250 std::error_code DelayImportDirectoryEntryRef::
1251 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1253 return std::error_code();
1256 std::error_code DelayImportDirectoryEntryRef::
1257 getImportAddress(int AddrIndex, uint64_t &Result) const {
1258 uint32_t RVA = Table[Index].DelayImportAddressTable +
1259 AddrIndex * (OwningObject->is64() ? 8 : 4);
1260 uintptr_t IntPtr = 0;
1261 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1263 if (OwningObject->is64())
1264 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1266 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1267 return std::error_code();
1270 bool ExportDirectoryEntryRef::
1271 operator==(const ExportDirectoryEntryRef &Other) const {
1272 return ExportTable == Other.ExportTable && Index == Other.Index;
1275 void ExportDirectoryEntryRef::moveNext() {
1279 // Returns the name of the current export symbol. If the symbol is exported only
1280 // by ordinal, the empty string is set as a result.
1281 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1282 uintptr_t IntPtr = 0;
1283 if (std::error_code EC =
1284 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1286 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1287 return std::error_code();
1290 // Returns the starting ordinal number.
1292 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1293 Result = ExportTable->OrdinalBase;
1294 return std::error_code();
1297 // Returns the export ordinal of the current export symbol.
1298 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1299 Result = ExportTable->OrdinalBase + Index;
1300 return std::error_code();
1303 // Returns the address of the current export symbol.
1304 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1305 uintptr_t IntPtr = 0;
1306 if (std::error_code EC =
1307 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1309 const export_address_table_entry *entry =
1310 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1311 Result = entry[Index].ExportRVA;
1312 return std::error_code();
1315 // Returns the name of the current export symbol. If the symbol is exported only
1316 // by ordinal, the empty string is set as a result.
1318 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1319 uintptr_t IntPtr = 0;
1320 if (std::error_code EC =
1321 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1323 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1325 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1327 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1328 I < E; ++I, ++Offset) {
1331 if (std::error_code EC =
1332 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1334 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1335 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1337 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1338 return std::error_code();
1341 return std::error_code();
1344 bool ImportedSymbolRef::
1345 operator==(const ImportedSymbolRef &Other) const {
1346 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1347 && Index == Other.Index;
1350 void ImportedSymbolRef::moveNext() {
1355 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1358 // If a symbol is imported only by ordinal, it has no name.
1359 if (Entry32[Index].isOrdinal())
1360 return std::error_code();
1361 RVA = Entry32[Index].getHintNameRVA();
1363 if (Entry64[Index].isOrdinal())
1364 return std::error_code();
1365 RVA = Entry64[Index].getHintNameRVA();
1367 uintptr_t IntPtr = 0;
1368 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1370 // +2 because the first two bytes is hint.
1371 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1372 return std::error_code();
1375 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1378 if (Entry32[Index].isOrdinal()) {
1379 Result = Entry32[Index].getOrdinal();
1380 return std::error_code();
1382 RVA = Entry32[Index].getHintNameRVA();
1384 if (Entry64[Index].isOrdinal()) {
1385 Result = Entry64[Index].getOrdinal();
1386 return std::error_code();
1388 RVA = Entry64[Index].getHintNameRVA();
1390 uintptr_t IntPtr = 0;
1391 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1393 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1394 return std::error_code();
1397 ErrorOr<std::unique_ptr<COFFObjectFile>>
1398 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1400 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1403 return std::move(Ret);
1406 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1407 return Header == Other.Header && Index == Other.Index;
1410 void BaseRelocRef::moveNext() {
1411 // Header->BlockSize is the size of the current block, including the
1412 // size of the header itself.
1413 uint32_t Size = sizeof(*Header) +
1414 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1415 if (Size == Header->BlockSize) {
1416 // .reloc contains a list of base relocation blocks. Each block
1417 // consists of the header followed by entries. The header contains
1418 // how many entories will follow. When we reach the end of the
1419 // current block, proceed to the next block.
1420 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1421 reinterpret_cast<const uint8_t *>(Header) + Size);
1428 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1429 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1430 Type = Entry[Index].getType();
1431 return std::error_code();
1434 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1435 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1436 Result = Header->PageRVA + Entry[Index].getOffset();
1437 return std::error_code();