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 object_error::success;
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 object_error::success;
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()) {
158 Result = UnknownAddressOrSize;
159 return object_error::success;
161 if (Symb.isCommon()) {
162 Result = UnknownAddressOrSize;
163 return object_error::success;
165 int32_t SectionNumber = Symb.getSectionNumber();
166 if (!COFF::isReservedSectionNumber(SectionNumber)) {
167 const coff_section *Section = nullptr;
168 if (std::error_code EC = getSection(SectionNumber, Section))
171 Result = Section->VirtualAddress + Symb.getValue();
172 return object_error::success;
175 Result = Symb.getValue();
176 return object_error::success;
179 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
180 SymbolRef::Type &Result) const {
181 COFFSymbolRef Symb = getCOFFSymbol(Ref);
182 int32_t SectionNumber = Symb.getSectionNumber();
183 Result = SymbolRef::ST_Other;
185 if (Symb.isAnyUndefined()) {
186 Result = SymbolRef::ST_Unknown;
187 } else if (Symb.isFunctionDefinition()) {
188 Result = SymbolRef::ST_Function;
189 } else if (Symb.isCommon()) {
190 Result = SymbolRef::ST_Data;
191 } else if (Symb.isFileRecord()) {
192 Result = SymbolRef::ST_File;
193 } else if (SectionNumber == COFF::IMAGE_SYM_DEBUG) {
194 Result = SymbolRef::ST_Debug;
195 } else if (!COFF::isReservedSectionNumber(SectionNumber)) {
196 const coff_section *Section = nullptr;
197 if (std::error_code EC = getSection(SectionNumber, Section))
199 uint32_t Characteristics = Section->Characteristics;
200 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
201 Result = SymbolRef::ST_Function;
202 else if (Characteristics & (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
203 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA))
204 Result = SymbolRef::ST_Data;
206 return object_error::success;
209 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
210 COFFSymbolRef Symb = getCOFFSymbol(Ref);
211 uint32_t Result = SymbolRef::SF_None;
213 if (Symb.isExternal() || Symb.isWeakExternal())
214 Result |= SymbolRef::SF_Global;
216 if (Symb.isWeakExternal())
217 Result |= SymbolRef::SF_Weak;
219 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
220 Result |= SymbolRef::SF_Absolute;
222 if (Symb.isFileRecord())
223 Result |= SymbolRef::SF_FormatSpecific;
225 if (Symb.isSectionDefinition())
226 Result |= SymbolRef::SF_FormatSpecific;
229 Result |= SymbolRef::SF_Common;
231 if (Symb.isAnyUndefined())
232 Result |= SymbolRef::SF_Undefined;
237 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
238 uint64_t &Result) const {
239 COFFSymbolRef Symb = getCOFFSymbol(Ref);
241 if (Symb.isAnyUndefined()) {
242 Result = UnknownAddressOrSize;
243 return object_error::success;
245 if (Symb.isCommon()) {
246 Result = Symb.getValue();
247 return object_error::success;
250 // Let's attempt to get the size of the symbol by looking at the address of
251 // the symbol after the symbol in question.
253 if (std::error_code EC = getSymbolAddress(Ref, SymbAddr))
255 int32_t SectionNumber = Symb.getSectionNumber();
256 if (COFF::isReservedSectionNumber(SectionNumber)) {
257 // Absolute and debug symbols aren't sorted in any interesting way.
259 return object_error::success;
261 const section_iterator SecEnd = section_end();
262 uint64_t AfterAddr = UnknownAddressOrSize;
263 for (const symbol_iterator &SymbI : symbols()) {
264 section_iterator SecI = SecEnd;
265 if (std::error_code EC = SymbI->getSection(SecI))
267 // Check the symbol's section, skip it if it's in the wrong section.
268 // First, make sure it is in any section.
271 // Second, make sure it is in the same section as the symbol in question.
272 if (!sectionContainsSymbol(SecI->getRawDataRefImpl(), Ref))
275 if (std::error_code EC = SymbI->getAddress(Addr))
277 // We want to compare our symbol in question with the closest possible
278 // symbol that comes after.
279 if (AfterAddr > Addr && Addr > SymbAddr)
282 if (AfterAddr == UnknownAddressOrSize) {
283 // No symbol comes after this one, assume that everything after our symbol
285 const coff_section *Section = nullptr;
286 if (std::error_code EC = getSection(SectionNumber, Section))
288 Result = Section->SizeOfRawData - Symb.getValue();
290 // Take the difference between our symbol and the symbol that comes after
292 Result = AfterAddr - SymbAddr;
295 return object_error::success;
299 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
300 section_iterator &Result) const {
301 COFFSymbolRef Symb = getCOFFSymbol(Ref);
302 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
303 Result = section_end();
305 const coff_section *Sec = nullptr;
306 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
309 Ref.p = reinterpret_cast<uintptr_t>(Sec);
310 Result = section_iterator(SectionRef(Ref, this));
312 return object_error::success;
315 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
316 const coff_section *Sec = toSec(Ref);
318 Ref.p = reinterpret_cast<uintptr_t>(Sec);
321 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
322 StringRef &Result) const {
323 const coff_section *Sec = toSec(Ref);
324 return getSectionName(Sec, Result);
327 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
328 const coff_section *Sec = toSec(Ref);
329 return Sec->VirtualAddress;
332 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
333 return getSectionSize(toSec(Ref));
336 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
337 StringRef &Result) const {
338 const coff_section *Sec = toSec(Ref);
339 ArrayRef<uint8_t> Res;
340 std::error_code EC = getSectionContents(Sec, Res);
341 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
345 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
346 const coff_section *Sec = toSec(Ref);
347 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
350 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
351 const coff_section *Sec = toSec(Ref);
352 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
355 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
356 const coff_section *Sec = toSec(Ref);
357 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
360 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
361 const coff_section *Sec = toSec(Ref);
362 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
365 bool COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref) const {
366 // Sections marked 'Info', 'Remove', or 'Discardable' aren't required for
368 const coff_section *Sec = toSec(Ref);
369 return !(Sec->Characteristics &
370 (COFF::IMAGE_SCN_LNK_INFO | COFF::IMAGE_SCN_LNK_REMOVE |
371 COFF::IMAGE_SCN_MEM_DISCARDABLE));
374 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
375 const coff_section *Sec = toSec(Ref);
376 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
379 bool COFFObjectFile::isSectionZeroInit(DataRefImpl Ref) const {
380 const coff_section *Sec = toSec(Ref);
381 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
384 bool COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref) const {
385 const coff_section *Sec = toSec(Ref);
386 // Check if it's any sort of data section.
387 if (!(Sec->Characteristics & (COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
388 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)))
390 // If it's writable or executable or contains code, it isn't read-only data.
391 if (Sec->Characteristics &
392 (COFF::IMAGE_SCN_CNT_CODE | COFF::IMAGE_SCN_MEM_EXECUTE |
393 COFF::IMAGE_SCN_MEM_WRITE))
398 bool COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
399 DataRefImpl SymbRef) const {
400 const coff_section *Sec = toSec(SecRef);
401 COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
402 int32_t SecNumber = (Sec - SectionTable) + 1;
403 return SecNumber == Symb.getSectionNumber();
406 static uint32_t getNumberOfRelocations(const coff_section *Sec,
407 MemoryBufferRef M, const uint8_t *base) {
408 // The field for the number of relocations in COFF section table is only
409 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
410 // NumberOfRelocations field, and the actual relocation count is stored in the
411 // VirtualAddress field in the first relocation entry.
412 if (Sec->hasExtendedRelocations()) {
413 const coff_relocation *FirstReloc;
414 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
415 base + Sec->PointerToRelocations)))
417 // -1 to exclude this first relocation entry.
418 return FirstReloc->VirtualAddress - 1;
420 return Sec->NumberOfRelocations;
423 static const coff_relocation *
424 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
425 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
428 auto begin = reinterpret_cast<const coff_relocation *>(
429 Base + Sec->PointerToRelocations);
430 if (Sec->hasExtendedRelocations()) {
431 // Skip the first relocation entry repurposed to store the number of
435 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
440 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
441 const coff_section *Sec = toSec(Ref);
442 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
444 Ret.p = reinterpret_cast<uintptr_t>(begin);
445 return relocation_iterator(RelocationRef(Ret, this));
448 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
449 const coff_section *Sec = toSec(Ref);
450 const coff_relocation *I = getFirstReloc(Sec, Data, base());
452 I += getNumberOfRelocations(Sec, Data, base());
454 Ret.p = reinterpret_cast<uintptr_t>(I);
455 return relocation_iterator(RelocationRef(Ret, this));
458 // Initialize the pointer to the symbol table.
459 std::error_code COFFObjectFile::initSymbolTablePtr() {
461 if (std::error_code EC = getObject(
462 SymbolTable16, Data, base() + getPointerToSymbolTable(),
463 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
466 if (COFFBigObjHeader)
467 if (std::error_code EC = getObject(
468 SymbolTable32, Data, base() + getPointerToSymbolTable(),
469 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
472 // Find string table. The first four byte of the string table contains the
473 // total size of the string table, including the size field itself. If the
474 // string table is empty, the value of the first four byte would be 4.
475 uint32_t StringTableOffset = getPointerToSymbolTable() +
476 getNumberOfSymbols() * getSymbolTableEntrySize();
477 const uint8_t *StringTableAddr = base() + StringTableOffset;
478 const ulittle32_t *StringTableSizePtr;
479 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
481 StringTableSize = *StringTableSizePtr;
482 if (std::error_code EC =
483 getObject(StringTable, Data, StringTableAddr, StringTableSize))
486 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
487 // tools like cvtres write a size of 0 for an empty table instead of 4.
488 if (StringTableSize < 4)
491 // Check that the string table is null terminated if has any in it.
492 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
493 return object_error::parse_failed;
494 return object_error::success;
497 // Returns the file offset for the given VA.
498 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
499 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
500 : (uint64_t)PE32PlusHeader->ImageBase;
501 uint64_t Rva = Addr - ImageBase;
502 assert(Rva <= UINT32_MAX);
503 return getRvaPtr((uint32_t)Rva, Res);
506 // Returns the file offset for the given RVA.
507 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
508 for (const SectionRef &S : sections()) {
509 const coff_section *Section = getCOFFSection(S);
510 uint32_t SectionStart = Section->VirtualAddress;
511 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
512 if (SectionStart <= Addr && Addr < SectionEnd) {
513 uint32_t Offset = Addr - SectionStart;
514 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
515 return object_error::success;
518 return object_error::parse_failed;
521 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
523 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
524 StringRef &Name) const {
525 uintptr_t IntPtr = 0;
526 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
528 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
529 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
530 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
531 return object_error::success;
534 // Find the import table.
535 std::error_code COFFObjectFile::initImportTablePtr() {
536 // First, we get the RVA of the import table. If the file lacks a pointer to
537 // the import table, do nothing.
538 const data_directory *DataEntry;
539 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
540 return object_error::success;
542 // Do nothing if the pointer to import table is NULL.
543 if (DataEntry->RelativeVirtualAddress == 0)
544 return object_error::success;
546 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
547 // -1 because the last entry is the null entry.
548 NumberOfImportDirectory = DataEntry->Size /
549 sizeof(import_directory_table_entry) - 1;
551 // Find the section that contains the RVA. This is needed because the RVA is
552 // the import table's memory address which is different from its file offset.
553 uintptr_t IntPtr = 0;
554 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
556 ImportDirectory = reinterpret_cast<
557 const import_directory_table_entry *>(IntPtr);
558 return object_error::success;
561 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
562 std::error_code COFFObjectFile::initDelayImportTablePtr() {
563 const data_directory *DataEntry;
564 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
565 return object_error::success;
566 if (DataEntry->RelativeVirtualAddress == 0)
567 return object_error::success;
569 uint32_t RVA = DataEntry->RelativeVirtualAddress;
570 NumberOfDelayImportDirectory = DataEntry->Size /
571 sizeof(delay_import_directory_table_entry) - 1;
573 uintptr_t IntPtr = 0;
574 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
576 DelayImportDirectory = reinterpret_cast<
577 const delay_import_directory_table_entry *>(IntPtr);
578 return object_error::success;
581 // Find the export table.
582 std::error_code COFFObjectFile::initExportTablePtr() {
583 // First, we get the RVA of the export table. If the file lacks a pointer to
584 // the export table, do nothing.
585 const data_directory *DataEntry;
586 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
587 return object_error::success;
589 // Do nothing if the pointer to export table is NULL.
590 if (DataEntry->RelativeVirtualAddress == 0)
591 return object_error::success;
593 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
594 uintptr_t IntPtr = 0;
595 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
598 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
599 return object_error::success;
602 std::error_code COFFObjectFile::initBaseRelocPtr() {
603 const data_directory *DataEntry;
604 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
605 return object_error::success;
606 if (DataEntry->RelativeVirtualAddress == 0)
607 return object_error::success;
609 uintptr_t IntPtr = 0;
610 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
612 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
614 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
615 IntPtr + DataEntry->Size);
616 return object_error::success;
619 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
620 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
621 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
622 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
623 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
624 ImportDirectory(nullptr), NumberOfImportDirectory(0),
625 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
626 ExportDirectory(nullptr), BaseRelocHeader(nullptr),
627 BaseRelocEnd(nullptr) {
628 // Check that we at least have enough room for a header.
629 if (!checkSize(Data, EC, sizeof(coff_file_header)))
632 // The current location in the file where we are looking at.
635 // PE header is optional and is present only in executables. If it exists,
636 // it is placed right after COFF header.
637 bool HasPEHeader = false;
639 // Check if this is a PE/COFF file.
640 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
641 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
642 // PE signature to find 'normal' COFF header.
643 const auto *DH = reinterpret_cast<const dos_header *>(base());
644 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
645 CurPtr = DH->AddressOfNewExeHeader;
646 // Check the PE magic bytes. ("PE\0\0")
647 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
648 EC = object_error::parse_failed;
651 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
656 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
659 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
660 // import libraries share a common prefix but bigobj is more restrictive.
661 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
662 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
663 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
664 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
667 // Verify that we are dealing with bigobj.
668 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
669 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
670 sizeof(COFF::BigObjMagic)) == 0) {
671 COFFHeader = nullptr;
672 CurPtr += sizeof(coff_bigobj_file_header);
674 // It's not a bigobj.
675 COFFBigObjHeader = nullptr;
679 // The prior checkSize call may have failed. This isn't a hard error
680 // because we were just trying to sniff out bigobj.
681 EC = object_error::success;
682 CurPtr += sizeof(coff_file_header);
684 if (COFFHeader->isImportLibrary())
689 const pe32_header *Header;
690 if ((EC = getObject(Header, Data, base() + CurPtr)))
693 const uint8_t *DataDirAddr;
694 uint64_t DataDirSize;
695 if (Header->Magic == COFF::PE32Header::PE32) {
697 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
698 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
699 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
700 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
701 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
702 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
704 // It's neither PE32 nor PE32+.
705 EC = object_error::parse_failed;
708 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
710 CurPtr += COFFHeader->SizeOfOptionalHeader;
713 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
714 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
717 // Initialize the pointer to the symbol table.
718 if (getPointerToSymbolTable() != 0) {
719 if ((EC = initSymbolTablePtr()))
722 // We had better not have any symbols if we don't have a symbol table.
723 if (getNumberOfSymbols() != 0) {
724 EC = object_error::parse_failed;
729 // Initialize the pointer to the beginning of the import table.
730 if ((EC = initImportTablePtr()))
732 if ((EC = initDelayImportTablePtr()))
735 // Initialize the pointer to the export table.
736 if ((EC = initExportTablePtr()))
739 // Initialize the pointer to the base relocation table.
740 if ((EC = initBaseRelocPtr()))
743 EC = object_error::success;
746 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
748 Ret.p = getSymbolTable();
749 return basic_symbol_iterator(SymbolRef(Ret, this));
752 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
753 // The symbol table ends where the string table begins.
755 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
756 return basic_symbol_iterator(SymbolRef(Ret, this));
759 import_directory_iterator COFFObjectFile::import_directory_begin() const {
760 return import_directory_iterator(
761 ImportDirectoryEntryRef(ImportDirectory, 0, this));
764 import_directory_iterator COFFObjectFile::import_directory_end() const {
765 return import_directory_iterator(
766 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
769 delay_import_directory_iterator
770 COFFObjectFile::delay_import_directory_begin() const {
771 return delay_import_directory_iterator(
772 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
775 delay_import_directory_iterator
776 COFFObjectFile::delay_import_directory_end() const {
777 return delay_import_directory_iterator(
778 DelayImportDirectoryEntryRef(
779 DelayImportDirectory, NumberOfDelayImportDirectory, this));
782 export_directory_iterator COFFObjectFile::export_directory_begin() const {
783 return export_directory_iterator(
784 ExportDirectoryEntryRef(ExportDirectory, 0, this));
787 export_directory_iterator COFFObjectFile::export_directory_end() const {
788 if (!ExportDirectory)
789 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
790 ExportDirectoryEntryRef Ref(ExportDirectory,
791 ExportDirectory->AddressTableEntries, this);
792 return export_directory_iterator(Ref);
795 section_iterator COFFObjectFile::section_begin() const {
797 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
798 return section_iterator(SectionRef(Ret, this));
801 section_iterator COFFObjectFile::section_end() const {
804 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
805 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
806 return section_iterator(SectionRef(Ret, this));
809 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
810 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
813 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
814 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
817 uint8_t COFFObjectFile::getBytesInAddress() const {
818 return getArch() == Triple::x86_64 ? 8 : 4;
821 StringRef COFFObjectFile::getFileFormatName() const {
822 switch(getMachine()) {
823 case COFF::IMAGE_FILE_MACHINE_I386:
825 case COFF::IMAGE_FILE_MACHINE_AMD64:
826 return "COFF-x86-64";
827 case COFF::IMAGE_FILE_MACHINE_ARMNT:
830 return "COFF-<unknown arch>";
834 unsigned COFFObjectFile::getArch() const {
835 switch (getMachine()) {
836 case COFF::IMAGE_FILE_MACHINE_I386:
838 case COFF::IMAGE_FILE_MACHINE_AMD64:
839 return Triple::x86_64;
840 case COFF::IMAGE_FILE_MACHINE_ARMNT:
841 return Triple::thumb;
843 return Triple::UnknownArch;
847 iterator_range<import_directory_iterator>
848 COFFObjectFile::import_directories() const {
849 return make_range(import_directory_begin(), import_directory_end());
852 iterator_range<delay_import_directory_iterator>
853 COFFObjectFile::delay_import_directories() const {
854 return make_range(delay_import_directory_begin(),
855 delay_import_directory_end());
858 iterator_range<export_directory_iterator>
859 COFFObjectFile::export_directories() const {
860 return make_range(export_directory_begin(), export_directory_end());
863 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
864 return make_range(base_reloc_begin(), base_reloc_end());
867 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
869 return object_error::success;
873 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
874 Res = PE32PlusHeader;
875 return object_error::success;
879 COFFObjectFile::getDataDirectory(uint32_t Index,
880 const data_directory *&Res) const {
881 // Error if if there's no data directory or the index is out of range.
882 if (!DataDirectory) {
884 return object_error::parse_failed;
886 assert(PE32Header || PE32PlusHeader);
887 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
888 : PE32PlusHeader->NumberOfRvaAndSize;
889 if (Index >= NumEnt) {
891 return object_error::parse_failed;
893 Res = &DataDirectory[Index];
894 return object_error::success;
897 std::error_code COFFObjectFile::getSection(int32_t Index,
898 const coff_section *&Result) const {
900 if (COFF::isReservedSectionNumber(Index))
901 return object_error::success;
902 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
903 // We already verified the section table data, so no need to check again.
904 Result = SectionTable + (Index - 1);
905 return object_error::success;
907 return object_error::parse_failed;
910 std::error_code COFFObjectFile::getString(uint32_t Offset,
911 StringRef &Result) const {
912 if (StringTableSize <= 4)
913 // Tried to get a string from an empty string table.
914 return object_error::parse_failed;
915 if (Offset >= StringTableSize)
916 return object_error::unexpected_eof;
917 Result = StringRef(StringTable + Offset);
918 return object_error::success;
921 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
922 StringRef &Res) const {
923 // Check for string table entry. First 4 bytes are 0.
924 if (Symbol.getStringTableOffset().Zeroes == 0) {
925 uint32_t Offset = Symbol.getStringTableOffset().Offset;
926 if (std::error_code EC = getString(Offset, Res))
928 return object_error::success;
931 if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
932 // Null terminated, let ::strlen figure out the length.
933 Res = StringRef(Symbol.getShortName());
935 // Not null terminated, use all 8 bytes.
936 Res = StringRef(Symbol.getShortName(), COFF::NameSize);
937 return object_error::success;
941 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
942 const uint8_t *Aux = nullptr;
944 size_t SymbolSize = getSymbolTableEntrySize();
945 if (Symbol.getNumberOfAuxSymbols() > 0) {
946 // AUX data comes immediately after the symbol in COFF
947 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
949 // Verify that the Aux symbol points to a valid entry in the symbol table.
950 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
951 if (Offset < getPointerToSymbolTable() ||
953 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
954 report_fatal_error("Aux Symbol data was outside of symbol table.");
956 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
957 "Aux Symbol data did not point to the beginning of a symbol");
960 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
963 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
964 StringRef &Res) const {
966 if (Sec->Name[COFF::NameSize - 1] == 0)
967 // Null terminated, let ::strlen figure out the length.
970 // Not null terminated, use all 8 bytes.
971 Name = StringRef(Sec->Name, COFF::NameSize);
973 // Check for string table entry. First byte is '/'.
974 if (Name.startswith("/")) {
976 if (Name.startswith("//")) {
977 if (decodeBase64StringEntry(Name.substr(2), Offset))
978 return object_error::parse_failed;
980 if (Name.substr(1).getAsInteger(10, Offset))
981 return object_error::parse_failed;
983 if (std::error_code EC = getString(Offset, Name))
988 return object_error::success;
991 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
992 // SizeOfRawData and VirtualSize change what they represent depending on
993 // whether or not we have an executable image.
995 // For object files, SizeOfRawData contains the size of section's data;
996 // VirtualSize is always zero.
998 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
999 // actual section size is in VirtualSize. It is possible for VirtualSize to
1000 // be greater than SizeOfRawData; the contents past that point should be
1001 // considered to be zero.
1002 uint32_t SectionSize;
1003 if (Sec->VirtualSize)
1004 SectionSize = std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1006 SectionSize = Sec->SizeOfRawData;
1012 COFFObjectFile::getSectionContents(const coff_section *Sec,
1013 ArrayRef<uint8_t> &Res) const {
1014 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
1015 // don't do anything interesting for them.
1016 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
1017 "BSS sections don't have contents!");
1018 // The only thing that we need to verify is that the contents is contained
1019 // within the file bounds. We don't need to make sure it doesn't cover other
1020 // data, as there's nothing that says that is not allowed.
1021 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1022 uint32_t SectionSize = getSectionSize(Sec);
1023 if (checkOffset(Data, ConStart, SectionSize))
1024 return object_error::parse_failed;
1025 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1026 return object_error::success;
1029 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1030 return reinterpret_cast<const coff_relocation*>(Rel.p);
1033 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1034 Rel.p = reinterpret_cast<uintptr_t>(
1035 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1038 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
1039 uint64_t &Res) const {
1040 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
1043 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
1044 uint64_t &Res) const {
1045 const coff_relocation *R = toRel(Rel);
1046 const support::ulittle32_t *VirtualAddressPtr;
1047 if (std::error_code EC =
1048 getObject(VirtualAddressPtr, Data, &R->VirtualAddress))
1050 Res = *VirtualAddressPtr;
1051 return object_error::success;
1054 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1055 const coff_relocation *R = toRel(Rel);
1057 if (R->SymbolTableIndex >= getNumberOfSymbols())
1058 return symbol_end();
1060 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1061 else if (SymbolTable32)
1062 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1064 llvm_unreachable("no symbol table pointer!");
1065 return symbol_iterator(SymbolRef(Ref, this));
1068 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
1069 uint64_t &Res) const {
1070 const coff_relocation* R = toRel(Rel);
1072 return object_error::success;
1075 const coff_section *
1076 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1077 return toSec(Section.getRawDataRefImpl());
1080 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1082 return toSymb<coff_symbol16>(Ref);
1084 return toSymb<coff_symbol32>(Ref);
1085 llvm_unreachable("no symbol table pointer!");
1088 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1089 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1092 const coff_relocation *
1093 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1094 return toRel(Reloc.getRawDataRefImpl());
1097 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1098 case COFF::reloc_type: \
1099 Res = #reloc_type; \
1103 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
1104 SmallVectorImpl<char> &Result) const {
1105 const coff_relocation *Reloc = toRel(Rel);
1107 switch (getMachine()) {
1108 case COFF::IMAGE_FILE_MACHINE_AMD64:
1109 switch (Reloc->Type) {
1110 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1111 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1112 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1113 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1114 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1115 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1116 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1117 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1118 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1119 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1120 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1121 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1122 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1123 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1124 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1125 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1126 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1131 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1132 switch (Reloc->Type) {
1133 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1134 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1135 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1136 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1137 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1138 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1139 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1140 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1141 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1142 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1143 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1144 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1145 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1146 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1147 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1152 case COFF::IMAGE_FILE_MACHINE_I386:
1153 switch (Reloc->Type) {
1154 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1155 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1156 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1157 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1158 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1159 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1160 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1161 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1162 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1163 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1164 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1172 Result.append(Res.begin(), Res.end());
1173 return object_error::success;
1176 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1179 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
1180 SmallVectorImpl<char> &Result) const {
1181 const coff_relocation *Reloc = toRel(Rel);
1183 ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1184 if (std::error_code EC = Symb.getError())
1186 Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1188 if (std::error_code EC = getSymbolName(Sym, SymName))
1190 Result.append(SymName.begin(), SymName.end());
1191 return object_error::success;
1194 bool COFFObjectFile::isRelocatableObject() const {
1195 return !DataDirectory;
1198 bool ImportDirectoryEntryRef::
1199 operator==(const ImportDirectoryEntryRef &Other) const {
1200 return ImportTable == Other.ImportTable && Index == Other.Index;
1203 void ImportDirectoryEntryRef::moveNext() {
1207 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1208 const import_directory_table_entry *&Result) const {
1209 Result = ImportTable + Index;
1210 return object_error::success;
1213 static imported_symbol_iterator
1214 makeImportedSymbolIterator(const COFFObjectFile *Object,
1215 uintptr_t Ptr, int Index) {
1216 if (Object->getBytesInAddress() == 4) {
1217 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1218 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1220 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1221 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1224 static imported_symbol_iterator
1225 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1226 uintptr_t IntPtr = 0;
1227 Object->getRvaPtr(RVA, IntPtr);
1228 return makeImportedSymbolIterator(Object, IntPtr, 0);
1231 static imported_symbol_iterator
1232 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1233 uintptr_t IntPtr = 0;
1234 Object->getRvaPtr(RVA, IntPtr);
1235 // Forward the pointer to the last entry which is null.
1237 if (Object->getBytesInAddress() == 4) {
1238 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1242 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1246 return makeImportedSymbolIterator(Object, IntPtr, Index);
1249 imported_symbol_iterator
1250 ImportDirectoryEntryRef::imported_symbol_begin() const {
1251 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1255 imported_symbol_iterator
1256 ImportDirectoryEntryRef::imported_symbol_end() const {
1257 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1261 iterator_range<imported_symbol_iterator>
1262 ImportDirectoryEntryRef::imported_symbols() const {
1263 return make_range(imported_symbol_begin(), imported_symbol_end());
1266 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1267 uintptr_t IntPtr = 0;
1268 if (std::error_code EC =
1269 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1271 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1272 return object_error::success;
1276 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1277 Result = ImportTable[Index].ImportLookupTableRVA;
1278 return object_error::success;
1282 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1283 Result = ImportTable[Index].ImportAddressTableRVA;
1284 return object_error::success;
1287 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1288 const import_lookup_table_entry32 *&Result) const {
1289 uintptr_t IntPtr = 0;
1290 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1291 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1293 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1294 return object_error::success;
1297 bool DelayImportDirectoryEntryRef::
1298 operator==(const DelayImportDirectoryEntryRef &Other) const {
1299 return Table == Other.Table && Index == Other.Index;
1302 void DelayImportDirectoryEntryRef::moveNext() {
1306 imported_symbol_iterator
1307 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1308 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1312 imported_symbol_iterator
1313 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1314 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1318 iterator_range<imported_symbol_iterator>
1319 DelayImportDirectoryEntryRef::imported_symbols() const {
1320 return make_range(imported_symbol_begin(), imported_symbol_end());
1323 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1324 uintptr_t IntPtr = 0;
1325 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1327 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1328 return object_error::success;
1331 std::error_code DelayImportDirectoryEntryRef::
1332 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1334 return object_error::success;
1337 std::error_code DelayImportDirectoryEntryRef::
1338 getImportAddress(int AddrIndex, uint64_t &Result) const {
1339 uint32_t RVA = Table[Index].DelayImportAddressTable +
1340 AddrIndex * (OwningObject->is64() ? 8 : 4);
1341 uintptr_t IntPtr = 0;
1342 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1344 if (OwningObject->is64())
1345 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1347 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1348 return object_error::success;
1351 bool ExportDirectoryEntryRef::
1352 operator==(const ExportDirectoryEntryRef &Other) const {
1353 return ExportTable == Other.ExportTable && Index == Other.Index;
1356 void ExportDirectoryEntryRef::moveNext() {
1360 // Returns the name of the current export symbol. If the symbol is exported only
1361 // by ordinal, the empty string is set as a result.
1362 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1363 uintptr_t IntPtr = 0;
1364 if (std::error_code EC =
1365 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1367 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1368 return object_error::success;
1371 // Returns the starting ordinal number.
1373 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1374 Result = ExportTable->OrdinalBase;
1375 return object_error::success;
1378 // Returns the export ordinal of the current export symbol.
1379 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1380 Result = ExportTable->OrdinalBase + Index;
1381 return object_error::success;
1384 // Returns the address of the current export symbol.
1385 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1386 uintptr_t IntPtr = 0;
1387 if (std::error_code EC =
1388 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1390 const export_address_table_entry *entry =
1391 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1392 Result = entry[Index].ExportRVA;
1393 return object_error::success;
1396 // Returns the name of the current export symbol. If the symbol is exported only
1397 // by ordinal, the empty string is set as a result.
1399 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1400 uintptr_t IntPtr = 0;
1401 if (std::error_code EC =
1402 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1404 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1406 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1408 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1409 I < E; ++I, ++Offset) {
1412 if (std::error_code EC =
1413 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1415 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1416 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1418 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1419 return object_error::success;
1422 return object_error::success;
1425 bool ImportedSymbolRef::
1426 operator==(const ImportedSymbolRef &Other) const {
1427 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1428 && Index == Other.Index;
1431 void ImportedSymbolRef::moveNext() {
1436 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1439 // If a symbol is imported only by ordinal, it has no name.
1440 if (Entry32[Index].isOrdinal())
1441 return object_error::success;
1442 RVA = Entry32[Index].getHintNameRVA();
1444 if (Entry64[Index].isOrdinal())
1445 return object_error::success;
1446 RVA = Entry64[Index].getHintNameRVA();
1448 uintptr_t IntPtr = 0;
1449 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1451 // +2 because the first two bytes is hint.
1452 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1453 return object_error::success;
1456 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1459 if (Entry32[Index].isOrdinal()) {
1460 Result = Entry32[Index].getOrdinal();
1461 return object_error::success;
1463 RVA = Entry32[Index].getHintNameRVA();
1465 if (Entry64[Index].isOrdinal()) {
1466 Result = Entry64[Index].getOrdinal();
1467 return object_error::success;
1469 RVA = Entry64[Index].getHintNameRVA();
1471 uintptr_t IntPtr = 0;
1472 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1474 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1475 return object_error::success;
1478 ErrorOr<std::unique_ptr<COFFObjectFile>>
1479 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1481 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1484 return std::move(Ret);
1487 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1488 return Header == Other.Header && Index == Other.Index;
1491 void BaseRelocRef::moveNext() {
1492 // Header->BlockSize is the size of the current block, including the
1493 // size of the header itself.
1494 uint32_t Size = sizeof(*Header) +
1495 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1496 if (Size == Header->BlockSize) {
1497 // .reloc contains a list of base relocation blocks. Each block
1498 // consists of the header followed by entries. The header contains
1499 // how many entories will follow. When we reach the end of the
1500 // current block, proceed to the next block.
1501 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1502 reinterpret_cast<const uint8_t *>(Header) + Size);
1509 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1510 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1511 Type = Entry[Index].getType();
1512 return object_error::success;
1515 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1516 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1517 Result = Header->PageRVA + Entry[Index].getOffset();
1518 return object_error::success;