1 //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the COFFObjectFile class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Object/COFF.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/Support/COFF.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
27 using namespace object;
29 using support::ulittle16_t;
30 using support::ulittle32_t;
31 using support::ulittle64_t;
32 using support::little16_t;
34 // Returns false if size is greater than the buffer size. And sets ec.
35 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
36 if (M.getBufferSize() < Size) {
37 EC = object_error::unexpected_eof;
43 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
44 const uint64_t Size) {
45 if (Addr + Size < Addr || Addr + Size < Size ||
46 Addr + Size > uintptr_t(M.getBufferEnd()) ||
47 Addr < uintptr_t(M.getBufferStart())) {
48 return object_error::unexpected_eof;
50 return std::error_code();
53 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
54 // Returns unexpected_eof if error.
56 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
58 const uint64_t Size = sizeof(T)) {
59 uintptr_t Addr = uintptr_t(Ptr);
60 if (std::error_code EC = checkOffset(M, Addr, Size))
62 Obj = reinterpret_cast<const T *>(Addr);
63 return std::error_code();
66 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
68 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
69 assert(Str.size() <= 6 && "String too long, possible overflow.");
74 while (!Str.empty()) {
76 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
77 CharVal = Str[0] - 'A';
78 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
79 CharVal = Str[0] - 'a' + 26;
80 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
81 CharVal = Str[0] - '0' + 52;
82 else if (Str[0] == '+') // 62
84 else if (Str[0] == '/') // 63
89 Value = (Value * 64) + CharVal;
93 if (Value > std::numeric_limits<uint32_t>::max())
96 Result = static_cast<uint32_t>(Value);
100 template <typename coff_symbol_type>
101 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
102 const coff_symbol_type *Addr =
103 reinterpret_cast<const coff_symbol_type *>(Ref.p);
105 assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
107 // Verify that the symbol points to a valid entry in the symbol table.
108 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
110 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
111 "Symbol did not point to the beginning of a symbol");
117 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
118 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
121 // Verify that the section points to a valid entry in the section table.
122 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
123 report_fatal_error("Section was outside of section table.");
125 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
126 assert(Offset % sizeof(coff_section) == 0 &&
127 "Section did not point to the beginning of a section");
133 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
134 auto End = reinterpret_cast<uintptr_t>(StringTable);
136 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
137 Symb += 1 + Symb->NumberOfAuxSymbols;
138 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
139 } else if (SymbolTable32) {
140 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
141 Symb += 1 + Symb->NumberOfAuxSymbols;
142 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
144 llvm_unreachable("no symbol table pointer!");
148 ErrorOr<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
149 COFFSymbolRef Symb = getCOFFSymbol(Ref);
151 std::error_code EC = getSymbolName(Symb, Result);
157 uint64_t COFFObjectFile::getSymbolValue(DataRefImpl Ref) const {
158 COFFSymbolRef Sym = getCOFFSymbol(Ref);
160 if (Sym.isAnyUndefined() || Sym.isCommon())
161 return UnknownAddress;
163 return Sym.getValue();
166 ErrorOr<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
167 uint64_t Result = getSymbolValue(Ref);
168 COFFSymbolRef Symb = getCOFFSymbol(Ref);
169 int32_t SectionNumber = Symb.getSectionNumber();
171 if (Symb.isAnyUndefined() || Symb.isCommon() ||
172 COFF::isReservedSectionNumber(SectionNumber))
175 const coff_section *Section = nullptr;
176 if (std::error_code EC = getSection(SectionNumber, Section))
178 Result += Section->VirtualAddress;
182 SymbolRef::Type COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
183 COFFSymbolRef Symb = getCOFFSymbol(Ref);
184 int32_t SectionNumber = Symb.getSectionNumber();
186 if (Symb.isAnyUndefined())
187 return SymbolRef::ST_Unknown;
188 if (Symb.isFunctionDefinition())
189 return SymbolRef::ST_Function;
191 return SymbolRef::ST_Data;
192 if (Symb.isFileRecord())
193 return SymbolRef::ST_File;
195 // TODO: perhaps we need a new symbol type ST_Section.
196 if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
197 return SymbolRef::ST_Debug;
199 if (!COFF::isReservedSectionNumber(SectionNumber))
200 return SymbolRef::ST_Data;
202 return SymbolRef::ST_Other;
205 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
206 COFFSymbolRef Symb = getCOFFSymbol(Ref);
207 uint32_t Result = SymbolRef::SF_None;
209 if (Symb.isExternal() || Symb.isWeakExternal())
210 Result |= SymbolRef::SF_Global;
212 if (Symb.isWeakExternal())
213 Result |= SymbolRef::SF_Weak;
215 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
216 Result |= SymbolRef::SF_Absolute;
218 if (Symb.isFileRecord())
219 Result |= SymbolRef::SF_FormatSpecific;
221 if (Symb.isSectionDefinition())
222 Result |= SymbolRef::SF_FormatSpecific;
225 Result |= SymbolRef::SF_Common;
227 if (Symb.isAnyUndefined())
228 Result |= SymbolRef::SF_Undefined;
233 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
234 COFFSymbolRef Symb = getCOFFSymbol(Ref);
235 return Symb.getValue();
239 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
240 section_iterator &Result) const {
241 COFFSymbolRef Symb = getCOFFSymbol(Ref);
242 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
243 Result = section_end();
245 const coff_section *Sec = nullptr;
246 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
249 Ref.p = reinterpret_cast<uintptr_t>(Sec);
250 Result = section_iterator(SectionRef(Ref, this));
252 return std::error_code();
255 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
256 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
257 return Symb.getSectionNumber();
260 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
261 const coff_section *Sec = toSec(Ref);
263 Ref.p = reinterpret_cast<uintptr_t>(Sec);
266 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
267 StringRef &Result) const {
268 const coff_section *Sec = toSec(Ref);
269 return getSectionName(Sec, Result);
272 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
273 const coff_section *Sec = toSec(Ref);
274 return Sec->VirtualAddress;
277 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
278 return getSectionSize(toSec(Ref));
281 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
282 StringRef &Result) const {
283 const coff_section *Sec = toSec(Ref);
284 ArrayRef<uint8_t> Res;
285 std::error_code EC = getSectionContents(Sec, Res);
286 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
290 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
291 const coff_section *Sec = toSec(Ref);
292 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
295 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
296 const coff_section *Sec = toSec(Ref);
297 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
300 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
301 const coff_section *Sec = toSec(Ref);
302 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
305 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
306 const coff_section *Sec = toSec(Ref);
307 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
308 COFF::IMAGE_SCN_MEM_READ |
309 COFF::IMAGE_SCN_MEM_WRITE;
310 return (Sec->Characteristics & BssFlags) == BssFlags;
313 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
315 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
316 assert((Offset % sizeof(coff_section)) == 0);
317 return (Offset / sizeof(coff_section)) + 1;
320 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
321 const coff_section *Sec = toSec(Ref);
322 // In COFF, a virtual section won't have any in-file
323 // content, so the file pointer to the content will be zero.
324 return Sec->PointerToRawData == 0;
327 static uint32_t getNumberOfRelocations(const coff_section *Sec,
328 MemoryBufferRef M, const uint8_t *base) {
329 // The field for the number of relocations in COFF section table is only
330 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
331 // NumberOfRelocations field, and the actual relocation count is stored in the
332 // VirtualAddress field in the first relocation entry.
333 if (Sec->hasExtendedRelocations()) {
334 const coff_relocation *FirstReloc;
335 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
336 base + Sec->PointerToRelocations)))
338 // -1 to exclude this first relocation entry.
339 return FirstReloc->VirtualAddress - 1;
341 return Sec->NumberOfRelocations;
344 static const coff_relocation *
345 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
346 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
349 auto begin = reinterpret_cast<const coff_relocation *>(
350 Base + Sec->PointerToRelocations);
351 if (Sec->hasExtendedRelocations()) {
352 // Skip the first relocation entry repurposed to store the number of
356 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
361 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
362 const coff_section *Sec = toSec(Ref);
363 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
365 Ret.p = reinterpret_cast<uintptr_t>(begin);
366 return relocation_iterator(RelocationRef(Ret, this));
369 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
370 const coff_section *Sec = toSec(Ref);
371 const coff_relocation *I = getFirstReloc(Sec, Data, base());
373 I += getNumberOfRelocations(Sec, Data, base());
375 Ret.p = reinterpret_cast<uintptr_t>(I);
376 return relocation_iterator(RelocationRef(Ret, this));
379 // Initialize the pointer to the symbol table.
380 std::error_code COFFObjectFile::initSymbolTablePtr() {
382 if (std::error_code EC = getObject(
383 SymbolTable16, Data, base() + getPointerToSymbolTable(),
384 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
387 if (COFFBigObjHeader)
388 if (std::error_code EC = getObject(
389 SymbolTable32, Data, base() + getPointerToSymbolTable(),
390 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
393 // Find string table. The first four byte of the string table contains the
394 // total size of the string table, including the size field itself. If the
395 // string table is empty, the value of the first four byte would be 4.
396 uint32_t StringTableOffset = getPointerToSymbolTable() +
397 getNumberOfSymbols() * getSymbolTableEntrySize();
398 const uint8_t *StringTableAddr = base() + StringTableOffset;
399 const ulittle32_t *StringTableSizePtr;
400 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
402 StringTableSize = *StringTableSizePtr;
403 if (std::error_code EC =
404 getObject(StringTable, Data, StringTableAddr, StringTableSize))
407 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
408 // tools like cvtres write a size of 0 for an empty table instead of 4.
409 if (StringTableSize < 4)
412 // Check that the string table is null terminated if has any in it.
413 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
414 return object_error::parse_failed;
415 return std::error_code();
418 // Returns the file offset for the given VA.
419 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
420 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
421 : (uint64_t)PE32PlusHeader->ImageBase;
422 uint64_t Rva = Addr - ImageBase;
423 assert(Rva <= UINT32_MAX);
424 return getRvaPtr((uint32_t)Rva, Res);
427 // Returns the file offset for the given RVA.
428 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
429 for (const SectionRef &S : sections()) {
430 const coff_section *Section = getCOFFSection(S);
431 uint32_t SectionStart = Section->VirtualAddress;
432 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
433 if (SectionStart <= Addr && Addr < SectionEnd) {
434 uint32_t Offset = Addr - SectionStart;
435 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
436 return std::error_code();
439 return object_error::parse_failed;
442 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
444 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
445 StringRef &Name) const {
446 uintptr_t IntPtr = 0;
447 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
449 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
450 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
451 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
452 return std::error_code();
455 // Find the import table.
456 std::error_code COFFObjectFile::initImportTablePtr() {
457 // First, we get the RVA of the import table. If the file lacks a pointer to
458 // the import table, do nothing.
459 const data_directory *DataEntry;
460 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
461 return std::error_code();
463 // Do nothing if the pointer to import table is NULL.
464 if (DataEntry->RelativeVirtualAddress == 0)
465 return std::error_code();
467 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
468 // -1 because the last entry is the null entry.
469 NumberOfImportDirectory = DataEntry->Size /
470 sizeof(import_directory_table_entry) - 1;
472 // Find the section that contains the RVA. This is needed because the RVA is
473 // the import table's memory address which is different from its file offset.
474 uintptr_t IntPtr = 0;
475 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
477 ImportDirectory = reinterpret_cast<
478 const import_directory_table_entry *>(IntPtr);
479 return std::error_code();
482 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
483 std::error_code COFFObjectFile::initDelayImportTablePtr() {
484 const data_directory *DataEntry;
485 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
486 return std::error_code();
487 if (DataEntry->RelativeVirtualAddress == 0)
488 return std::error_code();
490 uint32_t RVA = DataEntry->RelativeVirtualAddress;
491 NumberOfDelayImportDirectory = DataEntry->Size /
492 sizeof(delay_import_directory_table_entry) - 1;
494 uintptr_t IntPtr = 0;
495 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
497 DelayImportDirectory = reinterpret_cast<
498 const delay_import_directory_table_entry *>(IntPtr);
499 return std::error_code();
502 // Find the export table.
503 std::error_code COFFObjectFile::initExportTablePtr() {
504 // First, we get the RVA of the export table. If the file lacks a pointer to
505 // the export table, do nothing.
506 const data_directory *DataEntry;
507 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
508 return std::error_code();
510 // Do nothing if the pointer to export table is NULL.
511 if (DataEntry->RelativeVirtualAddress == 0)
512 return std::error_code();
514 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
515 uintptr_t IntPtr = 0;
516 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
519 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
520 return std::error_code();
523 std::error_code COFFObjectFile::initBaseRelocPtr() {
524 const data_directory *DataEntry;
525 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
526 return std::error_code();
527 if (DataEntry->RelativeVirtualAddress == 0)
528 return std::error_code();
530 uintptr_t IntPtr = 0;
531 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
533 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
535 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
536 IntPtr + DataEntry->Size);
537 return std::error_code();
540 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
541 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
542 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
543 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
544 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
545 ImportDirectory(nullptr), NumberOfImportDirectory(0),
546 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
547 ExportDirectory(nullptr), BaseRelocHeader(nullptr),
548 BaseRelocEnd(nullptr) {
549 // Check that we at least have enough room for a header.
550 if (!checkSize(Data, EC, sizeof(coff_file_header)))
553 // The current location in the file where we are looking at.
556 // PE header is optional and is present only in executables. If it exists,
557 // it is placed right after COFF header.
558 bool HasPEHeader = false;
560 // Check if this is a PE/COFF file.
561 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
562 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
563 // PE signature to find 'normal' COFF header.
564 const auto *DH = reinterpret_cast<const dos_header *>(base());
565 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
566 CurPtr = DH->AddressOfNewExeHeader;
567 // Check the PE magic bytes. ("PE\0\0")
568 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
569 EC = object_error::parse_failed;
572 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
577 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
580 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
581 // import libraries share a common prefix but bigobj is more restrictive.
582 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
583 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
584 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
585 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
588 // Verify that we are dealing with bigobj.
589 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
590 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
591 sizeof(COFF::BigObjMagic)) == 0) {
592 COFFHeader = nullptr;
593 CurPtr += sizeof(coff_bigobj_file_header);
595 // It's not a bigobj.
596 COFFBigObjHeader = nullptr;
600 // The prior checkSize call may have failed. This isn't a hard error
601 // because we were just trying to sniff out bigobj.
602 EC = std::error_code();
603 CurPtr += sizeof(coff_file_header);
605 if (COFFHeader->isImportLibrary())
610 const pe32_header *Header;
611 if ((EC = getObject(Header, Data, base() + CurPtr)))
614 const uint8_t *DataDirAddr;
615 uint64_t DataDirSize;
616 if (Header->Magic == COFF::PE32Header::PE32) {
618 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
619 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
620 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
621 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
622 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
623 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
625 // It's neither PE32 nor PE32+.
626 EC = object_error::parse_failed;
629 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
631 CurPtr += COFFHeader->SizeOfOptionalHeader;
634 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
635 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
638 // Initialize the pointer to the symbol table.
639 if (getPointerToSymbolTable() != 0) {
640 if ((EC = initSymbolTablePtr()))
643 // We had better not have any symbols if we don't have a symbol table.
644 if (getNumberOfSymbols() != 0) {
645 EC = object_error::parse_failed;
650 // Initialize the pointer to the beginning of the import table.
651 if ((EC = initImportTablePtr()))
653 if ((EC = initDelayImportTablePtr()))
656 // Initialize the pointer to the export table.
657 if ((EC = initExportTablePtr()))
660 // Initialize the pointer to the base relocation table.
661 if ((EC = initBaseRelocPtr()))
664 EC = std::error_code();
667 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
669 Ret.p = getSymbolTable();
670 return basic_symbol_iterator(SymbolRef(Ret, this));
673 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
674 // The symbol table ends where the string table begins.
676 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
677 return basic_symbol_iterator(SymbolRef(Ret, this));
680 import_directory_iterator COFFObjectFile::import_directory_begin() const {
681 return import_directory_iterator(
682 ImportDirectoryEntryRef(ImportDirectory, 0, this));
685 import_directory_iterator COFFObjectFile::import_directory_end() const {
686 return import_directory_iterator(
687 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
690 delay_import_directory_iterator
691 COFFObjectFile::delay_import_directory_begin() const {
692 return delay_import_directory_iterator(
693 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
696 delay_import_directory_iterator
697 COFFObjectFile::delay_import_directory_end() const {
698 return delay_import_directory_iterator(
699 DelayImportDirectoryEntryRef(
700 DelayImportDirectory, NumberOfDelayImportDirectory, this));
703 export_directory_iterator COFFObjectFile::export_directory_begin() const {
704 return export_directory_iterator(
705 ExportDirectoryEntryRef(ExportDirectory, 0, this));
708 export_directory_iterator COFFObjectFile::export_directory_end() const {
709 if (!ExportDirectory)
710 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
711 ExportDirectoryEntryRef Ref(ExportDirectory,
712 ExportDirectory->AddressTableEntries, this);
713 return export_directory_iterator(Ref);
716 section_iterator COFFObjectFile::section_begin() const {
718 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
719 return section_iterator(SectionRef(Ret, this));
722 section_iterator COFFObjectFile::section_end() const {
725 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
726 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
727 return section_iterator(SectionRef(Ret, this));
730 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
731 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
734 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
735 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
738 uint8_t COFFObjectFile::getBytesInAddress() const {
739 return getArch() == Triple::x86_64 ? 8 : 4;
742 StringRef COFFObjectFile::getFileFormatName() const {
743 switch(getMachine()) {
744 case COFF::IMAGE_FILE_MACHINE_I386:
746 case COFF::IMAGE_FILE_MACHINE_AMD64:
747 return "COFF-x86-64";
748 case COFF::IMAGE_FILE_MACHINE_ARMNT:
751 return "COFF-<unknown arch>";
755 unsigned COFFObjectFile::getArch() const {
756 switch (getMachine()) {
757 case COFF::IMAGE_FILE_MACHINE_I386:
759 case COFF::IMAGE_FILE_MACHINE_AMD64:
760 return Triple::x86_64;
761 case COFF::IMAGE_FILE_MACHINE_ARMNT:
762 return Triple::thumb;
764 return Triple::UnknownArch;
768 iterator_range<import_directory_iterator>
769 COFFObjectFile::import_directories() const {
770 return make_range(import_directory_begin(), import_directory_end());
773 iterator_range<delay_import_directory_iterator>
774 COFFObjectFile::delay_import_directories() const {
775 return make_range(delay_import_directory_begin(),
776 delay_import_directory_end());
779 iterator_range<export_directory_iterator>
780 COFFObjectFile::export_directories() const {
781 return make_range(export_directory_begin(), export_directory_end());
784 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
785 return make_range(base_reloc_begin(), base_reloc_end());
788 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
790 return std::error_code();
794 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
795 Res = PE32PlusHeader;
796 return std::error_code();
800 COFFObjectFile::getDataDirectory(uint32_t Index,
801 const data_directory *&Res) const {
802 // Error if if there's no data directory or the index is out of range.
803 if (!DataDirectory) {
805 return object_error::parse_failed;
807 assert(PE32Header || PE32PlusHeader);
808 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
809 : PE32PlusHeader->NumberOfRvaAndSize;
810 if (Index >= NumEnt) {
812 return object_error::parse_failed;
814 Res = &DataDirectory[Index];
815 return std::error_code();
818 std::error_code COFFObjectFile::getSection(int32_t Index,
819 const coff_section *&Result) const {
821 if (COFF::isReservedSectionNumber(Index))
822 return std::error_code();
823 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
824 // We already verified the section table data, so no need to check again.
825 Result = SectionTable + (Index - 1);
826 return std::error_code();
828 return object_error::parse_failed;
831 std::error_code COFFObjectFile::getString(uint32_t Offset,
832 StringRef &Result) const {
833 if (StringTableSize <= 4)
834 // Tried to get a string from an empty string table.
835 return object_error::parse_failed;
836 if (Offset >= StringTableSize)
837 return object_error::unexpected_eof;
838 Result = StringRef(StringTable + Offset);
839 return std::error_code();
842 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
843 StringRef &Res) const {
844 return getSymbolName(Symbol.getGeneric(), Res);
847 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
848 StringRef &Res) const {
849 // Check for string table entry. First 4 bytes are 0.
850 if (Symbol->Name.Offset.Zeroes == 0) {
851 if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
853 return std::error_code();
856 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
857 // Null terminated, let ::strlen figure out the length.
858 Res = StringRef(Symbol->Name.ShortName);
860 // Not null terminated, use all 8 bytes.
861 Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
862 return std::error_code();
866 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
867 const uint8_t *Aux = nullptr;
869 size_t SymbolSize = getSymbolTableEntrySize();
870 if (Symbol.getNumberOfAuxSymbols() > 0) {
871 // AUX data comes immediately after the symbol in COFF
872 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
874 // Verify that the Aux symbol points to a valid entry in the symbol table.
875 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
876 if (Offset < getPointerToSymbolTable() ||
878 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
879 report_fatal_error("Aux Symbol data was outside of symbol table.");
881 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
882 "Aux Symbol data did not point to the beginning of a symbol");
885 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
888 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
889 StringRef &Res) const {
891 if (Sec->Name[COFF::NameSize - 1] == 0)
892 // Null terminated, let ::strlen figure out the length.
895 // Not null terminated, use all 8 bytes.
896 Name = StringRef(Sec->Name, COFF::NameSize);
898 // Check for string table entry. First byte is '/'.
899 if (Name.startswith("/")) {
901 if (Name.startswith("//")) {
902 if (decodeBase64StringEntry(Name.substr(2), Offset))
903 return object_error::parse_failed;
905 if (Name.substr(1).getAsInteger(10, Offset))
906 return object_error::parse_failed;
908 if (std::error_code EC = getString(Offset, Name))
913 return std::error_code();
916 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
917 // SizeOfRawData and VirtualSize change what they represent depending on
918 // whether or not we have an executable image.
920 // For object files, SizeOfRawData contains the size of section's data;
921 // VirtualSize is always zero.
923 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
924 // actual section size is in VirtualSize. It is possible for VirtualSize to
925 // be greater than SizeOfRawData; the contents past that point should be
926 // considered to be zero.
927 uint32_t SectionSize;
928 if (Sec->VirtualSize)
929 SectionSize = std::min(Sec->VirtualSize, Sec->SizeOfRawData);
931 SectionSize = Sec->SizeOfRawData;
937 COFFObjectFile::getSectionContents(const coff_section *Sec,
938 ArrayRef<uint8_t> &Res) const {
939 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
940 // don't do anything interesting for them.
941 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
942 "BSS sections don't have contents!");
943 // The only thing that we need to verify is that the contents is contained
944 // within the file bounds. We don't need to make sure it doesn't cover other
945 // data, as there's nothing that says that is not allowed.
946 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
947 uint32_t SectionSize = getSectionSize(Sec);
948 if (checkOffset(Data, ConStart, SectionSize))
949 return object_error::parse_failed;
950 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
951 return std::error_code();
954 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
955 return reinterpret_cast<const coff_relocation*>(Rel.p);
958 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
959 Rel.p = reinterpret_cast<uintptr_t>(
960 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
963 ErrorOr<uint64_t> COFFObjectFile::getRelocationAddress(DataRefImpl Rel) const {
964 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
967 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
968 const coff_relocation *R = toRel(Rel);
969 return R->VirtualAddress;
972 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
973 const coff_relocation *R = toRel(Rel);
975 if (R->SymbolTableIndex >= getNumberOfSymbols())
978 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
979 else if (SymbolTable32)
980 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
982 llvm_unreachable("no symbol table pointer!");
983 return symbol_iterator(SymbolRef(Ref, this));
986 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
987 const coff_relocation* R = toRel(Rel);
992 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
993 return toSec(Section.getRawDataRefImpl());
996 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
998 return toSymb<coff_symbol16>(Ref);
1000 return toSymb<coff_symbol32>(Ref);
1001 llvm_unreachable("no symbol table pointer!");
1004 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1005 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1008 const coff_relocation *
1009 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1010 return toRel(Reloc.getRawDataRefImpl());
1013 iterator_range<const coff_relocation *>
1014 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1015 const coff_relocation *I = getFirstReloc(Sec, Data, base());
1016 const coff_relocation *E = I;
1018 E += getNumberOfRelocations(Sec, Data, base());
1019 return make_range(I, E);
1022 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1023 case COFF::reloc_type: \
1024 Res = #reloc_type; \
1027 void COFFObjectFile::getRelocationTypeName(
1028 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1029 const coff_relocation *Reloc = toRel(Rel);
1031 switch (getMachine()) {
1032 case COFF::IMAGE_FILE_MACHINE_AMD64:
1033 switch (Reloc->Type) {
1034 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1035 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1036 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1037 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1038 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1039 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1040 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1041 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1042 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1043 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1044 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1045 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1046 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1047 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1048 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1049 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1050 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1055 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1056 switch (Reloc->Type) {
1057 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1058 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1059 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1060 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1061 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1062 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1063 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1064 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1065 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1066 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1067 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1068 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1069 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1070 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1071 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1076 case COFF::IMAGE_FILE_MACHINE_I386:
1077 switch (Reloc->Type) {
1078 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1079 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1080 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1081 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1082 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1083 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1084 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1085 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1086 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1087 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1088 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1096 Result.append(Res.begin(), Res.end());
1099 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1101 bool COFFObjectFile::isRelocatableObject() const {
1102 return !DataDirectory;
1105 bool ImportDirectoryEntryRef::
1106 operator==(const ImportDirectoryEntryRef &Other) const {
1107 return ImportTable == Other.ImportTable && Index == Other.Index;
1110 void ImportDirectoryEntryRef::moveNext() {
1114 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1115 const import_directory_table_entry *&Result) const {
1116 Result = ImportTable + Index;
1117 return std::error_code();
1120 static imported_symbol_iterator
1121 makeImportedSymbolIterator(const COFFObjectFile *Object,
1122 uintptr_t Ptr, int Index) {
1123 if (Object->getBytesInAddress() == 4) {
1124 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1125 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1127 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1128 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1131 static imported_symbol_iterator
1132 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1133 uintptr_t IntPtr = 0;
1134 Object->getRvaPtr(RVA, IntPtr);
1135 return makeImportedSymbolIterator(Object, IntPtr, 0);
1138 static imported_symbol_iterator
1139 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1140 uintptr_t IntPtr = 0;
1141 Object->getRvaPtr(RVA, IntPtr);
1142 // Forward the pointer to the last entry which is null.
1144 if (Object->getBytesInAddress() == 4) {
1145 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1149 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1153 return makeImportedSymbolIterator(Object, IntPtr, Index);
1156 imported_symbol_iterator
1157 ImportDirectoryEntryRef::imported_symbol_begin() const {
1158 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1162 imported_symbol_iterator
1163 ImportDirectoryEntryRef::imported_symbol_end() const {
1164 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1168 iterator_range<imported_symbol_iterator>
1169 ImportDirectoryEntryRef::imported_symbols() const {
1170 return make_range(imported_symbol_begin(), imported_symbol_end());
1173 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1174 uintptr_t IntPtr = 0;
1175 if (std::error_code EC =
1176 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1178 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1179 return std::error_code();
1183 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1184 Result = ImportTable[Index].ImportLookupTableRVA;
1185 return std::error_code();
1189 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1190 Result = ImportTable[Index].ImportAddressTableRVA;
1191 return std::error_code();
1194 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1195 const import_lookup_table_entry32 *&Result) const {
1196 uintptr_t IntPtr = 0;
1197 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1198 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1200 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1201 return std::error_code();
1204 bool DelayImportDirectoryEntryRef::
1205 operator==(const DelayImportDirectoryEntryRef &Other) const {
1206 return Table == Other.Table && Index == Other.Index;
1209 void DelayImportDirectoryEntryRef::moveNext() {
1213 imported_symbol_iterator
1214 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1215 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1219 imported_symbol_iterator
1220 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1221 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1225 iterator_range<imported_symbol_iterator>
1226 DelayImportDirectoryEntryRef::imported_symbols() const {
1227 return make_range(imported_symbol_begin(), imported_symbol_end());
1230 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1231 uintptr_t IntPtr = 0;
1232 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1234 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1235 return std::error_code();
1238 std::error_code DelayImportDirectoryEntryRef::
1239 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1241 return std::error_code();
1244 std::error_code DelayImportDirectoryEntryRef::
1245 getImportAddress(int AddrIndex, uint64_t &Result) const {
1246 uint32_t RVA = Table[Index].DelayImportAddressTable +
1247 AddrIndex * (OwningObject->is64() ? 8 : 4);
1248 uintptr_t IntPtr = 0;
1249 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1251 if (OwningObject->is64())
1252 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1254 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1255 return std::error_code();
1258 bool ExportDirectoryEntryRef::
1259 operator==(const ExportDirectoryEntryRef &Other) const {
1260 return ExportTable == Other.ExportTable && Index == Other.Index;
1263 void ExportDirectoryEntryRef::moveNext() {
1267 // Returns the name of the current export symbol. If the symbol is exported only
1268 // by ordinal, the empty string is set as a result.
1269 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1270 uintptr_t IntPtr = 0;
1271 if (std::error_code EC =
1272 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1274 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1275 return std::error_code();
1278 // Returns the starting ordinal number.
1280 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1281 Result = ExportTable->OrdinalBase;
1282 return std::error_code();
1285 // Returns the export ordinal of the current export symbol.
1286 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1287 Result = ExportTable->OrdinalBase + Index;
1288 return std::error_code();
1291 // Returns the address of the current export symbol.
1292 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1293 uintptr_t IntPtr = 0;
1294 if (std::error_code EC =
1295 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1297 const export_address_table_entry *entry =
1298 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1299 Result = entry[Index].ExportRVA;
1300 return std::error_code();
1303 // Returns the name of the current export symbol. If the symbol is exported only
1304 // by ordinal, the empty string is set as a result.
1306 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1307 uintptr_t IntPtr = 0;
1308 if (std::error_code EC =
1309 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1311 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1313 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1315 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1316 I < E; ++I, ++Offset) {
1319 if (std::error_code EC =
1320 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1322 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1323 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1325 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1326 return std::error_code();
1329 return std::error_code();
1332 bool ImportedSymbolRef::
1333 operator==(const ImportedSymbolRef &Other) const {
1334 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1335 && Index == Other.Index;
1338 void ImportedSymbolRef::moveNext() {
1343 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1346 // If a symbol is imported only by ordinal, it has no name.
1347 if (Entry32[Index].isOrdinal())
1348 return std::error_code();
1349 RVA = Entry32[Index].getHintNameRVA();
1351 if (Entry64[Index].isOrdinal())
1352 return std::error_code();
1353 RVA = Entry64[Index].getHintNameRVA();
1355 uintptr_t IntPtr = 0;
1356 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1358 // +2 because the first two bytes is hint.
1359 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1360 return std::error_code();
1363 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1366 if (Entry32[Index].isOrdinal()) {
1367 Result = Entry32[Index].getOrdinal();
1368 return std::error_code();
1370 RVA = Entry32[Index].getHintNameRVA();
1372 if (Entry64[Index].isOrdinal()) {
1373 Result = Entry64[Index].getOrdinal();
1374 return std::error_code();
1376 RVA = Entry64[Index].getHintNameRVA();
1378 uintptr_t IntPtr = 0;
1379 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1381 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1382 return std::error_code();
1385 ErrorOr<std::unique_ptr<COFFObjectFile>>
1386 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1388 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1391 return std::move(Ret);
1394 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1395 return Header == Other.Header && Index == Other.Index;
1398 void BaseRelocRef::moveNext() {
1399 // Header->BlockSize is the size of the current block, including the
1400 // size of the header itself.
1401 uint32_t Size = sizeof(*Header) +
1402 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1403 if (Size == Header->BlockSize) {
1404 // .reloc contains a list of base relocation blocks. Each block
1405 // consists of the header followed by entries. The header contains
1406 // how many entories will follow. When we reach the end of the
1407 // current block, proceed to the next block.
1408 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1409 reinterpret_cast<const uint8_t *>(Header) + Size);
1416 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1417 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1418 Type = Entry[Index].getType();
1419 return std::error_code();
1422 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1423 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1424 Result = Header->PageRVA + Entry[Index].getOffset();
1425 return std::error_code();