1 //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the COFFObjectFile class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Object/COFF.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/ADT/iterator_range.h"
20 #include "llvm/Support/COFF.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
27 using namespace object;
29 using support::ulittle16_t;
30 using support::ulittle32_t;
31 using support::ulittle64_t;
32 using support::little16_t;
34 // Returns false if size is greater than the buffer size. And sets ec.
35 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
36 if (M.getBufferSize() < Size) {
37 EC = object_error::unexpected_eof;
43 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
44 const uint64_t Size) {
45 if (Addr + Size < Addr || Addr + Size < Size ||
46 Addr + Size > uintptr_t(M.getBufferEnd()) ||
47 Addr < uintptr_t(M.getBufferStart())) {
48 return object_error::unexpected_eof;
50 return std::error_code();
53 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
54 // Returns unexpected_eof if error.
56 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
58 const uint64_t Size = sizeof(T)) {
59 uintptr_t Addr = uintptr_t(Ptr);
60 if (std::error_code EC = checkOffset(M, Addr, Size))
62 Obj = reinterpret_cast<const T *>(Addr);
63 return std::error_code();
66 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
68 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
69 assert(Str.size() <= 6 && "String too long, possible overflow.");
74 while (!Str.empty()) {
76 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
77 CharVal = Str[0] - 'A';
78 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
79 CharVal = Str[0] - 'a' + 26;
80 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
81 CharVal = Str[0] - '0' + 52;
82 else if (Str[0] == '+') // 62
84 else if (Str[0] == '/') // 63
89 Value = (Value * 64) + CharVal;
93 if (Value > std::numeric_limits<uint32_t>::max())
96 Result = static_cast<uint32_t>(Value);
100 template <typename coff_symbol_type>
101 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
102 const coff_symbol_type *Addr =
103 reinterpret_cast<const coff_symbol_type *>(Ref.p);
105 assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
107 // Verify that the symbol points to a valid entry in the symbol table.
108 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
110 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
111 "Symbol did not point to the beginning of a symbol");
117 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
118 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
121 // Verify that the section points to a valid entry in the section table.
122 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
123 report_fatal_error("Section was outside of section table.");
125 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
126 assert(Offset % sizeof(coff_section) == 0 &&
127 "Section did not point to the beginning of a section");
133 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
134 auto End = reinterpret_cast<uintptr_t>(StringTable);
136 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
137 Symb += 1 + Symb->NumberOfAuxSymbols;
138 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
139 } else if (SymbolTable32) {
140 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
141 Symb += 1 + Symb->NumberOfAuxSymbols;
142 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
144 llvm_unreachable("no symbol table pointer!");
148 ErrorOr<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
149 COFFSymbolRef Symb = getCOFFSymbol(Ref);
151 std::error_code EC = getSymbolName(Symb, Result);
157 uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const {
158 return getCOFFSymbol(Ref).getValue();
161 ErrorOr<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
162 uint64_t Result = getSymbolValue(Ref);
163 COFFSymbolRef Symb = getCOFFSymbol(Ref);
164 int32_t SectionNumber = Symb.getSectionNumber();
166 if (Symb.isAnyUndefined() || Symb.isCommon() ||
167 COFF::isReservedSectionNumber(SectionNumber))
170 const coff_section *Section = nullptr;
171 if (std::error_code EC = getSection(SectionNumber, Section))
173 Result += Section->VirtualAddress;
177 SymbolRef::Type COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
178 COFFSymbolRef Symb = getCOFFSymbol(Ref);
179 int32_t SectionNumber = Symb.getSectionNumber();
181 if (Symb.isAnyUndefined())
182 return SymbolRef::ST_Unknown;
183 if (Symb.isFunctionDefinition())
184 return SymbolRef::ST_Function;
186 return SymbolRef::ST_Data;
187 if (Symb.isFileRecord())
188 return SymbolRef::ST_File;
190 // TODO: perhaps we need a new symbol type ST_Section.
191 if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
192 return SymbolRef::ST_Debug;
194 if (!COFF::isReservedSectionNumber(SectionNumber))
195 return SymbolRef::ST_Data;
197 return SymbolRef::ST_Other;
200 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
201 COFFSymbolRef Symb = getCOFFSymbol(Ref);
202 uint32_t Result = SymbolRef::SF_None;
204 if (Symb.isExternal() || Symb.isWeakExternal())
205 Result |= SymbolRef::SF_Global;
207 if (Symb.isWeakExternal())
208 Result |= SymbolRef::SF_Weak;
210 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
211 Result |= SymbolRef::SF_Absolute;
213 if (Symb.isFileRecord())
214 Result |= SymbolRef::SF_FormatSpecific;
216 if (Symb.isSectionDefinition())
217 Result |= SymbolRef::SF_FormatSpecific;
220 Result |= SymbolRef::SF_Common;
222 if (Symb.isAnyUndefined())
223 Result |= SymbolRef::SF_Undefined;
228 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
229 COFFSymbolRef Symb = getCOFFSymbol(Ref);
230 return Symb.getValue();
234 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
235 section_iterator &Result) const {
236 COFFSymbolRef Symb = getCOFFSymbol(Ref);
237 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
238 Result = section_end();
240 const coff_section *Sec = nullptr;
241 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
244 Ref.p = reinterpret_cast<uintptr_t>(Sec);
245 Result = section_iterator(SectionRef(Ref, this));
247 return std::error_code();
250 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
251 COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
252 return Symb.getSectionNumber();
255 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
256 const coff_section *Sec = toSec(Ref);
258 Ref.p = reinterpret_cast<uintptr_t>(Sec);
261 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
262 StringRef &Result) const {
263 const coff_section *Sec = toSec(Ref);
264 return getSectionName(Sec, Result);
267 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
268 const coff_section *Sec = toSec(Ref);
269 return Sec->VirtualAddress;
272 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
273 return getSectionSize(toSec(Ref));
276 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
277 StringRef &Result) const {
278 const coff_section *Sec = toSec(Ref);
279 ArrayRef<uint8_t> Res;
280 std::error_code EC = getSectionContents(Sec, Res);
281 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
285 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
286 const coff_section *Sec = toSec(Ref);
287 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
290 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
291 const coff_section *Sec = toSec(Ref);
292 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
295 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
296 const coff_section *Sec = toSec(Ref);
297 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
300 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
301 const coff_section *Sec = toSec(Ref);
302 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
303 COFF::IMAGE_SCN_MEM_READ |
304 COFF::IMAGE_SCN_MEM_WRITE;
305 return (Sec->Characteristics & BssFlags) == BssFlags;
308 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
310 uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
311 assert((Offset % sizeof(coff_section)) == 0);
312 return (Offset / sizeof(coff_section)) + 1;
315 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
316 const coff_section *Sec = toSec(Ref);
317 // In COFF, a virtual section won't have any in-file
318 // content, so the file pointer to the content will be zero.
319 return Sec->PointerToRawData == 0;
322 static uint32_t getNumberOfRelocations(const coff_section *Sec,
323 MemoryBufferRef M, const uint8_t *base) {
324 // The field for the number of relocations in COFF section table is only
325 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
326 // NumberOfRelocations field, and the actual relocation count is stored in the
327 // VirtualAddress field in the first relocation entry.
328 if (Sec->hasExtendedRelocations()) {
329 const coff_relocation *FirstReloc;
330 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
331 base + Sec->PointerToRelocations)))
333 // -1 to exclude this first relocation entry.
334 return FirstReloc->VirtualAddress - 1;
336 return Sec->NumberOfRelocations;
339 static const coff_relocation *
340 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
341 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
344 auto begin = reinterpret_cast<const coff_relocation *>(
345 Base + Sec->PointerToRelocations);
346 if (Sec->hasExtendedRelocations()) {
347 // Skip the first relocation entry repurposed to store the number of
351 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
356 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
357 const coff_section *Sec = toSec(Ref);
358 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
359 if (begin && Sec->VirtualAddress != 0)
360 report_fatal_error("Sections with relocations should have an address of 0");
362 Ret.p = reinterpret_cast<uintptr_t>(begin);
363 return relocation_iterator(RelocationRef(Ret, this));
366 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
367 const coff_section *Sec = toSec(Ref);
368 const coff_relocation *I = getFirstReloc(Sec, Data, base());
370 I += getNumberOfRelocations(Sec, Data, base());
372 Ret.p = reinterpret_cast<uintptr_t>(I);
373 return relocation_iterator(RelocationRef(Ret, this));
376 // Initialize the pointer to the symbol table.
377 std::error_code COFFObjectFile::initSymbolTablePtr() {
379 if (std::error_code EC = getObject(
380 SymbolTable16, Data, base() + getPointerToSymbolTable(),
381 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
384 if (COFFBigObjHeader)
385 if (std::error_code EC = getObject(
386 SymbolTable32, Data, base() + getPointerToSymbolTable(),
387 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
390 // Find string table. The first four byte of the string table contains the
391 // total size of the string table, including the size field itself. If the
392 // string table is empty, the value of the first four byte would be 4.
393 uint32_t StringTableOffset = getPointerToSymbolTable() +
394 getNumberOfSymbols() * getSymbolTableEntrySize();
395 const uint8_t *StringTableAddr = base() + StringTableOffset;
396 const ulittle32_t *StringTableSizePtr;
397 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
399 StringTableSize = *StringTableSizePtr;
400 if (std::error_code EC =
401 getObject(StringTable, Data, StringTableAddr, StringTableSize))
404 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
405 // tools like cvtres write a size of 0 for an empty table instead of 4.
406 if (StringTableSize < 4)
409 // Check that the string table is null terminated if has any in it.
410 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
411 return object_error::parse_failed;
412 return std::error_code();
415 // Returns the file offset for the given VA.
416 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
417 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
418 : (uint64_t)PE32PlusHeader->ImageBase;
419 uint64_t Rva = Addr - ImageBase;
420 assert(Rva <= UINT32_MAX);
421 return getRvaPtr((uint32_t)Rva, Res);
424 // Returns the file offset for the given RVA.
425 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
426 for (const SectionRef &S : sections()) {
427 const coff_section *Section = getCOFFSection(S);
428 uint32_t SectionStart = Section->VirtualAddress;
429 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
430 if (SectionStart <= Addr && Addr < SectionEnd) {
431 uint32_t Offset = Addr - SectionStart;
432 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
433 return std::error_code();
436 return object_error::parse_failed;
439 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
441 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
442 StringRef &Name) const {
443 uintptr_t IntPtr = 0;
444 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
446 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
447 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
448 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
449 return std::error_code();
452 // Find the import table.
453 std::error_code COFFObjectFile::initImportTablePtr() {
454 // First, we get the RVA of the import table. If the file lacks a pointer to
455 // the import table, do nothing.
456 const data_directory *DataEntry;
457 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
458 return std::error_code();
460 // Do nothing if the pointer to import table is NULL.
461 if (DataEntry->RelativeVirtualAddress == 0)
462 return std::error_code();
464 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
465 // -1 because the last entry is the null entry.
466 NumberOfImportDirectory = DataEntry->Size /
467 sizeof(import_directory_table_entry) - 1;
469 // Find the section that contains the RVA. This is needed because the RVA is
470 // the import table's memory address which is different from its file offset.
471 uintptr_t IntPtr = 0;
472 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
474 ImportDirectory = reinterpret_cast<
475 const import_directory_table_entry *>(IntPtr);
476 return std::error_code();
479 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
480 std::error_code COFFObjectFile::initDelayImportTablePtr() {
481 const data_directory *DataEntry;
482 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
483 return std::error_code();
484 if (DataEntry->RelativeVirtualAddress == 0)
485 return std::error_code();
487 uint32_t RVA = DataEntry->RelativeVirtualAddress;
488 NumberOfDelayImportDirectory = DataEntry->Size /
489 sizeof(delay_import_directory_table_entry) - 1;
491 uintptr_t IntPtr = 0;
492 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
494 DelayImportDirectory = reinterpret_cast<
495 const delay_import_directory_table_entry *>(IntPtr);
496 return std::error_code();
499 // Find the export table.
500 std::error_code COFFObjectFile::initExportTablePtr() {
501 // First, we get the RVA of the export table. If the file lacks a pointer to
502 // the export table, do nothing.
503 const data_directory *DataEntry;
504 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
505 return std::error_code();
507 // Do nothing if the pointer to export table is NULL.
508 if (DataEntry->RelativeVirtualAddress == 0)
509 return std::error_code();
511 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
512 uintptr_t IntPtr = 0;
513 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
516 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
517 return std::error_code();
520 std::error_code COFFObjectFile::initBaseRelocPtr() {
521 const data_directory *DataEntry;
522 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
523 return std::error_code();
524 if (DataEntry->RelativeVirtualAddress == 0)
525 return std::error_code();
527 uintptr_t IntPtr = 0;
528 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
530 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
532 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
533 IntPtr + DataEntry->Size);
534 return std::error_code();
537 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
538 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
539 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
540 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
541 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
542 ImportDirectory(nullptr), NumberOfImportDirectory(0),
543 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
544 ExportDirectory(nullptr), BaseRelocHeader(nullptr),
545 BaseRelocEnd(nullptr) {
546 // Check that we at least have enough room for a header.
547 if (!checkSize(Data, EC, sizeof(coff_file_header)))
550 // The current location in the file where we are looking at.
553 // PE header is optional and is present only in executables. If it exists,
554 // it is placed right after COFF header.
555 bool HasPEHeader = false;
557 // Check if this is a PE/COFF file.
558 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
559 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
560 // PE signature to find 'normal' COFF header.
561 const auto *DH = reinterpret_cast<const dos_header *>(base());
562 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
563 CurPtr = DH->AddressOfNewExeHeader;
564 // Check the PE magic bytes. ("PE\0\0")
565 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
566 EC = object_error::parse_failed;
569 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
574 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
577 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
578 // import libraries share a common prefix but bigobj is more restrictive.
579 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
580 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
581 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
582 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
585 // Verify that we are dealing with bigobj.
586 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
587 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
588 sizeof(COFF::BigObjMagic)) == 0) {
589 COFFHeader = nullptr;
590 CurPtr += sizeof(coff_bigobj_file_header);
592 // It's not a bigobj.
593 COFFBigObjHeader = nullptr;
597 // The prior checkSize call may have failed. This isn't a hard error
598 // because we were just trying to sniff out bigobj.
599 EC = std::error_code();
600 CurPtr += sizeof(coff_file_header);
602 if (COFFHeader->isImportLibrary())
607 const pe32_header *Header;
608 if ((EC = getObject(Header, Data, base() + CurPtr)))
611 const uint8_t *DataDirAddr;
612 uint64_t DataDirSize;
613 if (Header->Magic == COFF::PE32Header::PE32) {
615 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
616 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
617 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
618 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
619 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
620 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
622 // It's neither PE32 nor PE32+.
623 EC = object_error::parse_failed;
626 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
628 CurPtr += COFFHeader->SizeOfOptionalHeader;
631 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
632 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
635 // Initialize the pointer to the symbol table.
636 if (getPointerToSymbolTable() != 0) {
637 if ((EC = initSymbolTablePtr()))
640 // We had better not have any symbols if we don't have a symbol table.
641 if (getNumberOfSymbols() != 0) {
642 EC = object_error::parse_failed;
647 // Initialize the pointer to the beginning of the import table.
648 if ((EC = initImportTablePtr()))
650 if ((EC = initDelayImportTablePtr()))
653 // Initialize the pointer to the export table.
654 if ((EC = initExportTablePtr()))
657 // Initialize the pointer to the base relocation table.
658 if ((EC = initBaseRelocPtr()))
661 EC = std::error_code();
664 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
666 Ret.p = getSymbolTable();
667 return basic_symbol_iterator(SymbolRef(Ret, this));
670 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
671 // The symbol table ends where the string table begins.
673 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
674 return basic_symbol_iterator(SymbolRef(Ret, this));
677 import_directory_iterator COFFObjectFile::import_directory_begin() const {
678 return import_directory_iterator(
679 ImportDirectoryEntryRef(ImportDirectory, 0, this));
682 import_directory_iterator COFFObjectFile::import_directory_end() const {
683 return import_directory_iterator(
684 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
687 delay_import_directory_iterator
688 COFFObjectFile::delay_import_directory_begin() const {
689 return delay_import_directory_iterator(
690 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
693 delay_import_directory_iterator
694 COFFObjectFile::delay_import_directory_end() const {
695 return delay_import_directory_iterator(
696 DelayImportDirectoryEntryRef(
697 DelayImportDirectory, NumberOfDelayImportDirectory, this));
700 export_directory_iterator COFFObjectFile::export_directory_begin() const {
701 return export_directory_iterator(
702 ExportDirectoryEntryRef(ExportDirectory, 0, this));
705 export_directory_iterator COFFObjectFile::export_directory_end() const {
706 if (!ExportDirectory)
707 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
708 ExportDirectoryEntryRef Ref(ExportDirectory,
709 ExportDirectory->AddressTableEntries, this);
710 return export_directory_iterator(Ref);
713 section_iterator COFFObjectFile::section_begin() const {
715 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
716 return section_iterator(SectionRef(Ret, this));
719 section_iterator COFFObjectFile::section_end() const {
722 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
723 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
724 return section_iterator(SectionRef(Ret, this));
727 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
728 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
731 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
732 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
735 uint8_t COFFObjectFile::getBytesInAddress() const {
736 return getArch() == Triple::x86_64 ? 8 : 4;
739 StringRef COFFObjectFile::getFileFormatName() const {
740 switch(getMachine()) {
741 case COFF::IMAGE_FILE_MACHINE_I386:
743 case COFF::IMAGE_FILE_MACHINE_AMD64:
744 return "COFF-x86-64";
745 case COFF::IMAGE_FILE_MACHINE_ARMNT:
748 return "COFF-<unknown arch>";
752 unsigned COFFObjectFile::getArch() const {
753 switch (getMachine()) {
754 case COFF::IMAGE_FILE_MACHINE_I386:
756 case COFF::IMAGE_FILE_MACHINE_AMD64:
757 return Triple::x86_64;
758 case COFF::IMAGE_FILE_MACHINE_ARMNT:
759 return Triple::thumb;
761 return Triple::UnknownArch;
765 iterator_range<import_directory_iterator>
766 COFFObjectFile::import_directories() const {
767 return make_range(import_directory_begin(), import_directory_end());
770 iterator_range<delay_import_directory_iterator>
771 COFFObjectFile::delay_import_directories() const {
772 return make_range(delay_import_directory_begin(),
773 delay_import_directory_end());
776 iterator_range<export_directory_iterator>
777 COFFObjectFile::export_directories() const {
778 return make_range(export_directory_begin(), export_directory_end());
781 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
782 return make_range(base_reloc_begin(), base_reloc_end());
785 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
787 return std::error_code();
791 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
792 Res = PE32PlusHeader;
793 return std::error_code();
797 COFFObjectFile::getDataDirectory(uint32_t Index,
798 const data_directory *&Res) const {
799 // Error if if there's no data directory or the index is out of range.
800 if (!DataDirectory) {
802 return object_error::parse_failed;
804 assert(PE32Header || PE32PlusHeader);
805 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
806 : PE32PlusHeader->NumberOfRvaAndSize;
807 if (Index >= NumEnt) {
809 return object_error::parse_failed;
811 Res = &DataDirectory[Index];
812 return std::error_code();
815 std::error_code COFFObjectFile::getSection(int32_t Index,
816 const coff_section *&Result) const {
818 if (COFF::isReservedSectionNumber(Index))
819 return std::error_code();
820 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
821 // We already verified the section table data, so no need to check again.
822 Result = SectionTable + (Index - 1);
823 return std::error_code();
825 return object_error::parse_failed;
828 std::error_code COFFObjectFile::getString(uint32_t Offset,
829 StringRef &Result) const {
830 if (StringTableSize <= 4)
831 // Tried to get a string from an empty string table.
832 return object_error::parse_failed;
833 if (Offset >= StringTableSize)
834 return object_error::unexpected_eof;
835 Result = StringRef(StringTable + Offset);
836 return std::error_code();
839 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
840 StringRef &Res) const {
841 return getSymbolName(Symbol.getGeneric(), Res);
844 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
845 StringRef &Res) const {
846 // Check for string table entry. First 4 bytes are 0.
847 if (Symbol->Name.Offset.Zeroes == 0) {
848 if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
850 return std::error_code();
853 if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
854 // Null terminated, let ::strlen figure out the length.
855 Res = StringRef(Symbol->Name.ShortName);
857 // Not null terminated, use all 8 bytes.
858 Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
859 return std::error_code();
863 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
864 const uint8_t *Aux = nullptr;
866 size_t SymbolSize = getSymbolTableEntrySize();
867 if (Symbol.getNumberOfAuxSymbols() > 0) {
868 // AUX data comes immediately after the symbol in COFF
869 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
871 // Verify that the Aux symbol points to a valid entry in the symbol table.
872 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
873 if (Offset < getPointerToSymbolTable() ||
875 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
876 report_fatal_error("Aux Symbol data was outside of symbol table.");
878 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
879 "Aux Symbol data did not point to the beginning of a symbol");
882 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
885 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
886 StringRef &Res) const {
888 if (Sec->Name[COFF::NameSize - 1] == 0)
889 // Null terminated, let ::strlen figure out the length.
892 // Not null terminated, use all 8 bytes.
893 Name = StringRef(Sec->Name, COFF::NameSize);
895 // Check for string table entry. First byte is '/'.
896 if (Name.startswith("/")) {
898 if (Name.startswith("//")) {
899 if (decodeBase64StringEntry(Name.substr(2), Offset))
900 return object_error::parse_failed;
902 if (Name.substr(1).getAsInteger(10, Offset))
903 return object_error::parse_failed;
905 if (std::error_code EC = getString(Offset, Name))
910 return std::error_code();
913 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
914 // SizeOfRawData and VirtualSize change what they represent depending on
915 // whether or not we have an executable image.
917 // For object files, SizeOfRawData contains the size of section's data;
918 // VirtualSize should be zero but isn't due to buggy COFF writers.
920 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
921 // actual section size is in VirtualSize. It is possible for VirtualSize to
922 // be greater than SizeOfRawData; the contents past that point should be
923 // considered to be zero.
925 return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
926 return Sec->SizeOfRawData;
930 COFFObjectFile::getSectionContents(const coff_section *Sec,
931 ArrayRef<uint8_t> &Res) const {
932 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
933 // don't do anything interesting for them.
934 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
935 "BSS sections don't have contents!");
936 // The only thing that we need to verify is that the contents is contained
937 // within the file bounds. We don't need to make sure it doesn't cover other
938 // data, as there's nothing that says that is not allowed.
939 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
940 uint32_t SectionSize = getSectionSize(Sec);
941 if (checkOffset(Data, ConStart, SectionSize))
942 return object_error::parse_failed;
943 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
944 return std::error_code();
947 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
948 return reinterpret_cast<const coff_relocation*>(Rel.p);
951 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
952 Rel.p = reinterpret_cast<uintptr_t>(
953 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
956 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
957 const coff_relocation *R = toRel(Rel);
958 return R->VirtualAddress;
961 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
962 const coff_relocation *R = toRel(Rel);
964 if (R->SymbolTableIndex >= getNumberOfSymbols())
967 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
968 else if (SymbolTable32)
969 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
971 llvm_unreachable("no symbol table pointer!");
972 return symbol_iterator(SymbolRef(Ref, this));
975 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
976 const coff_relocation* R = toRel(Rel);
981 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
982 return toSec(Section.getRawDataRefImpl());
985 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
987 return toSymb<coff_symbol16>(Ref);
989 return toSymb<coff_symbol32>(Ref);
990 llvm_unreachable("no symbol table pointer!");
993 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
994 return getCOFFSymbol(Symbol.getRawDataRefImpl());
997 const coff_relocation *
998 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
999 return toRel(Reloc.getRawDataRefImpl());
1002 iterator_range<const coff_relocation *>
1003 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1004 const coff_relocation *I = getFirstReloc(Sec, Data, base());
1005 const coff_relocation *E = I;
1007 E += getNumberOfRelocations(Sec, Data, base());
1008 return make_range(I, E);
1011 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1012 case COFF::reloc_type: \
1013 Res = #reloc_type; \
1016 void COFFObjectFile::getRelocationTypeName(
1017 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1018 const coff_relocation *Reloc = toRel(Rel);
1020 switch (getMachine()) {
1021 case COFF::IMAGE_FILE_MACHINE_AMD64:
1022 switch (Reloc->Type) {
1023 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1024 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1025 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1026 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1027 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1028 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1029 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1030 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1031 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1032 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1033 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1034 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1035 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1036 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1037 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1038 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1039 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1044 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1045 switch (Reloc->Type) {
1046 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1047 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1048 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1049 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1050 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1051 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1052 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1053 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1054 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1055 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1056 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1057 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1058 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1059 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1060 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1065 case COFF::IMAGE_FILE_MACHINE_I386:
1066 switch (Reloc->Type) {
1067 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1068 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1069 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1070 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1071 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1072 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1073 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1074 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1075 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1076 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1077 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1085 Result.append(Res.begin(), Res.end());
1088 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1090 bool COFFObjectFile::isRelocatableObject() const {
1091 return !DataDirectory;
1094 bool ImportDirectoryEntryRef::
1095 operator==(const ImportDirectoryEntryRef &Other) const {
1096 return ImportTable == Other.ImportTable && Index == Other.Index;
1099 void ImportDirectoryEntryRef::moveNext() {
1103 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1104 const import_directory_table_entry *&Result) const {
1105 Result = ImportTable + Index;
1106 return std::error_code();
1109 static imported_symbol_iterator
1110 makeImportedSymbolIterator(const COFFObjectFile *Object,
1111 uintptr_t Ptr, int Index) {
1112 if (Object->getBytesInAddress() == 4) {
1113 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1114 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1116 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1117 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1120 static imported_symbol_iterator
1121 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1122 uintptr_t IntPtr = 0;
1123 Object->getRvaPtr(RVA, IntPtr);
1124 return makeImportedSymbolIterator(Object, IntPtr, 0);
1127 static imported_symbol_iterator
1128 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1129 uintptr_t IntPtr = 0;
1130 Object->getRvaPtr(RVA, IntPtr);
1131 // Forward the pointer to the last entry which is null.
1133 if (Object->getBytesInAddress() == 4) {
1134 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1138 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1142 return makeImportedSymbolIterator(Object, IntPtr, Index);
1145 imported_symbol_iterator
1146 ImportDirectoryEntryRef::imported_symbol_begin() const {
1147 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1151 imported_symbol_iterator
1152 ImportDirectoryEntryRef::imported_symbol_end() const {
1153 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1157 iterator_range<imported_symbol_iterator>
1158 ImportDirectoryEntryRef::imported_symbols() const {
1159 return make_range(imported_symbol_begin(), imported_symbol_end());
1162 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1163 uintptr_t IntPtr = 0;
1164 if (std::error_code EC =
1165 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1167 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1168 return std::error_code();
1172 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1173 Result = ImportTable[Index].ImportLookupTableRVA;
1174 return std::error_code();
1178 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1179 Result = ImportTable[Index].ImportAddressTableRVA;
1180 return std::error_code();
1183 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1184 const import_lookup_table_entry32 *&Result) const {
1185 uintptr_t IntPtr = 0;
1186 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1187 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1189 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1190 return std::error_code();
1193 bool DelayImportDirectoryEntryRef::
1194 operator==(const DelayImportDirectoryEntryRef &Other) const {
1195 return Table == Other.Table && Index == Other.Index;
1198 void DelayImportDirectoryEntryRef::moveNext() {
1202 imported_symbol_iterator
1203 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1204 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1208 imported_symbol_iterator
1209 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1210 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1214 iterator_range<imported_symbol_iterator>
1215 DelayImportDirectoryEntryRef::imported_symbols() const {
1216 return make_range(imported_symbol_begin(), imported_symbol_end());
1219 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1220 uintptr_t IntPtr = 0;
1221 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1223 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1224 return std::error_code();
1227 std::error_code DelayImportDirectoryEntryRef::
1228 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1230 return std::error_code();
1233 std::error_code DelayImportDirectoryEntryRef::
1234 getImportAddress(int AddrIndex, uint64_t &Result) const {
1235 uint32_t RVA = Table[Index].DelayImportAddressTable +
1236 AddrIndex * (OwningObject->is64() ? 8 : 4);
1237 uintptr_t IntPtr = 0;
1238 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1240 if (OwningObject->is64())
1241 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1243 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1244 return std::error_code();
1247 bool ExportDirectoryEntryRef::
1248 operator==(const ExportDirectoryEntryRef &Other) const {
1249 return ExportTable == Other.ExportTable && Index == Other.Index;
1252 void ExportDirectoryEntryRef::moveNext() {
1256 // Returns the name of the current export symbol. If the symbol is exported only
1257 // by ordinal, the empty string is set as a result.
1258 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1259 uintptr_t IntPtr = 0;
1260 if (std::error_code EC =
1261 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1263 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1264 return std::error_code();
1267 // Returns the starting ordinal number.
1269 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1270 Result = ExportTable->OrdinalBase;
1271 return std::error_code();
1274 // Returns the export ordinal of the current export symbol.
1275 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1276 Result = ExportTable->OrdinalBase + Index;
1277 return std::error_code();
1280 // Returns the address of the current export symbol.
1281 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1282 uintptr_t IntPtr = 0;
1283 if (std::error_code EC =
1284 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1286 const export_address_table_entry *entry =
1287 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1288 Result = entry[Index].ExportRVA;
1289 return std::error_code();
1292 // Returns the name of the current export symbol. If the symbol is exported only
1293 // by ordinal, the empty string is set as a result.
1295 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1296 uintptr_t IntPtr = 0;
1297 if (std::error_code EC =
1298 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1300 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1302 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1304 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1305 I < E; ++I, ++Offset) {
1308 if (std::error_code EC =
1309 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1311 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1312 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1314 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1315 return std::error_code();
1318 return std::error_code();
1321 bool ImportedSymbolRef::
1322 operator==(const ImportedSymbolRef &Other) const {
1323 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1324 && Index == Other.Index;
1327 void ImportedSymbolRef::moveNext() {
1332 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1335 // If a symbol is imported only by ordinal, it has no name.
1336 if (Entry32[Index].isOrdinal())
1337 return std::error_code();
1338 RVA = Entry32[Index].getHintNameRVA();
1340 if (Entry64[Index].isOrdinal())
1341 return std::error_code();
1342 RVA = Entry64[Index].getHintNameRVA();
1344 uintptr_t IntPtr = 0;
1345 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1347 // +2 because the first two bytes is hint.
1348 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1349 return std::error_code();
1352 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1355 if (Entry32[Index].isOrdinal()) {
1356 Result = Entry32[Index].getOrdinal();
1357 return std::error_code();
1359 RVA = Entry32[Index].getHintNameRVA();
1361 if (Entry64[Index].isOrdinal()) {
1362 Result = Entry64[Index].getOrdinal();
1363 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 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1371 return std::error_code();
1374 ErrorOr<std::unique_ptr<COFFObjectFile>>
1375 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1377 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1380 return std::move(Ret);
1383 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1384 return Header == Other.Header && Index == Other.Index;
1387 void BaseRelocRef::moveNext() {
1388 // Header->BlockSize is the size of the current block, including the
1389 // size of the header itself.
1390 uint32_t Size = sizeof(*Header) +
1391 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1392 if (Size == Header->BlockSize) {
1393 // .reloc contains a list of base relocation blocks. Each block
1394 // consists of the header followed by entries. The header contains
1395 // how many entories will follow. When we reach the end of the
1396 // current block, proceed to the next block.
1397 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1398 reinterpret_cast<const uint8_t *>(Header) + Size);
1405 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1406 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1407 Type = Entry[Index].getType();
1408 return std::error_code();
1411 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1412 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1413 Result = Header->PageRVA + Entry[Index].getOffset();
1414 return std::error_code();