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 Symb.isSectionDefinition()) {
195 // TODO: perhaps we need a new symbol type ST_Section.
196 Result = SymbolRef::ST_Debug;
197 } else if (!COFF::isReservedSectionNumber(SectionNumber)) {
198 const coff_section *Section = nullptr;
199 if (std::error_code EC = getSection(SectionNumber, Section))
201 uint32_t Characteristics = Section->Characteristics;
202 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
203 Result = SymbolRef::ST_Function;
204 else if (Characteristics & (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
205 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA))
206 Result = SymbolRef::ST_Data;
208 return object_error::success;
211 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
212 COFFSymbolRef Symb = getCOFFSymbol(Ref);
213 uint32_t Result = SymbolRef::SF_None;
215 if (Symb.isExternal() || Symb.isWeakExternal())
216 Result |= SymbolRef::SF_Global;
218 if (Symb.isWeakExternal())
219 Result |= SymbolRef::SF_Weak;
221 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
222 Result |= SymbolRef::SF_Absolute;
224 if (Symb.isFileRecord())
225 Result |= SymbolRef::SF_FormatSpecific;
227 if (Symb.isSectionDefinition())
228 Result |= SymbolRef::SF_FormatSpecific;
231 Result |= SymbolRef::SF_Common;
233 if (Symb.isAnyUndefined())
234 Result |= SymbolRef::SF_Undefined;
239 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
240 uint64_t &Result) const {
241 COFFSymbolRef Symb = getCOFFSymbol(Ref);
243 if (Symb.isAnyUndefined()) {
244 Result = UnknownAddressOrSize;
245 return object_error::success;
247 if (Symb.isCommon()) {
248 Result = Symb.getValue();
249 return object_error::success;
252 // Let's attempt to get the size of the symbol by looking at the address of
253 // the symbol after the symbol in question.
255 if (std::error_code EC = getSymbolAddress(Ref, SymbAddr))
257 int32_t SectionNumber = Symb.getSectionNumber();
258 if (COFF::isReservedSectionNumber(SectionNumber)) {
259 // Absolute and debug symbols aren't sorted in any interesting way.
261 return object_error::success;
263 const section_iterator SecEnd = section_end();
264 uint64_t AfterAddr = UnknownAddressOrSize;
265 for (const symbol_iterator &SymbI : symbols()) {
266 section_iterator SecI = SecEnd;
267 if (std::error_code EC = SymbI->getSection(SecI))
269 // Check the symbol's section, skip it if it's in the wrong section.
270 // First, make sure it is in any section.
273 // Second, make sure it is in the same section as the symbol in question.
274 if (!sectionContainsSymbol(SecI->getRawDataRefImpl(), Ref))
277 if (std::error_code EC = SymbI->getAddress(Addr))
279 // We want to compare our symbol in question with the closest possible
280 // symbol that comes after.
281 if (AfterAddr > Addr && Addr > SymbAddr)
284 if (AfterAddr == UnknownAddressOrSize) {
285 // No symbol comes after this one, assume that everything after our symbol
287 const coff_section *Section = nullptr;
288 if (std::error_code EC = getSection(SectionNumber, Section))
290 Result = Section->SizeOfRawData - Symb.getValue();
292 // Take the difference between our symbol and the symbol that comes after
294 Result = AfterAddr - SymbAddr;
297 return object_error::success;
301 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
302 section_iterator &Result) const {
303 COFFSymbolRef Symb = getCOFFSymbol(Ref);
304 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
305 Result = section_end();
307 const coff_section *Sec = nullptr;
308 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
311 Ref.p = reinterpret_cast<uintptr_t>(Sec);
312 Result = section_iterator(SectionRef(Ref, this));
314 return object_error::success;
317 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
318 const coff_section *Sec = toSec(Ref);
320 Ref.p = reinterpret_cast<uintptr_t>(Sec);
323 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
324 StringRef &Result) const {
325 const coff_section *Sec = toSec(Ref);
326 return getSectionName(Sec, Result);
329 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
330 const coff_section *Sec = toSec(Ref);
331 return Sec->VirtualAddress;
334 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
335 return getSectionSize(toSec(Ref));
338 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
339 StringRef &Result) const {
340 const coff_section *Sec = toSec(Ref);
341 ArrayRef<uint8_t> Res;
342 std::error_code EC = getSectionContents(Sec, Res);
343 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
347 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
348 const coff_section *Sec = toSec(Ref);
349 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
352 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
353 const coff_section *Sec = toSec(Ref);
354 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
357 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
358 const coff_section *Sec = toSec(Ref);
359 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
362 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
363 const coff_section *Sec = toSec(Ref);
364 const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
365 COFF::IMAGE_SCN_MEM_READ |
366 COFF::IMAGE_SCN_MEM_WRITE;
367 return (Sec->Characteristics & BssFlags) == BssFlags;
370 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
371 const coff_section *Sec = toSec(Ref);
372 // In COFF, a virtual section won't have any in-file
373 // content, so the file pointer to the content will be zero.
374 return Sec->PointerToRawData == 0;
377 bool COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
378 DataRefImpl SymbRef) const {
379 const coff_section *Sec = toSec(SecRef);
380 COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
381 int32_t SecNumber = (Sec - SectionTable) + 1;
382 return SecNumber == Symb.getSectionNumber();
385 static uint32_t getNumberOfRelocations(const coff_section *Sec,
386 MemoryBufferRef M, const uint8_t *base) {
387 // The field for the number of relocations in COFF section table is only
388 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
389 // NumberOfRelocations field, and the actual relocation count is stored in the
390 // VirtualAddress field in the first relocation entry.
391 if (Sec->hasExtendedRelocations()) {
392 const coff_relocation *FirstReloc;
393 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
394 base + Sec->PointerToRelocations)))
396 // -1 to exclude this first relocation entry.
397 return FirstReloc->VirtualAddress - 1;
399 return Sec->NumberOfRelocations;
402 static const coff_relocation *
403 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
404 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
407 auto begin = reinterpret_cast<const coff_relocation *>(
408 Base + Sec->PointerToRelocations);
409 if (Sec->hasExtendedRelocations()) {
410 // Skip the first relocation entry repurposed to store the number of
414 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
419 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
420 const coff_section *Sec = toSec(Ref);
421 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
423 Ret.p = reinterpret_cast<uintptr_t>(begin);
424 return relocation_iterator(RelocationRef(Ret, this));
427 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
428 const coff_section *Sec = toSec(Ref);
429 const coff_relocation *I = getFirstReloc(Sec, Data, base());
431 I += getNumberOfRelocations(Sec, Data, base());
433 Ret.p = reinterpret_cast<uintptr_t>(I);
434 return relocation_iterator(RelocationRef(Ret, this));
437 // Initialize the pointer to the symbol table.
438 std::error_code COFFObjectFile::initSymbolTablePtr() {
440 if (std::error_code EC = getObject(
441 SymbolTable16, Data, base() + getPointerToSymbolTable(),
442 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
445 if (COFFBigObjHeader)
446 if (std::error_code EC = getObject(
447 SymbolTable32, Data, base() + getPointerToSymbolTable(),
448 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
451 // Find string table. The first four byte of the string table contains the
452 // total size of the string table, including the size field itself. If the
453 // string table is empty, the value of the first four byte would be 4.
454 uint32_t StringTableOffset = getPointerToSymbolTable() +
455 getNumberOfSymbols() * getSymbolTableEntrySize();
456 const uint8_t *StringTableAddr = base() + StringTableOffset;
457 const ulittle32_t *StringTableSizePtr;
458 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
460 StringTableSize = *StringTableSizePtr;
461 if (std::error_code EC =
462 getObject(StringTable, Data, StringTableAddr, StringTableSize))
465 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
466 // tools like cvtres write a size of 0 for an empty table instead of 4.
467 if (StringTableSize < 4)
470 // Check that the string table is null terminated if has any in it.
471 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
472 return object_error::parse_failed;
473 return object_error::success;
476 // Returns the file offset for the given VA.
477 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
478 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
479 : (uint64_t)PE32PlusHeader->ImageBase;
480 uint64_t Rva = Addr - ImageBase;
481 assert(Rva <= UINT32_MAX);
482 return getRvaPtr((uint32_t)Rva, Res);
485 // Returns the file offset for the given RVA.
486 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
487 for (const SectionRef &S : sections()) {
488 const coff_section *Section = getCOFFSection(S);
489 uint32_t SectionStart = Section->VirtualAddress;
490 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
491 if (SectionStart <= Addr && Addr < SectionEnd) {
492 uint32_t Offset = Addr - SectionStart;
493 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
494 return object_error::success;
497 return object_error::parse_failed;
500 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
502 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
503 StringRef &Name) const {
504 uintptr_t IntPtr = 0;
505 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
507 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
508 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
509 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
510 return object_error::success;
513 // Find the import table.
514 std::error_code COFFObjectFile::initImportTablePtr() {
515 // First, we get the RVA of the import table. If the file lacks a pointer to
516 // the import table, do nothing.
517 const data_directory *DataEntry;
518 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
519 return object_error::success;
521 // Do nothing if the pointer to import table is NULL.
522 if (DataEntry->RelativeVirtualAddress == 0)
523 return object_error::success;
525 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
526 // -1 because the last entry is the null entry.
527 NumberOfImportDirectory = DataEntry->Size /
528 sizeof(import_directory_table_entry) - 1;
530 // Find the section that contains the RVA. This is needed because the RVA is
531 // the import table's memory address which is different from its file offset.
532 uintptr_t IntPtr = 0;
533 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
535 ImportDirectory = reinterpret_cast<
536 const import_directory_table_entry *>(IntPtr);
537 return object_error::success;
540 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
541 std::error_code COFFObjectFile::initDelayImportTablePtr() {
542 const data_directory *DataEntry;
543 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
544 return object_error::success;
545 if (DataEntry->RelativeVirtualAddress == 0)
546 return object_error::success;
548 uint32_t RVA = DataEntry->RelativeVirtualAddress;
549 NumberOfDelayImportDirectory = DataEntry->Size /
550 sizeof(delay_import_directory_table_entry) - 1;
552 uintptr_t IntPtr = 0;
553 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
555 DelayImportDirectory = reinterpret_cast<
556 const delay_import_directory_table_entry *>(IntPtr);
557 return object_error::success;
560 // Find the export table.
561 std::error_code COFFObjectFile::initExportTablePtr() {
562 // First, we get the RVA of the export table. If the file lacks a pointer to
563 // the export table, do nothing.
564 const data_directory *DataEntry;
565 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
566 return object_error::success;
568 // Do nothing if the pointer to export table is NULL.
569 if (DataEntry->RelativeVirtualAddress == 0)
570 return object_error::success;
572 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
573 uintptr_t IntPtr = 0;
574 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
577 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
578 return object_error::success;
581 std::error_code COFFObjectFile::initBaseRelocPtr() {
582 const data_directory *DataEntry;
583 if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
584 return object_error::success;
585 if (DataEntry->RelativeVirtualAddress == 0)
586 return object_error::success;
588 uintptr_t IntPtr = 0;
589 if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
591 BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
593 BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
594 IntPtr + DataEntry->Size);
595 return object_error::success;
598 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
599 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
600 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
601 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
602 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
603 ImportDirectory(nullptr), NumberOfImportDirectory(0),
604 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
605 ExportDirectory(nullptr), BaseRelocHeader(nullptr),
606 BaseRelocEnd(nullptr) {
607 // Check that we at least have enough room for a header.
608 if (!checkSize(Data, EC, sizeof(coff_file_header)))
611 // The current location in the file where we are looking at.
614 // PE header is optional and is present only in executables. If it exists,
615 // it is placed right after COFF header.
616 bool HasPEHeader = false;
618 // Check if this is a PE/COFF file.
619 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
620 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
621 // PE signature to find 'normal' COFF header.
622 const auto *DH = reinterpret_cast<const dos_header *>(base());
623 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
624 CurPtr = DH->AddressOfNewExeHeader;
625 // Check the PE magic bytes. ("PE\0\0")
626 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
627 EC = object_error::parse_failed;
630 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
635 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
638 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
639 // import libraries share a common prefix but bigobj is more restrictive.
640 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
641 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
642 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
643 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
646 // Verify that we are dealing with bigobj.
647 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
648 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
649 sizeof(COFF::BigObjMagic)) == 0) {
650 COFFHeader = nullptr;
651 CurPtr += sizeof(coff_bigobj_file_header);
653 // It's not a bigobj.
654 COFFBigObjHeader = nullptr;
658 // The prior checkSize call may have failed. This isn't a hard error
659 // because we were just trying to sniff out bigobj.
660 EC = object_error::success;
661 CurPtr += sizeof(coff_file_header);
663 if (COFFHeader->isImportLibrary())
668 const pe32_header *Header;
669 if ((EC = getObject(Header, Data, base() + CurPtr)))
672 const uint8_t *DataDirAddr;
673 uint64_t DataDirSize;
674 if (Header->Magic == COFF::PE32Header::PE32) {
676 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
677 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
678 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
679 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
680 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
681 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
683 // It's neither PE32 nor PE32+.
684 EC = object_error::parse_failed;
687 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
689 CurPtr += COFFHeader->SizeOfOptionalHeader;
692 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
693 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
696 // Initialize the pointer to the symbol table.
697 if (getPointerToSymbolTable() != 0) {
698 if ((EC = initSymbolTablePtr()))
701 // We had better not have any symbols if we don't have a symbol table.
702 if (getNumberOfSymbols() != 0) {
703 EC = object_error::parse_failed;
708 // Initialize the pointer to the beginning of the import table.
709 if ((EC = initImportTablePtr()))
711 if ((EC = initDelayImportTablePtr()))
714 // Initialize the pointer to the export table.
715 if ((EC = initExportTablePtr()))
718 // Initialize the pointer to the base relocation table.
719 if ((EC = initBaseRelocPtr()))
722 EC = object_error::success;
725 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
727 Ret.p = getSymbolTable();
728 return basic_symbol_iterator(SymbolRef(Ret, this));
731 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
732 // The symbol table ends where the string table begins.
734 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
735 return basic_symbol_iterator(SymbolRef(Ret, this));
738 import_directory_iterator COFFObjectFile::import_directory_begin() const {
739 return import_directory_iterator(
740 ImportDirectoryEntryRef(ImportDirectory, 0, this));
743 import_directory_iterator COFFObjectFile::import_directory_end() const {
744 return import_directory_iterator(
745 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
748 delay_import_directory_iterator
749 COFFObjectFile::delay_import_directory_begin() const {
750 return delay_import_directory_iterator(
751 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
754 delay_import_directory_iterator
755 COFFObjectFile::delay_import_directory_end() const {
756 return delay_import_directory_iterator(
757 DelayImportDirectoryEntryRef(
758 DelayImportDirectory, NumberOfDelayImportDirectory, this));
761 export_directory_iterator COFFObjectFile::export_directory_begin() const {
762 return export_directory_iterator(
763 ExportDirectoryEntryRef(ExportDirectory, 0, this));
766 export_directory_iterator COFFObjectFile::export_directory_end() const {
767 if (!ExportDirectory)
768 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
769 ExportDirectoryEntryRef Ref(ExportDirectory,
770 ExportDirectory->AddressTableEntries, this);
771 return export_directory_iterator(Ref);
774 section_iterator COFFObjectFile::section_begin() const {
776 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
777 return section_iterator(SectionRef(Ret, this));
780 section_iterator COFFObjectFile::section_end() const {
783 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
784 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
785 return section_iterator(SectionRef(Ret, this));
788 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
789 return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
792 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
793 return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
796 uint8_t COFFObjectFile::getBytesInAddress() const {
797 return getArch() == Triple::x86_64 ? 8 : 4;
800 StringRef COFFObjectFile::getFileFormatName() const {
801 switch(getMachine()) {
802 case COFF::IMAGE_FILE_MACHINE_I386:
804 case COFF::IMAGE_FILE_MACHINE_AMD64:
805 return "COFF-x86-64";
806 case COFF::IMAGE_FILE_MACHINE_ARMNT:
809 return "COFF-<unknown arch>";
813 unsigned COFFObjectFile::getArch() const {
814 switch (getMachine()) {
815 case COFF::IMAGE_FILE_MACHINE_I386:
817 case COFF::IMAGE_FILE_MACHINE_AMD64:
818 return Triple::x86_64;
819 case COFF::IMAGE_FILE_MACHINE_ARMNT:
820 return Triple::thumb;
822 return Triple::UnknownArch;
826 iterator_range<import_directory_iterator>
827 COFFObjectFile::import_directories() const {
828 return make_range(import_directory_begin(), import_directory_end());
831 iterator_range<delay_import_directory_iterator>
832 COFFObjectFile::delay_import_directories() const {
833 return make_range(delay_import_directory_begin(),
834 delay_import_directory_end());
837 iterator_range<export_directory_iterator>
838 COFFObjectFile::export_directories() const {
839 return make_range(export_directory_begin(), export_directory_end());
842 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
843 return make_range(base_reloc_begin(), base_reloc_end());
846 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
848 return object_error::success;
852 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
853 Res = PE32PlusHeader;
854 return object_error::success;
858 COFFObjectFile::getDataDirectory(uint32_t Index,
859 const data_directory *&Res) const {
860 // Error if if there's no data directory or the index is out of range.
861 if (!DataDirectory) {
863 return object_error::parse_failed;
865 assert(PE32Header || PE32PlusHeader);
866 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
867 : PE32PlusHeader->NumberOfRvaAndSize;
868 if (Index >= NumEnt) {
870 return object_error::parse_failed;
872 Res = &DataDirectory[Index];
873 return object_error::success;
876 std::error_code COFFObjectFile::getSection(int32_t Index,
877 const coff_section *&Result) const {
879 if (COFF::isReservedSectionNumber(Index))
880 return object_error::success;
881 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
882 // We already verified the section table data, so no need to check again.
883 Result = SectionTable + (Index - 1);
884 return object_error::success;
886 return object_error::parse_failed;
889 std::error_code COFFObjectFile::getString(uint32_t Offset,
890 StringRef &Result) const {
891 if (StringTableSize <= 4)
892 // Tried to get a string from an empty string table.
893 return object_error::parse_failed;
894 if (Offset >= StringTableSize)
895 return object_error::unexpected_eof;
896 Result = StringRef(StringTable + Offset);
897 return object_error::success;
900 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
901 StringRef &Res) const {
902 // Check for string table entry. First 4 bytes are 0.
903 if (Symbol.getStringTableOffset().Zeroes == 0) {
904 uint32_t Offset = Symbol.getStringTableOffset().Offset;
905 if (std::error_code EC = getString(Offset, Res))
907 return object_error::success;
910 if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
911 // Null terminated, let ::strlen figure out the length.
912 Res = StringRef(Symbol.getShortName());
914 // Not null terminated, use all 8 bytes.
915 Res = StringRef(Symbol.getShortName(), COFF::NameSize);
916 return object_error::success;
920 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
921 const uint8_t *Aux = nullptr;
923 size_t SymbolSize = getSymbolTableEntrySize();
924 if (Symbol.getNumberOfAuxSymbols() > 0) {
925 // AUX data comes immediately after the symbol in COFF
926 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
928 // Verify that the Aux symbol points to a valid entry in the symbol table.
929 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
930 if (Offset < getPointerToSymbolTable() ||
932 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
933 report_fatal_error("Aux Symbol data was outside of symbol table.");
935 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
936 "Aux Symbol data did not point to the beginning of a symbol");
939 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
942 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
943 StringRef &Res) const {
945 if (Sec->Name[COFF::NameSize - 1] == 0)
946 // Null terminated, let ::strlen figure out the length.
949 // Not null terminated, use all 8 bytes.
950 Name = StringRef(Sec->Name, COFF::NameSize);
952 // Check for string table entry. First byte is '/'.
953 if (Name.startswith("/")) {
955 if (Name.startswith("//")) {
956 if (decodeBase64StringEntry(Name.substr(2), Offset))
957 return object_error::parse_failed;
959 if (Name.substr(1).getAsInteger(10, Offset))
960 return object_error::parse_failed;
962 if (std::error_code EC = getString(Offset, Name))
967 return object_error::success;
970 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
971 // SizeOfRawData and VirtualSize change what they represent depending on
972 // whether or not we have an executable image.
974 // For object files, SizeOfRawData contains the size of section's data;
975 // VirtualSize is always zero.
977 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
978 // actual section size is in VirtualSize. It is possible for VirtualSize to
979 // be greater than SizeOfRawData; the contents past that point should be
980 // considered to be zero.
981 uint32_t SectionSize;
982 if (Sec->VirtualSize)
983 SectionSize = std::min(Sec->VirtualSize, Sec->SizeOfRawData);
985 SectionSize = Sec->SizeOfRawData;
991 COFFObjectFile::getSectionContents(const coff_section *Sec,
992 ArrayRef<uint8_t> &Res) const {
993 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
994 // don't do anything interesting for them.
995 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
996 "BSS sections don't have contents!");
997 // The only thing that we need to verify is that the contents is contained
998 // within the file bounds. We don't need to make sure it doesn't cover other
999 // data, as there's nothing that says that is not allowed.
1000 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1001 uint32_t SectionSize = getSectionSize(Sec);
1002 if (checkOffset(Data, ConStart, SectionSize))
1003 return object_error::parse_failed;
1004 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1005 return object_error::success;
1008 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1009 return reinterpret_cast<const coff_relocation*>(Rel.p);
1012 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1013 Rel.p = reinterpret_cast<uintptr_t>(
1014 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1017 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
1018 uint64_t &Res) const {
1019 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
1022 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
1023 uint64_t &Res) const {
1024 const coff_relocation *R = toRel(Rel);
1025 const support::ulittle32_t *VirtualAddressPtr;
1026 if (std::error_code EC =
1027 getObject(VirtualAddressPtr, Data, &R->VirtualAddress))
1029 Res = *VirtualAddressPtr;
1030 return object_error::success;
1033 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1034 const coff_relocation *R = toRel(Rel);
1036 if (R->SymbolTableIndex >= getNumberOfSymbols())
1037 return symbol_end();
1039 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1040 else if (SymbolTable32)
1041 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1043 llvm_unreachable("no symbol table pointer!");
1044 return symbol_iterator(SymbolRef(Ref, this));
1047 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
1048 uint64_t &Res) const {
1049 const coff_relocation* R = toRel(Rel);
1051 return object_error::success;
1054 const coff_section *
1055 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1056 return toSec(Section.getRawDataRefImpl());
1059 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1061 return toSymb<coff_symbol16>(Ref);
1063 return toSymb<coff_symbol32>(Ref);
1064 llvm_unreachable("no symbol table pointer!");
1067 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1068 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1071 const coff_relocation *
1072 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1073 return toRel(Reloc.getRawDataRefImpl());
1076 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1077 case COFF::reloc_type: \
1078 Res = #reloc_type; \
1082 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
1083 SmallVectorImpl<char> &Result) const {
1084 const coff_relocation *Reloc = toRel(Rel);
1086 switch (getMachine()) {
1087 case COFF::IMAGE_FILE_MACHINE_AMD64:
1088 switch (Reloc->Type) {
1089 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1090 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1091 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1092 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1093 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1094 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1095 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1096 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1097 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1098 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1099 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1100 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1101 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1102 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1103 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1104 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1105 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1110 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1111 switch (Reloc->Type) {
1112 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1113 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1114 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1115 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1116 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1117 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1118 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1119 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1120 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1121 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1122 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1123 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1124 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1125 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1126 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1131 case COFF::IMAGE_FILE_MACHINE_I386:
1132 switch (Reloc->Type) {
1133 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1134 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1135 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1136 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1137 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1138 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1139 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1140 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1141 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1142 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1143 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1151 Result.append(Res.begin(), Res.end());
1152 return object_error::success;
1155 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1158 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
1159 SmallVectorImpl<char> &Result) const {
1160 const coff_relocation *Reloc = toRel(Rel);
1162 ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1163 if (std::error_code EC = Symb.getError())
1165 Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1167 if (std::error_code EC = getSymbolName(Sym, SymName))
1169 Result.append(SymName.begin(), SymName.end());
1170 return object_error::success;
1173 bool COFFObjectFile::isRelocatableObject() const {
1174 return !DataDirectory;
1177 bool ImportDirectoryEntryRef::
1178 operator==(const ImportDirectoryEntryRef &Other) const {
1179 return ImportTable == Other.ImportTable && Index == Other.Index;
1182 void ImportDirectoryEntryRef::moveNext() {
1186 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1187 const import_directory_table_entry *&Result) const {
1188 Result = ImportTable + Index;
1189 return object_error::success;
1192 static imported_symbol_iterator
1193 makeImportedSymbolIterator(const COFFObjectFile *Object,
1194 uintptr_t Ptr, int Index) {
1195 if (Object->getBytesInAddress() == 4) {
1196 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1197 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1199 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1200 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1203 static imported_symbol_iterator
1204 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1205 uintptr_t IntPtr = 0;
1206 Object->getRvaPtr(RVA, IntPtr);
1207 return makeImportedSymbolIterator(Object, IntPtr, 0);
1210 static imported_symbol_iterator
1211 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1212 uintptr_t IntPtr = 0;
1213 Object->getRvaPtr(RVA, IntPtr);
1214 // Forward the pointer to the last entry which is null.
1216 if (Object->getBytesInAddress() == 4) {
1217 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1221 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1225 return makeImportedSymbolIterator(Object, IntPtr, Index);
1228 imported_symbol_iterator
1229 ImportDirectoryEntryRef::imported_symbol_begin() const {
1230 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1234 imported_symbol_iterator
1235 ImportDirectoryEntryRef::imported_symbol_end() const {
1236 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1240 iterator_range<imported_symbol_iterator>
1241 ImportDirectoryEntryRef::imported_symbols() const {
1242 return make_range(imported_symbol_begin(), imported_symbol_end());
1245 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1246 uintptr_t IntPtr = 0;
1247 if (std::error_code EC =
1248 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1250 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1251 return object_error::success;
1255 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1256 Result = ImportTable[Index].ImportLookupTableRVA;
1257 return object_error::success;
1261 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1262 Result = ImportTable[Index].ImportAddressTableRVA;
1263 return object_error::success;
1266 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1267 const import_lookup_table_entry32 *&Result) const {
1268 uintptr_t IntPtr = 0;
1269 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1270 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1272 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1273 return object_error::success;
1276 bool DelayImportDirectoryEntryRef::
1277 operator==(const DelayImportDirectoryEntryRef &Other) const {
1278 return Table == Other.Table && Index == Other.Index;
1281 void DelayImportDirectoryEntryRef::moveNext() {
1285 imported_symbol_iterator
1286 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1287 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1291 imported_symbol_iterator
1292 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1293 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1297 iterator_range<imported_symbol_iterator>
1298 DelayImportDirectoryEntryRef::imported_symbols() const {
1299 return make_range(imported_symbol_begin(), imported_symbol_end());
1302 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1303 uintptr_t IntPtr = 0;
1304 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1306 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1307 return object_error::success;
1310 std::error_code DelayImportDirectoryEntryRef::
1311 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1313 return object_error::success;
1316 std::error_code DelayImportDirectoryEntryRef::
1317 getImportAddress(int AddrIndex, uint64_t &Result) const {
1318 uint32_t RVA = Table[Index].DelayImportAddressTable +
1319 AddrIndex * (OwningObject->is64() ? 8 : 4);
1320 uintptr_t IntPtr = 0;
1321 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1323 if (OwningObject->is64())
1324 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1326 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1327 return object_error::success;
1330 bool ExportDirectoryEntryRef::
1331 operator==(const ExportDirectoryEntryRef &Other) const {
1332 return ExportTable == Other.ExportTable && Index == Other.Index;
1335 void ExportDirectoryEntryRef::moveNext() {
1339 // Returns the name of the current export symbol. If the symbol is exported only
1340 // by ordinal, the empty string is set as a result.
1341 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1342 uintptr_t IntPtr = 0;
1343 if (std::error_code EC =
1344 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1346 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1347 return object_error::success;
1350 // Returns the starting ordinal number.
1352 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1353 Result = ExportTable->OrdinalBase;
1354 return object_error::success;
1357 // Returns the export ordinal of the current export symbol.
1358 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1359 Result = ExportTable->OrdinalBase + Index;
1360 return object_error::success;
1363 // Returns the address of the current export symbol.
1364 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1365 uintptr_t IntPtr = 0;
1366 if (std::error_code EC =
1367 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1369 const export_address_table_entry *entry =
1370 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1371 Result = entry[Index].ExportRVA;
1372 return object_error::success;
1375 // Returns the name of the current export symbol. If the symbol is exported only
1376 // by ordinal, the empty string is set as a result.
1378 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1379 uintptr_t IntPtr = 0;
1380 if (std::error_code EC =
1381 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1383 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1385 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1387 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1388 I < E; ++I, ++Offset) {
1391 if (std::error_code EC =
1392 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1394 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1395 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1397 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1398 return object_error::success;
1401 return object_error::success;
1404 bool ImportedSymbolRef::
1405 operator==(const ImportedSymbolRef &Other) const {
1406 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1407 && Index == Other.Index;
1410 void ImportedSymbolRef::moveNext() {
1415 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1418 // If a symbol is imported only by ordinal, it has no name.
1419 if (Entry32[Index].isOrdinal())
1420 return object_error::success;
1421 RVA = Entry32[Index].getHintNameRVA();
1423 if (Entry64[Index].isOrdinal())
1424 return object_error::success;
1425 RVA = Entry64[Index].getHintNameRVA();
1427 uintptr_t IntPtr = 0;
1428 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1430 // +2 because the first two bytes is hint.
1431 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1432 return object_error::success;
1435 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1438 if (Entry32[Index].isOrdinal()) {
1439 Result = Entry32[Index].getOrdinal();
1440 return object_error::success;
1442 RVA = Entry32[Index].getHintNameRVA();
1444 if (Entry64[Index].isOrdinal()) {
1445 Result = Entry64[Index].getOrdinal();
1446 return object_error::success;
1448 RVA = Entry64[Index].getHintNameRVA();
1450 uintptr_t IntPtr = 0;
1451 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1453 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1454 return object_error::success;
1457 ErrorOr<std::unique_ptr<COFFObjectFile>>
1458 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1460 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1463 return std::move(Ret);
1466 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1467 return Header == Other.Header && Index == Other.Index;
1470 void BaseRelocRef::moveNext() {
1471 // Header->BlockSize is the size of the current block, including the
1472 // size of the header itself.
1473 uint32_t Size = sizeof(*Header) +
1474 sizeof(coff_base_reloc_block_entry) * (Index + 1);
1475 if (Size == Header->BlockSize) {
1476 // .reloc contains a list of base relocation blocks. Each block
1477 // consists of the header followed by entries. The header contains
1478 // how many entories will follow. When we reach the end of the
1479 // current block, proceed to the next block.
1480 Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1481 reinterpret_cast<const uint8_t *>(Header) + Size);
1488 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1489 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1490 Type = Entry[Index].getType();
1491 return object_error::success;
1494 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1495 auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1496 Result = Header->PageRVA + Entry[Index].getOffset();
1497 return object_error::success;