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 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
43 // Returns unexpected_eof if error.
45 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
47 const size_t Size = sizeof(T)) {
48 uintptr_t Addr = uintptr_t(Ptr);
49 if (Addr + Size < Addr || Addr + Size < Size ||
50 Addr + Size > uintptr_t(M.getBufferEnd()) ||
51 Addr < uintptr_t(M.getBufferStart())) {
52 return object_error::unexpected_eof;
54 Obj = reinterpret_cast<const T *>(Addr);
55 return object_error::success;
58 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
60 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
61 assert(Str.size() <= 6 && "String too long, possible overflow.");
66 while (!Str.empty()) {
68 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
69 CharVal = Str[0] - 'A';
70 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
71 CharVal = Str[0] - 'a' + 26;
72 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
73 CharVal = Str[0] - '0' + 52;
74 else if (Str[0] == '+') // 62
76 else if (Str[0] == '/') // 63
81 Value = (Value * 64) + CharVal;
85 if (Value > std::numeric_limits<uint32_t>::max())
88 Result = static_cast<uint32_t>(Value);
92 template <typename coff_symbol_type>
93 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
94 const coff_symbol_type *Addr =
95 reinterpret_cast<const coff_symbol_type *>(Ref.p);
98 // Verify that the symbol points to a valid entry in the symbol table.
99 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
100 if (Offset < getPointerToSymbolTable() ||
101 Offset >= getPointerToSymbolTable() +
102 (getNumberOfSymbols() * sizeof(coff_symbol_type)))
103 report_fatal_error("Symbol was outside of symbol table.");
105 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
106 "Symbol did not point to the beginning of a symbol");
112 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
113 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
116 // Verify that the section points to a valid entry in the section table.
117 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
118 report_fatal_error("Section was outside of section table.");
120 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
121 assert(Offset % sizeof(coff_section) == 0 &&
122 "Section did not point to the beginning of a section");
128 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
130 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
131 Symb += 1 + Symb->NumberOfAuxSymbols;
132 Ref.p = reinterpret_cast<uintptr_t>(Symb);
133 } else if (SymbolTable32) {
134 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
135 Symb += 1 + Symb->NumberOfAuxSymbols;
136 Ref.p = reinterpret_cast<uintptr_t>(Symb);
138 llvm_unreachable("no symbol table pointer!");
142 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
143 StringRef &Result) const {
144 COFFSymbolRef Symb = getCOFFSymbol(Ref);
145 return getSymbolName(Symb, Result);
148 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
149 uint64_t &Result) const {
150 COFFSymbolRef Symb = getCOFFSymbol(Ref);
152 if (Symb.isAnyUndefined()) {
153 Result = UnknownAddressOrSize;
154 return object_error::success;
156 if (Symb.isCommon()) {
157 Result = UnknownAddressOrSize;
158 return object_error::success;
160 int32_t SectionNumber = Symb.getSectionNumber();
161 if (!COFF::isReservedSectionNumber(SectionNumber)) {
162 const coff_section *Section = nullptr;
163 if (std::error_code EC = getSection(SectionNumber, Section))
166 Result = Section->VirtualAddress + Symb.getValue();
167 return object_error::success;
170 Result = Symb.getValue();
171 return object_error::success;
174 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
175 SymbolRef::Type &Result) const {
176 COFFSymbolRef Symb = getCOFFSymbol(Ref);
177 int32_t SectionNumber = Symb.getSectionNumber();
178 Result = SymbolRef::ST_Other;
180 if (Symb.isAnyUndefined()) {
181 Result = SymbolRef::ST_Unknown;
182 } else if (Symb.isFunctionDefinition()) {
183 Result = SymbolRef::ST_Function;
184 } else if (Symb.isCommon()) {
185 Result = SymbolRef::ST_Data;
186 } else if (Symb.isFileRecord()) {
187 Result = SymbolRef::ST_File;
188 } else if (SectionNumber == COFF::IMAGE_SYM_DEBUG) {
189 Result = SymbolRef::ST_Debug;
190 } else if (!COFF::isReservedSectionNumber(SectionNumber)) {
191 const coff_section *Section = nullptr;
192 if (std::error_code EC = getSection(SectionNumber, Section))
194 uint32_t Characteristics = Section->Characteristics;
195 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
196 Result = SymbolRef::ST_Function;
197 else if (Characteristics & (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
198 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA))
199 Result = SymbolRef::ST_Data;
201 return object_error::success;
204 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
205 COFFSymbolRef Symb = getCOFFSymbol(Ref);
206 uint32_t Result = SymbolRef::SF_None;
208 if (Symb.isExternal() || Symb.isWeakExternal())
209 Result |= SymbolRef::SF_Global;
211 if (Symb.isWeakExternal())
212 Result |= SymbolRef::SF_Weak;
214 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
215 Result |= SymbolRef::SF_Absolute;
217 if (Symb.isFileRecord())
218 Result |= SymbolRef::SF_FormatSpecific;
220 if (Symb.isSectionDefinition())
221 Result |= SymbolRef::SF_FormatSpecific;
224 Result |= SymbolRef::SF_Common;
226 if (Symb.isAnyUndefined())
227 Result |= SymbolRef::SF_Undefined;
232 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
233 uint64_t &Result) const {
234 COFFSymbolRef Symb = getCOFFSymbol(Ref);
236 if (Symb.isAnyUndefined()) {
237 Result = UnknownAddressOrSize;
238 return object_error::success;
240 if (Symb.isCommon()) {
241 Result = Symb.getValue();
242 return object_error::success;
245 // Let's attempt to get the size of the symbol by looking at the address of
246 // the symbol after the symbol in question.
248 if (std::error_code EC = getSymbolAddress(Ref, SymbAddr))
250 int32_t SectionNumber = Symb.getSectionNumber();
251 if (COFF::isReservedSectionNumber(SectionNumber)) {
252 // Absolute and debug symbols aren't sorted in any interesting way.
254 return object_error::success;
256 const section_iterator SecEnd = section_end();
257 uint64_t AfterAddr = UnknownAddressOrSize;
258 for (const symbol_iterator &SymbI : symbols()) {
259 section_iterator SecI = SecEnd;
260 if (std::error_code EC = SymbI->getSection(SecI))
262 // Check the symbol's section, skip it if it's in the wrong section.
263 // First, make sure it is in any section.
266 // Second, make sure it is in the same section as the symbol in question.
267 if (!sectionContainsSymbol(SecI->getRawDataRefImpl(), Ref))
270 if (std::error_code EC = SymbI->getAddress(Addr))
272 // We want to compare our symbol in question with the closest possible
273 // symbol that comes after.
274 if (AfterAddr > Addr && Addr > SymbAddr)
277 if (AfterAddr == UnknownAddressOrSize) {
278 // No symbol comes after this one, assume that everything after our symbol
280 const coff_section *Section = nullptr;
281 if (std::error_code EC = getSection(SectionNumber, Section))
283 Result = Section->SizeOfRawData - Symb.getValue();
285 // Take the difference between our symbol and the symbol that comes after
287 Result = AfterAddr - SymbAddr;
290 return object_error::success;
294 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
295 section_iterator &Result) const {
296 COFFSymbolRef Symb = getCOFFSymbol(Ref);
297 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
298 Result = section_end();
300 const coff_section *Sec = nullptr;
301 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
304 Ref.p = reinterpret_cast<uintptr_t>(Sec);
305 Result = section_iterator(SectionRef(Ref, this));
307 return object_error::success;
310 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
311 const coff_section *Sec = toSec(Ref);
313 Ref.p = reinterpret_cast<uintptr_t>(Sec);
316 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
317 StringRef &Result) const {
318 const coff_section *Sec = toSec(Ref);
319 return getSectionName(Sec, Result);
322 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
323 const coff_section *Sec = toSec(Ref);
324 return Sec->VirtualAddress;
327 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
328 return getSectionSize(toSec(Ref));
331 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
332 StringRef &Result) const {
333 const coff_section *Sec = toSec(Ref);
334 ArrayRef<uint8_t> Res;
335 std::error_code EC = getSectionContents(Sec, Res);
336 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
340 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
341 const coff_section *Sec = toSec(Ref);
342 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
345 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
346 const coff_section *Sec = toSec(Ref);
347 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
350 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
351 const coff_section *Sec = toSec(Ref);
352 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
355 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
356 const coff_section *Sec = toSec(Ref);
357 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
360 bool COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref) const {
361 // FIXME: Unimplemented
365 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
366 const coff_section *Sec = toSec(Ref);
367 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
370 bool COFFObjectFile::isSectionZeroInit(DataRefImpl Ref) const {
371 // FIXME: Unimplemented.
375 bool COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref) const {
376 // FIXME: Unimplemented.
380 bool COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
381 DataRefImpl SymbRef) const {
382 const coff_section *Sec = toSec(SecRef);
383 COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
384 int32_t SecNumber = (Sec - SectionTable) + 1;
385 return SecNumber == Symb.getSectionNumber();
388 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
389 const coff_section *Sec = toSec(Ref);
391 if (Sec->NumberOfRelocations == 0) {
394 auto begin = reinterpret_cast<const coff_relocation*>(
395 base() + Sec->PointerToRelocations);
396 if (Sec->hasExtendedRelocations()) {
397 // Skip the first relocation entry repurposed to store the number of
401 Ret.p = reinterpret_cast<uintptr_t>(begin);
403 return relocation_iterator(RelocationRef(Ret, this));
406 static uint32_t getNumberOfRelocations(const coff_section *Sec,
407 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 auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
414 base + Sec->PointerToRelocations);
415 return FirstReloc->VirtualAddress;
417 return Sec->NumberOfRelocations;
420 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
421 const coff_section *Sec = toSec(Ref);
423 if (Sec->NumberOfRelocations == 0) {
426 auto begin = reinterpret_cast<const coff_relocation*>(
427 base() + Sec->PointerToRelocations);
428 if (Sec->hasExtendedRelocations()) {
429 // Skip the first relocation entry repurposed to store the number of
433 uint32_t NumReloc = getNumberOfRelocations(Sec, base());
434 Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
436 return relocation_iterator(RelocationRef(Ret, this));
439 // Initialize the pointer to the symbol table.
440 std::error_code COFFObjectFile::initSymbolTablePtr() {
442 if (std::error_code EC =
443 getObject(SymbolTable16, Data, base() + getPointerToSymbolTable(),
444 getNumberOfSymbols() * getSymbolTableEntrySize()))
447 if (COFFBigObjHeader)
448 if (std::error_code EC =
449 getObject(SymbolTable32, Data, base() + getPointerToSymbolTable(),
450 getNumberOfSymbols() * getSymbolTableEntrySize()))
453 // Find string table. The first four byte of the string table contains the
454 // total size of the string table, including the size field itself. If the
455 // string table is empty, the value of the first four byte would be 4.
456 const uint8_t *StringTableAddr =
457 base() + getPointerToSymbolTable() +
458 getNumberOfSymbols() * getSymbolTableEntrySize();
459 const ulittle32_t *StringTableSizePtr;
460 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
462 StringTableSize = *StringTableSizePtr;
463 if (std::error_code EC =
464 getObject(StringTable, Data, StringTableAddr, StringTableSize))
467 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
468 // tools like cvtres write a size of 0 for an empty table instead of 4.
469 if (StringTableSize < 4)
472 // Check that the string table is null terminated if has any in it.
473 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
474 return object_error::parse_failed;
475 return object_error::success;
478 // Returns the file offset for the given VA.
479 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
480 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
481 : (uint64_t)PE32PlusHeader->ImageBase;
482 uint64_t Rva = Addr - ImageBase;
483 assert(Rva <= UINT32_MAX);
484 return getRvaPtr((uint32_t)Rva, Res);
487 // Returns the file offset for the given RVA.
488 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
489 for (const SectionRef &S : sections()) {
490 const coff_section *Section = getCOFFSection(S);
491 uint32_t SectionStart = Section->VirtualAddress;
492 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
493 if (SectionStart <= Addr && Addr < SectionEnd) {
494 uint32_t Offset = Addr - SectionStart;
495 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
496 return object_error::success;
499 return object_error::parse_failed;
502 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
504 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
505 StringRef &Name) const {
506 uintptr_t IntPtr = 0;
507 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
509 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
510 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
511 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
512 return object_error::success;
515 // Find the import table.
516 std::error_code COFFObjectFile::initImportTablePtr() {
517 // First, we get the RVA of the import table. If the file lacks a pointer to
518 // the import table, do nothing.
519 const data_directory *DataEntry;
520 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
521 return object_error::success;
523 // Do nothing if the pointer to import table is NULL.
524 if (DataEntry->RelativeVirtualAddress == 0)
525 return object_error::success;
527 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
528 // -1 because the last entry is the null entry.
529 NumberOfImportDirectory = DataEntry->Size /
530 sizeof(import_directory_table_entry) - 1;
532 // Find the section that contains the RVA. This is needed because the RVA is
533 // the import table's memory address which is different from its file offset.
534 uintptr_t IntPtr = 0;
535 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
537 ImportDirectory = reinterpret_cast<
538 const import_directory_table_entry *>(IntPtr);
539 return object_error::success;
542 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
543 std::error_code COFFObjectFile::initDelayImportTablePtr() {
544 const data_directory *DataEntry;
545 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
546 return object_error::success;
547 if (DataEntry->RelativeVirtualAddress == 0)
548 return object_error::success;
550 uint32_t RVA = DataEntry->RelativeVirtualAddress;
551 NumberOfDelayImportDirectory = DataEntry->Size /
552 sizeof(delay_import_directory_table_entry) - 1;
554 uintptr_t IntPtr = 0;
555 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
557 DelayImportDirectory = reinterpret_cast<
558 const delay_import_directory_table_entry *>(IntPtr);
559 return object_error::success;
562 // Find the export table.
563 std::error_code COFFObjectFile::initExportTablePtr() {
564 // First, we get the RVA of the export table. If the file lacks a pointer to
565 // the export table, do nothing.
566 const data_directory *DataEntry;
567 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
568 return object_error::success;
570 // Do nothing if the pointer to export table is NULL.
571 if (DataEntry->RelativeVirtualAddress == 0)
572 return object_error::success;
574 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
575 uintptr_t IntPtr = 0;
576 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
579 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
580 return object_error::success;
583 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
584 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
585 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
586 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
587 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
588 ImportDirectory(nullptr), NumberOfImportDirectory(0),
589 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
590 ExportDirectory(nullptr) {
591 // Check that we at least have enough room for a header.
592 if (!checkSize(Data, EC, sizeof(coff_file_header)))
595 // The current location in the file where we are looking at.
598 // PE header is optional and is present only in executables. If it exists,
599 // it is placed right after COFF header.
600 bool HasPEHeader = false;
602 // Check if this is a PE/COFF file.
603 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
604 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
605 // PE signature to find 'normal' COFF header.
606 const auto *DH = reinterpret_cast<const dos_header *>(base());
607 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
608 CurPtr = DH->AddressOfNewExeHeader;
609 // Check the PE magic bytes. ("PE\0\0")
610 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
611 EC = object_error::parse_failed;
614 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
619 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
622 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
623 // import libraries share a common prefix but bigobj is more restrictive.
624 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
625 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
626 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
627 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
630 // Verify that we are dealing with bigobj.
631 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
632 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
633 sizeof(COFF::BigObjMagic)) == 0) {
634 COFFHeader = nullptr;
635 CurPtr += sizeof(coff_bigobj_file_header);
637 // It's not a bigobj.
638 COFFBigObjHeader = nullptr;
642 // The prior checkSize call may have failed. This isn't a hard error
643 // because we were just trying to sniff out bigobj.
644 EC = object_error::success;
645 CurPtr += sizeof(coff_file_header);
647 if (COFFHeader->isImportLibrary())
652 const pe32_header *Header;
653 if ((EC = getObject(Header, Data, base() + CurPtr)))
656 const uint8_t *DataDirAddr;
657 uint64_t DataDirSize;
658 if (Header->Magic == COFF::PE32Header::PE32) {
660 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
661 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
662 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
663 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
664 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
665 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
667 // It's neither PE32 nor PE32+.
668 EC = object_error::parse_failed;
671 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
673 CurPtr += COFFHeader->SizeOfOptionalHeader;
676 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
677 getNumberOfSections() * sizeof(coff_section))))
680 // Initialize the pointer to the symbol table.
681 if (getPointerToSymbolTable() != 0)
682 if ((EC = initSymbolTablePtr()))
685 // Initialize the pointer to the beginning of the import table.
686 if ((EC = initImportTablePtr()))
688 if ((EC = initDelayImportTablePtr()))
691 // Initialize the pointer to the export table.
692 if ((EC = initExportTablePtr()))
695 EC = object_error::success;
698 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
700 Ret.p = getSymbolTable();
701 return basic_symbol_iterator(SymbolRef(Ret, this));
704 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
705 // The symbol table ends where the string table begins.
707 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
708 return basic_symbol_iterator(SymbolRef(Ret, this));
711 import_directory_iterator COFFObjectFile::import_directory_begin() const {
712 return import_directory_iterator(
713 ImportDirectoryEntryRef(ImportDirectory, 0, this));
716 import_directory_iterator COFFObjectFile::import_directory_end() const {
717 return import_directory_iterator(
718 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
721 delay_import_directory_iterator
722 COFFObjectFile::delay_import_directory_begin() const {
723 return delay_import_directory_iterator(
724 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
727 delay_import_directory_iterator
728 COFFObjectFile::delay_import_directory_end() const {
729 return delay_import_directory_iterator(
730 DelayImportDirectoryEntryRef(
731 DelayImportDirectory, NumberOfDelayImportDirectory, this));
734 export_directory_iterator COFFObjectFile::export_directory_begin() const {
735 return export_directory_iterator(
736 ExportDirectoryEntryRef(ExportDirectory, 0, this));
739 export_directory_iterator COFFObjectFile::export_directory_end() const {
740 if (!ExportDirectory)
741 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
742 ExportDirectoryEntryRef Ref(ExportDirectory,
743 ExportDirectory->AddressTableEntries, this);
744 return export_directory_iterator(Ref);
747 section_iterator COFFObjectFile::section_begin() const {
749 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
750 return section_iterator(SectionRef(Ret, this));
753 section_iterator COFFObjectFile::section_end() const {
756 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
757 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
758 return section_iterator(SectionRef(Ret, this));
761 uint8_t COFFObjectFile::getBytesInAddress() const {
762 return getArch() == Triple::x86_64 ? 8 : 4;
765 StringRef COFFObjectFile::getFileFormatName() const {
766 switch(getMachine()) {
767 case COFF::IMAGE_FILE_MACHINE_I386:
769 case COFF::IMAGE_FILE_MACHINE_AMD64:
770 return "COFF-x86-64";
771 case COFF::IMAGE_FILE_MACHINE_ARMNT:
774 return "COFF-<unknown arch>";
778 unsigned COFFObjectFile::getArch() const {
779 switch (getMachine()) {
780 case COFF::IMAGE_FILE_MACHINE_I386:
782 case COFF::IMAGE_FILE_MACHINE_AMD64:
783 return Triple::x86_64;
784 case COFF::IMAGE_FILE_MACHINE_ARMNT:
785 return Triple::thumb;
787 return Triple::UnknownArch;
791 iterator_range<import_directory_iterator>
792 COFFObjectFile::import_directories() const {
793 return make_range(import_directory_begin(), import_directory_end());
796 iterator_range<delay_import_directory_iterator>
797 COFFObjectFile::delay_import_directories() const {
798 return make_range(delay_import_directory_begin(),
799 delay_import_directory_end());
802 iterator_range<export_directory_iterator>
803 COFFObjectFile::export_directories() const {
804 return make_range(export_directory_begin(), export_directory_end());
807 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
809 return object_error::success;
813 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
814 Res = PE32PlusHeader;
815 return object_error::success;
819 COFFObjectFile::getDataDirectory(uint32_t Index,
820 const data_directory *&Res) const {
821 // Error if if there's no data directory or the index is out of range.
823 return object_error::parse_failed;
824 assert(PE32Header || PE32PlusHeader);
825 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
826 : PE32PlusHeader->NumberOfRvaAndSize;
828 return object_error::parse_failed;
829 Res = &DataDirectory[Index];
830 return object_error::success;
833 std::error_code COFFObjectFile::getSection(int32_t Index,
834 const coff_section *&Result) const {
835 // Check for special index values.
836 if (COFF::isReservedSectionNumber(Index))
838 else if (Index > 0 && static_cast<uint32_t>(Index) <= getNumberOfSections())
839 // We already verified the section table data, so no need to check again.
840 Result = SectionTable + (Index - 1);
842 return object_error::parse_failed;
843 return object_error::success;
846 std::error_code COFFObjectFile::getString(uint32_t Offset,
847 StringRef &Result) const {
848 if (StringTableSize <= 4)
849 // Tried to get a string from an empty string table.
850 return object_error::parse_failed;
851 if (Offset >= StringTableSize)
852 return object_error::unexpected_eof;
853 Result = StringRef(StringTable + Offset);
854 return object_error::success;
857 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
858 StringRef &Res) const {
859 // Check for string table entry. First 4 bytes are 0.
860 if (Symbol.getStringTableOffset().Zeroes == 0) {
861 uint32_t Offset = Symbol.getStringTableOffset().Offset;
862 if (std::error_code EC = getString(Offset, Res))
864 return object_error::success;
867 if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
868 // Null terminated, let ::strlen figure out the length.
869 Res = StringRef(Symbol.getShortName());
871 // Not null terminated, use all 8 bytes.
872 Res = StringRef(Symbol.getShortName(), COFF::NameSize);
873 return object_error::success;
877 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
878 const uint8_t *Aux = nullptr;
880 size_t SymbolSize = getSymbolTableEntrySize();
881 if (Symbol.getNumberOfAuxSymbols() > 0) {
882 // AUX data comes immediately after the symbol in COFF
883 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
885 // Verify that the Aux symbol points to a valid entry in the symbol table.
886 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
887 if (Offset < getPointerToSymbolTable() ||
889 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
890 report_fatal_error("Aux Symbol data was outside of symbol table.");
892 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
893 "Aux Symbol data did not point to the beginning of a symbol");
896 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
899 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
900 StringRef &Res) const {
902 if (Sec->Name[COFF::NameSize - 1] == 0)
903 // Null terminated, let ::strlen figure out the length.
906 // Not null terminated, use all 8 bytes.
907 Name = StringRef(Sec->Name, COFF::NameSize);
909 // Check for string table entry. First byte is '/'.
910 if (Name.startswith("/")) {
912 if (Name.startswith("//")) {
913 if (decodeBase64StringEntry(Name.substr(2), Offset))
914 return object_error::parse_failed;
916 if (Name.substr(1).getAsInteger(10, Offset))
917 return object_error::parse_failed;
919 if (std::error_code EC = getString(Offset, Name))
924 return object_error::success;
927 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
928 // SizeOfRawData and VirtualSize change what they represent depending on
929 // whether or not we have an executable image.
931 // For object files, SizeOfRawData contains the size of section's data;
932 // VirtualSize is always zero.
934 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
935 // actual section size is in VirtualSize. It is possible for VirtualSize to
936 // be greater than SizeOfRawData; the contents past that point should be
937 // considered to be zero.
938 uint32_t SectionSize;
939 if (Sec->VirtualSize)
940 SectionSize = std::min(Sec->VirtualSize, Sec->SizeOfRawData);
942 SectionSize = Sec->SizeOfRawData;
948 COFFObjectFile::getSectionContents(const coff_section *Sec,
949 ArrayRef<uint8_t> &Res) const {
950 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
951 // don't do anything interesting for them.
952 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
953 "BSS sections don't have contents!");
954 // The only thing that we need to verify is that the contents is contained
955 // within the file bounds. We don't need to make sure it doesn't cover other
956 // data, as there's nothing that says that is not allowed.
957 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
958 uint32_t SectionSize = getSectionSize(Sec);
959 uintptr_t ConEnd = ConStart + SectionSize;
960 if (ConEnd > uintptr_t(Data.getBufferEnd()))
961 return object_error::parse_failed;
962 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
963 return object_error::success;
966 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
967 return reinterpret_cast<const coff_relocation*>(Rel.p);
970 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
971 Rel.p = reinterpret_cast<uintptr_t>(
972 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
975 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
976 uint64_t &Res) const {
977 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
980 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
981 uint64_t &Res) const {
982 const coff_relocation *R = toRel(Rel);
983 const support::ulittle32_t *VirtualAddressPtr;
984 if (std::error_code EC =
985 getObject(VirtualAddressPtr, Data, &R->VirtualAddress))
987 Res = *VirtualAddressPtr;
988 return object_error::success;
991 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
992 const coff_relocation *R = toRel(Rel);
995 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
996 else if (SymbolTable32)
997 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
999 llvm_unreachable("no symbol table pointer!");
1000 return symbol_iterator(SymbolRef(Ref, this));
1003 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
1004 uint64_t &Res) const {
1005 const coff_relocation* R = toRel(Rel);
1007 return object_error::success;
1010 const coff_section *
1011 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1012 return toSec(Section.getRawDataRefImpl());
1015 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1017 return toSymb<coff_symbol16>(Ref);
1019 return toSymb<coff_symbol32>(Ref);
1020 llvm_unreachable("no symbol table pointer!");
1023 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1024 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1027 const coff_relocation *
1028 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1029 return toRel(Reloc.getRawDataRefImpl());
1032 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1033 case COFF::reloc_type: \
1034 Res = #reloc_type; \
1038 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
1039 SmallVectorImpl<char> &Result) const {
1040 const coff_relocation *Reloc = toRel(Rel);
1042 switch (getMachine()) {
1043 case COFF::IMAGE_FILE_MACHINE_AMD64:
1044 switch (Reloc->Type) {
1045 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1046 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1047 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1048 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1049 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1050 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1051 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1052 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1053 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1054 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1055 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1056 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1057 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1058 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1059 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1060 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1061 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1066 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1067 switch (Reloc->Type) {
1068 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1069 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1070 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1071 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1072 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1073 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1074 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1075 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1076 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1077 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1078 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1079 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1080 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1081 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1082 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1087 case COFF::IMAGE_FILE_MACHINE_I386:
1088 switch (Reloc->Type) {
1089 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1090 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1091 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1092 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1093 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1094 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1095 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1096 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1097 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1098 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1099 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1107 Result.append(Res.begin(), Res.end());
1108 return object_error::success;
1111 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1114 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
1115 SmallVectorImpl<char> &Result) const {
1116 const coff_relocation *Reloc = toRel(Rel);
1118 ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1119 if (std::error_code EC = Symb.getError())
1121 Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1123 if (std::error_code EC = getSymbolName(Sym, SymName))
1125 Result.append(SymName.begin(), SymName.end());
1126 return object_error::success;
1129 bool COFFObjectFile::isRelocatableObject() const {
1130 return !DataDirectory;
1133 bool ImportDirectoryEntryRef::
1134 operator==(const ImportDirectoryEntryRef &Other) const {
1135 return ImportTable == Other.ImportTable && Index == Other.Index;
1138 void ImportDirectoryEntryRef::moveNext() {
1142 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1143 const import_directory_table_entry *&Result) const {
1144 Result = ImportTable + Index;
1145 return object_error::success;
1148 static imported_symbol_iterator
1149 makeImportedSymbolIterator(const COFFObjectFile *Object,
1150 uintptr_t Ptr, int Index) {
1151 if (Object->getBytesInAddress() == 4) {
1152 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1153 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1155 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1156 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1159 static imported_symbol_iterator
1160 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1161 uintptr_t IntPtr = 0;
1162 Object->getRvaPtr(RVA, IntPtr);
1163 return makeImportedSymbolIterator(Object, IntPtr, 0);
1166 static imported_symbol_iterator
1167 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1168 uintptr_t IntPtr = 0;
1169 Object->getRvaPtr(RVA, IntPtr);
1170 // Forward the pointer to the last entry which is null.
1172 if (Object->getBytesInAddress() == 4) {
1173 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1177 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1181 return makeImportedSymbolIterator(Object, IntPtr, Index);
1184 imported_symbol_iterator
1185 ImportDirectoryEntryRef::imported_symbol_begin() const {
1186 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1190 imported_symbol_iterator
1191 ImportDirectoryEntryRef::imported_symbol_end() const {
1192 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1196 iterator_range<imported_symbol_iterator>
1197 ImportDirectoryEntryRef::imported_symbols() const {
1198 return make_range(imported_symbol_begin(), imported_symbol_end());
1201 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1202 uintptr_t IntPtr = 0;
1203 if (std::error_code EC =
1204 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1206 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1207 return object_error::success;
1211 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1212 Result = ImportTable[Index].ImportLookupTableRVA;
1213 return object_error::success;
1217 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1218 Result = ImportTable[Index].ImportAddressTableRVA;
1219 return object_error::success;
1222 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1223 const import_lookup_table_entry32 *&Result) const {
1224 uintptr_t IntPtr = 0;
1225 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1226 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1228 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1229 return object_error::success;
1232 bool DelayImportDirectoryEntryRef::
1233 operator==(const DelayImportDirectoryEntryRef &Other) const {
1234 return Table == Other.Table && Index == Other.Index;
1237 void DelayImportDirectoryEntryRef::moveNext() {
1241 imported_symbol_iterator
1242 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1243 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1247 imported_symbol_iterator
1248 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1249 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1253 iterator_range<imported_symbol_iterator>
1254 DelayImportDirectoryEntryRef::imported_symbols() const {
1255 return make_range(imported_symbol_begin(), imported_symbol_end());
1258 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1259 uintptr_t IntPtr = 0;
1260 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1262 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1263 return object_error::success;
1266 std::error_code DelayImportDirectoryEntryRef::
1267 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1269 return object_error::success;
1272 std::error_code DelayImportDirectoryEntryRef::
1273 getImportAddress(int AddrIndex, uint64_t &Result) const {
1274 uint32_t RVA = Table[Index].DelayImportAddressTable +
1275 AddrIndex * (OwningObject->is64() ? 8 : 4);
1276 uintptr_t IntPtr = 0;
1277 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1279 if (OwningObject->is64())
1280 Result = *reinterpret_cast<const uint64_t *>(IntPtr);
1282 Result = *reinterpret_cast<const uint32_t *>(IntPtr);
1283 return object_error::success;
1286 bool ExportDirectoryEntryRef::
1287 operator==(const ExportDirectoryEntryRef &Other) const {
1288 return ExportTable == Other.ExportTable && Index == Other.Index;
1291 void ExportDirectoryEntryRef::moveNext() {
1295 // Returns the name of the current export symbol. If the symbol is exported only
1296 // by ordinal, the empty string is set as a result.
1297 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1298 uintptr_t IntPtr = 0;
1299 if (std::error_code EC =
1300 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1302 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1303 return object_error::success;
1306 // Returns the starting ordinal number.
1308 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1309 Result = ExportTable->OrdinalBase;
1310 return object_error::success;
1313 // Returns the export ordinal of the current export symbol.
1314 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1315 Result = ExportTable->OrdinalBase + Index;
1316 return object_error::success;
1319 // Returns the address of the current export symbol.
1320 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1321 uintptr_t IntPtr = 0;
1322 if (std::error_code EC =
1323 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1325 const export_address_table_entry *entry =
1326 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1327 Result = entry[Index].ExportRVA;
1328 return object_error::success;
1331 // Returns the name of the current export symbol. If the symbol is exported only
1332 // by ordinal, the empty string is set as a result.
1334 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1335 uintptr_t IntPtr = 0;
1336 if (std::error_code EC =
1337 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1339 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1341 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1343 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1344 I < E; ++I, ++Offset) {
1347 if (std::error_code EC =
1348 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1350 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1351 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1353 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1354 return object_error::success;
1357 return object_error::success;
1360 bool ImportedSymbolRef::
1361 operator==(const ImportedSymbolRef &Other) const {
1362 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1363 && Index == Other.Index;
1366 void ImportedSymbolRef::moveNext() {
1371 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1374 // If a symbol is imported only by ordinal, it has no name.
1375 if (Entry32[Index].isOrdinal())
1376 return object_error::success;
1377 RVA = Entry32[Index].getHintNameRVA();
1379 if (Entry64[Index].isOrdinal())
1380 return object_error::success;
1381 RVA = Entry64[Index].getHintNameRVA();
1383 uintptr_t IntPtr = 0;
1384 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1386 // +2 because the first two bytes is hint.
1387 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1388 return object_error::success;
1391 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1394 if (Entry32[Index].isOrdinal()) {
1395 Result = Entry32[Index].getOrdinal();
1396 return object_error::success;
1398 RVA = Entry32[Index].getHintNameRVA();
1400 if (Entry64[Index].isOrdinal()) {
1401 Result = Entry64[Index].getOrdinal();
1402 return object_error::success;
1404 RVA = Entry64[Index].getHintNameRVA();
1406 uintptr_t IntPtr = 0;
1407 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1409 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1410 return object_error::success;
1413 ErrorOr<std::unique_ptr<COFFObjectFile>>
1414 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1416 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1419 return std::move(Ret);