1 //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the COFFObjectFile class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Object/COFF.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Support/COFF.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
26 using namespace object;
28 using support::ulittle16_t;
29 using support::ulittle32_t;
30 using support::ulittle64_t;
31 using support::little16_t;
33 // Returns false if size is greater than the buffer size. And sets ec.
34 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
35 if (M.getBufferSize() < Size) {
36 EC = object_error::unexpected_eof;
42 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
43 const uint64_t Size) {
44 if (Addr + Size < Addr || Addr + Size < Size ||
45 Addr + Size > uintptr_t(M.getBufferEnd()) ||
46 Addr < uintptr_t(M.getBufferStart())) {
47 return object_error::unexpected_eof;
49 return std::error_code();
52 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
53 // Returns unexpected_eof if error.
55 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
57 const uint64_t Size = sizeof(T)) {
58 uintptr_t Addr = uintptr_t(Ptr);
59 if (std::error_code EC = checkOffset(M, Addr, Size))
61 Obj = reinterpret_cast<const T *>(Addr);
62 return std::error_code();
65 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
67 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
68 assert(Str.size() <= 6 && "String too long, possible overflow.");
73 while (!Str.empty()) {
75 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
76 CharVal = Str[0] - 'A';
77 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
78 CharVal = Str[0] - 'a' + 26;
79 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
80 CharVal = Str[0] - '0' + 52;
81 else if (Str[0] == '+') // 62
83 else if (Str[0] == '/') // 63
88 Value = (Value * 64) + CharVal;
92 if (Value > std::numeric_limits<uint32_t>::max())
95 Result = static_cast<uint32_t>(Value);
99 template <typename coff_symbol_type>
100 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
101 const coff_symbol_type *Addr =
102 reinterpret_cast<const coff_symbol_type *>(Ref.p);
104 assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
106 // Verify that the symbol points to a valid entry in the symbol table.
107 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
109 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
110 "Symbol did not point to the beginning of a symbol");
116 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
117 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
120 // Verify that the section points to a valid entry in the section table.
121 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
122 report_fatal_error("Section was outside of section table.");
124 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
125 assert(Offset % sizeof(coff_section) == 0 &&
126 "Section did not point to the beginning of a section");
132 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
133 auto End = reinterpret_cast<uintptr_t>(StringTable);
135 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
136 Symb += 1 + Symb->NumberOfAuxSymbols;
137 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
138 } else if (SymbolTable32) {
139 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
140 Symb += 1 + Symb->NumberOfAuxSymbols;
141 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
143 llvm_unreachable("no symbol table pointer!");
147 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
148 StringRef &Result) const {
149 COFFSymbolRef Symb = getCOFFSymbol(Ref);
150 return getSymbolName(Symb, Result);
153 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
154 uint64_t &Result) const {
155 COFFSymbolRef Symb = getCOFFSymbol(Ref);
157 if (Symb.isAnyUndefined() || Symb.isCommon()) {
158 Result = UnknownAddress;
159 return std::error_code();
162 int32_t SectionNumber = Symb.getSectionNumber();
163 if (COFF::isReservedSectionNumber(SectionNumber)) {
164 Result = Symb.getValue();
165 return std::error_code();
168 const coff_section *Section = nullptr;
169 if (std::error_code EC = getSection(SectionNumber, Section))
171 Result = Section->VirtualAddress + Symb.getValue();
172 return std::error_code();
175 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
176 SymbolRef::Type &Result) const {
177 COFFSymbolRef Symb = getCOFFSymbol(Ref);
178 int32_t SectionNumber = Symb.getSectionNumber();
179 Result = SymbolRef::ST_Other;
181 if (Symb.isAnyUndefined()) {
182 Result = SymbolRef::ST_Unknown;
183 } else if (Symb.isFunctionDefinition()) {
184 Result = SymbolRef::ST_Function;
185 } else if (Symb.isCommon()) {
186 Result = SymbolRef::ST_Data;
187 } else if (Symb.isFileRecord()) {
188 Result = SymbolRef::ST_File;
189 } else if (SectionNumber == COFF::IMAGE_SYM_DEBUG ||
190 Symb.isSectionDefinition()) {
191 // TODO: perhaps we need a new symbol type ST_Section.
192 Result = SymbolRef::ST_Debug;
193 } else if (!COFF::isReservedSectionNumber(SectionNumber)) {
194 const coff_section *Section = nullptr;
195 if (std::error_code EC = getSection(SectionNumber, Section))
197 uint32_t Characteristics = Section->Characteristics;
198 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
199 Result = SymbolRef::ST_Function;
200 else if (Characteristics & (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
201 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA))
202 Result = SymbolRef::ST_Data;
204 return std::error_code();
207 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
208 COFFSymbolRef Symb = getCOFFSymbol(Ref);
209 uint32_t Result = SymbolRef::SF_None;
211 if (Symb.isExternal() || Symb.isWeakExternal())
212 Result |= SymbolRef::SF_Global;
214 if (Symb.isWeakExternal())
215 Result |= SymbolRef::SF_Weak;
217 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
218 Result |= SymbolRef::SF_Absolute;
220 if (Symb.isFileRecord())
221 Result |= SymbolRef::SF_FormatSpecific;
223 if (Symb.isSectionDefinition())
224 Result |= SymbolRef::SF_FormatSpecific;
227 Result |= SymbolRef::SF_Common;
229 if (Symb.isAnyUndefined())
230 Result |= SymbolRef::SF_Undefined;
235 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
236 COFFSymbolRef Symb = getCOFFSymbol(Ref);
237 return Symb.getValue();
241 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
242 section_iterator &Result) const {
243 COFFSymbolRef Symb = getCOFFSymbol(Ref);
244 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
245 Result = section_end();
247 const coff_section *Sec = nullptr;
248 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
251 Ref.p = reinterpret_cast<uintptr_t>(Sec);
252 Result = section_iterator(SectionRef(Ref, this));
254 return std::error_code();
257 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
258 const coff_section *Sec = toSec(Ref);
260 Ref.p = reinterpret_cast<uintptr_t>(Sec);
263 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
264 StringRef &Result) const {
265 const coff_section *Sec = toSec(Ref);
266 return getSectionName(Sec, Result);
269 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
270 const coff_section *Sec = toSec(Ref);
271 return Sec->VirtualAddress;
274 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
275 return getSectionSize(toSec(Ref));
278 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
279 StringRef &Result) const {
280 const coff_section *Sec = toSec(Ref);
281 ArrayRef<uint8_t> Res;
282 std::error_code EC = getSectionContents(Sec, Res);
283 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
287 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
288 const coff_section *Sec = toSec(Ref);
289 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
292 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
293 const coff_section *Sec = toSec(Ref);
294 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
297 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
298 const coff_section *Sec = toSec(Ref);
299 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
302 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
303 const coff_section *Sec = toSec(Ref);
304 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
305 COFF::IMAGE_SCN_MEM_READ |
306 COFF::IMAGE_SCN_MEM_WRITE;
307 return (Sec->Characteristics & BssFlags) == BssFlags;
310 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
311 const coff_section *Sec = toSec(Ref);
312 // In COFF, a virtual section won't have any in-file
313 // content, so the file pointer to the content will be zero.
314 return Sec->PointerToRawData == 0;
317 bool COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
318 DataRefImpl SymbRef) const {
319 const coff_section *Sec = toSec(SecRef);
320 COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
321 int32_t SecNumber = (Sec - SectionTable) + 1;
322 return SecNumber == Symb.getSectionNumber();
325 static uint32_t getNumberOfRelocations(const coff_section *Sec,
326 MemoryBufferRef M, const uint8_t *base) {
327 // The field for the number of relocations in COFF section table is only
328 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
329 // NumberOfRelocations field, and the actual relocation count is stored in the
330 // VirtualAddress field in the first relocation entry.
331 if (Sec->hasExtendedRelocations()) {
332 const coff_relocation *FirstReloc;
333 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
334 base + Sec->PointerToRelocations)))
336 // -1 to exclude this first relocation entry.
337 return FirstReloc->VirtualAddress - 1;
339 return Sec->NumberOfRelocations;
342 static const coff_relocation *
343 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
344 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
347 auto begin = reinterpret_cast<const coff_relocation *>(
348 Base + Sec->PointerToRelocations);
349 if (Sec->hasExtendedRelocations()) {
350 // Skip the first relocation entry repurposed to store the number of
354 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
359 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
360 const coff_section *Sec = toSec(Ref);
361 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
363 Ret.p = reinterpret_cast<uintptr_t>(begin);
364 return relocation_iterator(RelocationRef(Ret, this));
367 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
368 const coff_section *Sec = toSec(Ref);
369 const coff_relocation *I = getFirstReloc(Sec, Data, base());
371 I += getNumberOfRelocations(Sec, Data, base());
373 Ret.p = reinterpret_cast<uintptr_t>(I);
374 return relocation_iterator(RelocationRef(Ret, this));
377 // Initialize the pointer to the symbol table.
378 std::error_code COFFObjectFile::initSymbolTablePtr() {
380 if (std::error_code EC = getObject(
381 SymbolTable16, Data, base() + getPointerToSymbolTable(),
382 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
385 if (COFFBigObjHeader)
386 if (std::error_code EC = getObject(
387 SymbolTable32, Data, base() + getPointerToSymbolTable(),
388 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
391 // Find string table. The first four byte of the string table contains the
392 // total size of the string table, including the size field itself. If the
393 // string table is empty, the value of the first four byte would be 4.
394 uint32_t StringTableOffset = getPointerToSymbolTable() +
395 getNumberOfSymbols() * getSymbolTableEntrySize();
396 const uint8_t *StringTableAddr = base() + StringTableOffset;
397 const ulittle32_t *StringTableSizePtr;
398 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
400 StringTableSize = *StringTableSizePtr;
401 if (std::error_code EC =
402 getObject(StringTable, Data, StringTableAddr, StringTableSize))
405 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
406 // tools like cvtres write a size of 0 for an empty table instead of 4.
407 if (StringTableSize < 4)
410 // Check that the string table is null terminated if has any in it.
411 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
412 return object_error::parse_failed;
413 return std::error_code();
416 // Returns the file offset for the given VA.
417 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
418 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
419 : (uint64_t)PE32PlusHeader->ImageBase;
420 uint64_t Rva = Addr - ImageBase;
421 assert(Rva <= UINT32_MAX);
422 return getRvaPtr((uint32_t)Rva, Res);
425 // Returns the file offset for the given RVA.
426 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
427 for (const SectionRef &S : sections()) {
428 const coff_section *Section = getCOFFSection(S);
429 uint32_t SectionStart = Section->VirtualAddress;
430 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
431 if (SectionStart <= Addr && Addr < SectionEnd) {
432 uint32_t Offset = Addr - SectionStart;
433 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
434 return std::error_code();
437 return object_error::parse_failed;
440 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
442 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
443 StringRef &Name) const {
444 uintptr_t IntPtr = 0;
445 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
447 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
448 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
449 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
450 return std::error_code();
453 // Find the import table.
454 std::error_code COFFObjectFile::initImportTablePtr() {
455 // First, we get the RVA of the import table. If the file lacks a pointer to
456 // the import table, do nothing.
457 const data_directory *DataEntry;
458 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
459 return std::error_code();
461 // Do nothing if the pointer to import table is NULL.
462 if (DataEntry->RelativeVirtualAddress == 0)
463 return std::error_code();
465 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
466 // -1 because the last entry is the null entry.
467 NumberOfImportDirectory = DataEntry->Size /
468 sizeof(import_directory_table_entry) - 1;
470 // Find the section that contains the RVA. This is needed because the RVA is
471 // the import table's memory address which is different from its file offset.
472 uintptr_t IntPtr = 0;
473 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
475 ImportDirectory = reinterpret_cast<
476 const import_directory_table_entry *>(IntPtr);
477 return std::error_code();
480 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
481 std::error_code COFFObjectFile::initDelayImportTablePtr() {
482 const data_directory *DataEntry;
483 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
484 return std::error_code();
485 if (DataEntry->RelativeVirtualAddress == 0)
486 return std::error_code();
488 uint32_t RVA = DataEntry->RelativeVirtualAddress;
489 NumberOfDelayImportDirectory = DataEntry->Size /
490 sizeof(delay_import_directory_table_entry) - 1;
492 uintptr_t IntPtr = 0;
493 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
495 DelayImportDirectory = reinterpret_cast<
496 const delay_import_directory_table_entry *>(IntPtr);
497 return std::error_code();
500 // Find the export table.
501 std::error_code COFFObjectFile::initExportTablePtr() {
502 // First, we get the RVA of the export table. If the file lacks a pointer to
503 // the export table, do nothing.
504 const data_directory *DataEntry;
505 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
506 return std::error_code();
508 // Do nothing if the pointer to export table is NULL.
509 if (DataEntry->RelativeVirtualAddress == 0)
510 return std::error_code();
512 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
513 uintptr_t IntPtr = 0;
514 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
517 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
518 return std::error_code();
521 std::error_code COFFObjectFile::initBaseRelocPtr() {
522 const data_directory *DataEntry;
523 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
524 return std::error_code();
525 if (DataEntry->RelativeVirtualAddress == 0)
526 return std::error_code();
528 uintptr_t IntPtr = 0;
529 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
531 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
533 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
534 IntPtr + DataEntry->Size);
535 return std::error_code();
538 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
539 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
540 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
541 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
542 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
543 ImportDirectory(nullptr), NumberOfImportDirectory(0),
544 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
545 ExportDirectory(nullptr), BaseRelocHeader(nullptr),
546 BaseRelocEnd(nullptr) {
547 // Check that we at least have enough room for a header.
548 if (!checkSize(Data, EC, sizeof(coff_file_header)))
551 // The current location in the file where we are looking at.
554 // PE header is optional and is present only in executables. If it exists,
555 // it is placed right after COFF header.
556 bool HasPEHeader = false;
558 // Check if this is a PE/COFF file.
559 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
560 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
561 // PE signature to find 'normal' COFF header.
562 const auto *DH = reinterpret_cast<const dos_header *>(base());
563 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
564 CurPtr = DH->AddressOfNewExeHeader;
565 // Check the PE magic bytes. ("PE\0\0")
566 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
567 EC = object_error::parse_failed;
570 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
575 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
578 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
579 // import libraries share a common prefix but bigobj is more restrictive.
580 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
581 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
582 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
583 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
586 // Verify that we are dealing with bigobj.
587 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
588 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
589 sizeof(COFF::BigObjMagic)) == 0) {
590 COFFHeader = nullptr;
591 CurPtr += sizeof(coff_bigobj_file_header);
593 // It's not a bigobj.
594 COFFBigObjHeader = nullptr;
598 // The prior checkSize call may have failed. This isn't a hard error
599 // because we were just trying to sniff out bigobj.
600 EC = std::error_code();
601 CurPtr += sizeof(coff_file_header);
603 if (COFFHeader->isImportLibrary())
608 const pe32_header *Header;
609 if ((EC = getObject(Header, Data, base() + CurPtr)))
612 const uint8_t *DataDirAddr;
613 uint64_t DataDirSize;
614 if (Header->Magic == COFF::PE32Header::PE32) {
616 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
617 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
618 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
619 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
620 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
621 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
623 // It's neither PE32 nor PE32+.
624 EC = object_error::parse_failed;
627 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
629 CurPtr += COFFHeader->SizeOfOptionalHeader;
632 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
633 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
636 // Initialize the pointer to the symbol table.
637 if (getPointerToSymbolTable() != 0) {
638 if ((EC = initSymbolTablePtr()))
641 // We had better not have any symbols if we don't have a symbol table.
642 if (getNumberOfSymbols() != 0) {
643 EC = object_error::parse_failed;
648 // Initialize the pointer to the beginning of the import table.
649 if ((EC = initImportTablePtr()))
651 if ((EC = initDelayImportTablePtr()))
654 // Initialize the pointer to the export table.
655 if ((EC = initExportTablePtr()))
658 // Initialize the pointer to the base relocation table.
659 if ((EC = initBaseRelocPtr()))
662 EC = std::error_code();
665 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
667 Ret.p = getSymbolTable();
668 return basic_symbol_iterator(SymbolRef(Ret, this));
671 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
672 // The symbol table ends where the string table begins.
674 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
675 return basic_symbol_iterator(SymbolRef(Ret, this));
678 import_directory_iterator COFFObjectFile::import_directory_begin() const {
679 return import_directory_iterator(
680 ImportDirectoryEntryRef(ImportDirectory, 0, this));
683 import_directory_iterator COFFObjectFile::import_directory_end() const {
684 return import_directory_iterator(
685 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
688 delay_import_directory_iterator
689 COFFObjectFile::delay_import_directory_begin() const {
690 return delay_import_directory_iterator(
691 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
694 delay_import_directory_iterator
695 COFFObjectFile::delay_import_directory_end() const {
696 return delay_import_directory_iterator(
697 DelayImportDirectoryEntryRef(
698 DelayImportDirectory, NumberOfDelayImportDirectory, this));
701 export_directory_iterator COFFObjectFile::export_directory_begin() const {
702 return export_directory_iterator(
703 ExportDirectoryEntryRef(ExportDirectory, 0, this));
706 export_directory_iterator COFFObjectFile::export_directory_end() const {
707 if (!ExportDirectory)
708 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
709 ExportDirectoryEntryRef Ref(ExportDirectory,
710 ExportDirectory->AddressTableEntries, this);
711 return export_directory_iterator(Ref);
714 section_iterator COFFObjectFile::section_begin() const {
716 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
717 return section_iterator(SectionRef(Ret, this));
720 section_iterator COFFObjectFile::section_end() const {
723 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
724 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
725 return section_iterator(SectionRef(Ret, this));
728 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
729 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
732 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
733 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
736 uint8_t COFFObjectFile::getBytesInAddress() const {
737 return getArch() == Triple::x86_64 ? 8 : 4;
740 StringRef COFFObjectFile::getFileFormatName() const {
741 switch(getMachine()) {
742 case COFF::IMAGE_FILE_MACHINE_I386:
744 case COFF::IMAGE_FILE_MACHINE_AMD64:
745 return "COFF-x86-64";
746 case COFF::IMAGE_FILE_MACHINE_ARMNT:
749 return "COFF-<unknown arch>";
753 unsigned COFFObjectFile::getArch() const {
754 switch (getMachine()) {
755 case COFF::IMAGE_FILE_MACHINE_I386:
757 case COFF::IMAGE_FILE_MACHINE_AMD64:
758 return Triple::x86_64;
759 case COFF::IMAGE_FILE_MACHINE_ARMNT:
760 return Triple::thumb;
762 return Triple::UnknownArch;
766 iterator_range<import_directory_iterator>
767 COFFObjectFile::import_directories() const {
768 return make_range(import_directory_begin(), import_directory_end());
771 iterator_range<delay_import_directory_iterator>
772 COFFObjectFile::delay_import_directories() const {
773 return make_range(delay_import_directory_begin(),
774 delay_import_directory_end());
777 iterator_range<export_directory_iterator>
778 COFFObjectFile::export_directories() const {
779 return make_range(export_directory_begin(), export_directory_end());
782 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
783 return make_range(base_reloc_begin(), base_reloc_end());
786 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
788 return std::error_code();
792 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
793 Res = PE32PlusHeader;
794 return std::error_code();
798 COFFObjectFile::getDataDirectory(uint32_t Index,
799 const data_directory *&Res) const {
800 // Error if if there's no data directory or the index is out of range.
801 if (!DataDirectory) {
803 return object_error::parse_failed;
805 assert(PE32Header || PE32PlusHeader);
806 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
807 : PE32PlusHeader->NumberOfRvaAndSize;
808 if (Index >= NumEnt) {
810 return object_error::parse_failed;
812 Res = &DataDirectory[Index];
813 return std::error_code();
816 std::error_code COFFObjectFile::getSection(int32_t Index,
817 const coff_section *&Result) const {
819 if (COFF::isReservedSectionNumber(Index))
820 return std::error_code();
821 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
822 // We already verified the section table data, so no need to check again.
823 Result = SectionTable + (Index - 1);
824 return std::error_code();
826 return object_error::parse_failed;
829 std::error_code COFFObjectFile::getString(uint32_t Offset,
830 StringRef &Result) const {
831 if (StringTableSize <= 4)
832 // Tried to get a string from an empty string table.
833 return object_error::parse_failed;
834 if (Offset >= StringTableSize)
835 return object_error::unexpected_eof;
836 Result = StringRef(StringTable + Offset);
837 return std::error_code();
840 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
841 StringRef &Res) const {
842 // Check for string table entry. First 4 bytes are 0.
843 if (Symbol.getStringTableOffset().Zeroes == 0) {
844 uint32_t Offset = Symbol.getStringTableOffset().Offset;
845 if (std::error_code EC = getString(Offset, Res))
847 return std::error_code();
850 if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
851 // Null terminated, let ::strlen figure out the length.
852 Res = StringRef(Symbol.getShortName());
854 // Not null terminated, use all 8 bytes.
855 Res = StringRef(Symbol.getShortName(), COFF::NameSize);
856 return std::error_code();
860 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
861 const uint8_t *Aux = nullptr;
863 size_t SymbolSize = getSymbolTableEntrySize();
864 if (Symbol.getNumberOfAuxSymbols() > 0) {
865 // AUX data comes immediately after the symbol in COFF
866 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
868 // Verify that the Aux symbol points to a valid entry in the symbol table.
869 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
870 if (Offset < getPointerToSymbolTable() ||
872 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
873 report_fatal_error("Aux Symbol data was outside of symbol table.");
875 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
876 "Aux Symbol data did not point to the beginning of a symbol");
879 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
882 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
883 StringRef &Res) const {
885 if (Sec->Name[COFF::NameSize - 1] == 0)
886 // Null terminated, let ::strlen figure out the length.
889 // Not null terminated, use all 8 bytes.
890 Name = StringRef(Sec->Name, COFF::NameSize);
892 // Check for string table entry. First byte is '/'.
893 if (Name.startswith("/")) {
895 if (Name.startswith("//")) {
896 if (decodeBase64StringEntry(Name.substr(2), Offset))
897 return object_error::parse_failed;
899 if (Name.substr(1).getAsInteger(10, Offset))
900 return object_error::parse_failed;
902 if (std::error_code EC = getString(Offset, Name))
907 return std::error_code();
910 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
911 // SizeOfRawData and VirtualSize change what they represent depending on
912 // whether or not we have an executable image.
914 // For object files, SizeOfRawData contains the size of section's data;
915 // VirtualSize is always zero.
917 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
918 // actual section size is in VirtualSize. It is possible for VirtualSize to
919 // be greater than SizeOfRawData; the contents past that point should be
920 // considered to be zero.
921 uint32_t SectionSize;
922 if (Sec->VirtualSize)
923 SectionSize = std::min(Sec->VirtualSize, Sec->SizeOfRawData);
925 SectionSize = Sec->SizeOfRawData;
931 COFFObjectFile::getSectionContents(const coff_section *Sec,
932 ArrayRef<uint8_t> &Res) const {
933 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
934 // don't do anything interesting for them.
935 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
936 "BSS sections don't have contents!");
937 // The only thing that we need to verify is that the contents is contained
938 // within the file bounds. We don't need to make sure it doesn't cover other
939 // data, as there's nothing that says that is not allowed.
940 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
941 uint32_t SectionSize = getSectionSize(Sec);
942 if (checkOffset(Data, ConStart, SectionSize))
943 return object_error::parse_failed;
944 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
945 return std::error_code();
948 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
949 return reinterpret_cast<const coff_relocation*>(Rel.p);
952 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
953 Rel.p = reinterpret_cast<uintptr_t>(
954 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
957 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
958 uint64_t &Res) const {
959 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
962 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
963 uint64_t &Res) const {
964 const coff_relocation *R = toRel(Rel);
965 const support::ulittle32_t *VirtualAddressPtr;
966 if (std::error_code EC =
967 getObject(VirtualAddressPtr, Data, &R->VirtualAddress))
969 Res = *VirtualAddressPtr;
970 return std::error_code();
973 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
974 const coff_relocation *R = toRel(Rel);
976 if (R->SymbolTableIndex >= getNumberOfSymbols())
979 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
980 else if (SymbolTable32)
981 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
983 llvm_unreachable("no symbol table pointer!");
984 return symbol_iterator(SymbolRef(Ref, this));
987 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
988 uint64_t &Res) const {
989 const coff_relocation* R = toRel(Rel);
991 return std::error_code();
995 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
996 return toSec(Section.getRawDataRefImpl());
999 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1001 return toSymb<coff_symbol16>(Ref);
1003 return toSymb<coff_symbol32>(Ref);
1004 llvm_unreachable("no symbol table pointer!");
1007 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1008 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1011 const coff_relocation *
1012 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1013 return toRel(Reloc.getRawDataRefImpl());
1016 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1017 case COFF::reloc_type: \
1018 Res = #reloc_type; \
1022 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
1023 SmallVectorImpl<char> &Result) const {
1024 const coff_relocation *Reloc = toRel(Rel);
1026 switch (getMachine()) {
1027 case COFF::IMAGE_FILE_MACHINE_AMD64:
1028 switch (Reloc->Type) {
1029 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1030 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1031 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1032 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1033 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1034 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1035 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1036 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1037 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1038 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1039 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1040 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1041 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1042 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1043 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1044 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1045 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1050 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1051 switch (Reloc->Type) {
1052 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1053 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1054 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1055 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1056 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1057 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1058 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1059 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1060 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1061 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1062 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1063 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1064 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1065 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1066 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1071 case COFF::IMAGE_FILE_MACHINE_I386:
1072 switch (Reloc->Type) {
1073 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1074 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1075 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1076 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1077 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1078 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1079 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1080 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1081 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1082 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1083 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1091 Result.append(Res.begin(), Res.end());
1092 return std::error_code();
1095 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1097 bool COFFObjectFile::isRelocatableObject() const {
1098 return !DataDirectory;
1101 bool ImportDirectoryEntryRef::
1102 operator==(const ImportDirectoryEntryRef &Other) const {
1103 return ImportTable == Other.ImportTable && Index == Other.Index;
1106 void ImportDirectoryEntryRef::moveNext() {
1110 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1111 const import_directory_table_entry *&Result) const {
1112 Result = ImportTable + Index;
1113 return std::error_code();
1116 static imported_symbol_iterator
1117 makeImportedSymbolIterator(const COFFObjectFile *Object,
1118 uintptr_t Ptr, int Index) {
1119 if (Object->getBytesInAddress() == 4) {
1120 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1121 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1123 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1124 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1127 static imported_symbol_iterator
1128 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1129 uintptr_t IntPtr = 0;
1130 Object->getRvaPtr(RVA, IntPtr);
1131 return makeImportedSymbolIterator(Object, IntPtr, 0);
1134 static imported_symbol_iterator
1135 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1136 uintptr_t IntPtr = 0;
1137 Object->getRvaPtr(RVA, IntPtr);
1138 // Forward the pointer to the last entry which is null.
1140 if (Object->getBytesInAddress() == 4) {
1141 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1145 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1149 return makeImportedSymbolIterator(Object, IntPtr, Index);
1152 imported_symbol_iterator
1153 ImportDirectoryEntryRef::imported_symbol_begin() const {
1154 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1158 imported_symbol_iterator
1159 ImportDirectoryEntryRef::imported_symbol_end() const {
1160 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1164 iterator_range<imported_symbol_iterator>
1165 ImportDirectoryEntryRef::imported_symbols() const {
1166 return make_range(imported_symbol_begin(), imported_symbol_end());
1169 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1170 uintptr_t IntPtr = 0;
1171 if (std::error_code EC =
1172 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1174 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1175 return std::error_code();
1179 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1180 Result = ImportTable[Index].ImportLookupTableRVA;
1181 return std::error_code();
1185 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1186 Result = ImportTable[Index].ImportAddressTableRVA;
1187 return std::error_code();
1190 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1191 const import_lookup_table_entry32 *&Result) const {
1192 uintptr_t IntPtr = 0;
1193 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1194 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1196 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1197 return std::error_code();
1200 bool DelayImportDirectoryEntryRef::
1201 operator==(const DelayImportDirectoryEntryRef &Other) const {
1202 return Table == Other.Table && Index == Other.Index;
1205 void DelayImportDirectoryEntryRef::moveNext() {
1209 imported_symbol_iterator
1210 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1211 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1215 imported_symbol_iterator
1216 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1217 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1221 iterator_range<imported_symbol_iterator>
1222 DelayImportDirectoryEntryRef::imported_symbols() const {
1223 return make_range(imported_symbol_begin(), imported_symbol_end());
1226 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1227 uintptr_t IntPtr = 0;
1228 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1230 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1231 return std::error_code();
1234 std::error_code DelayImportDirectoryEntryRef::
1235 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1237 return std::error_code();
1240 std::error_code DelayImportDirectoryEntryRef::
1241 getImportAddress(int AddrIndex, uint64_t &Result) const {
1242 uint32_t RVA = Table[Index].DelayImportAddressTable +
1243 AddrIndex * (OwningObject->is64() ? 8 : 4);
1244 uintptr_t IntPtr = 0;
1245 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1247 if (OwningObject->is64())
1248 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1250 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1251 return std::error_code();
1254 bool ExportDirectoryEntryRef::
1255 operator==(const ExportDirectoryEntryRef &Other) const {
1256 return ExportTable == Other.ExportTable && Index == Other.Index;
1259 void ExportDirectoryEntryRef::moveNext() {
1263 // Returns the name of the current export symbol. If the symbol is exported only
1264 // by ordinal, the empty string is set as a result.
1265 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1266 uintptr_t IntPtr = 0;
1267 if (std::error_code EC =
1268 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1270 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1271 return std::error_code();
1274 // Returns the starting ordinal number.
1276 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1277 Result = ExportTable->OrdinalBase;
1278 return std::error_code();
1281 // Returns the export ordinal of the current export symbol.
1282 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1283 Result = ExportTable->OrdinalBase + Index;
1284 return std::error_code();
1287 // Returns the address of the current export symbol.
1288 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1289 uintptr_t IntPtr = 0;
1290 if (std::error_code EC =
1291 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1293 const export_address_table_entry *entry =
1294 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1295 Result = entry[Index].ExportRVA;
1296 return std::error_code();
1299 // Returns the name of the current export symbol. If the symbol is exported only
1300 // by ordinal, the empty string is set as a result.
1302 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1303 uintptr_t IntPtr = 0;
1304 if (std::error_code EC =
1305 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1307 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1309 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1311 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1312 I < E; ++I, ++Offset) {
1315 if (std::error_code EC =
1316 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1318 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1319 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1321 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1322 return std::error_code();
1325 return std::error_code();
1328 bool ImportedSymbolRef::
1329 operator==(const ImportedSymbolRef &Other) const {
1330 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1331 && Index == Other.Index;
1334 void ImportedSymbolRef::moveNext() {
1339 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1342 // If a symbol is imported only by ordinal, it has no name.
1343 if (Entry32[Index].isOrdinal())
1344 return std::error_code();
1345 RVA = Entry32[Index].getHintNameRVA();
1347 if (Entry64[Index].isOrdinal())
1348 return std::error_code();
1349 RVA = Entry64[Index].getHintNameRVA();
1351 uintptr_t IntPtr = 0;
1352 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1354 // +2 because the first two bytes is hint.
1355 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1356 return std::error_code();
1359 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1362 if (Entry32[Index].isOrdinal()) {
1363 Result = Entry32[Index].getOrdinal();
1364 return std::error_code();
1366 RVA = Entry32[Index].getHintNameRVA();
1368 if (Entry64[Index].isOrdinal()) {
1369 Result = Entry64[Index].getOrdinal();
1370 return std::error_code();
1372 RVA = Entry64[Index].getHintNameRVA();
1374 uintptr_t IntPtr = 0;
1375 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1377 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1378 return std::error_code();
1381 ErrorOr<std::unique_ptr<COFFObjectFile>>
1382 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1384 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1387 return std::move(Ret);
1390 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1391 return Header == Other.Header && Index == Other.Index;
1394 void BaseRelocRef::moveNext() {
1395 // Header->BlockSize is the size of the current block, including the
1396 // size of the header itself.
1397 uint32_t Size = sizeof(*Header) +
1398 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1399 if (Size == Header->BlockSize) {
1400 // .reloc contains a list of base relocation blocks. Each block
1401 // consists of the header followed by entries. The header contains
1402 // how many entories will follow. When we reach the end of the
1403 // current block, proceed to the next block.
1404 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1405 reinterpret_cast<const uint8_t *>(Header) + Size);
1412 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1413 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1414 Type = Entry[Index].getType();
1415 return std::error_code();
1418 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1419 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1420 Result = Header->PageRVA + Entry[Index].getOffset();
1421 return std::error_code();