1 //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the COFFObjectFile class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Object/COFF.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Support/COFF.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
26 using namespace object;
28 using support::ulittle16_t;
29 using support::ulittle32_t;
30 using support::ulittle64_t;
31 using support::little16_t;
33 // Returns false if size is greater than the buffer size. And sets ec.
34 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
35 if (M.getBufferSize() < Size) {
36 EC = object_error::unexpected_eof;
42 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
43 const uint64_t Size) {
44 if (Addr + Size < Addr || Addr + Size < Size ||
45 Addr + Size > uintptr_t(M.getBufferEnd()) ||
46 Addr < uintptr_t(M.getBufferStart())) {
47 return object_error::unexpected_eof;
49 return object_error::success;
52 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
53 // Returns unexpected_eof if error.
55 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
57 const uint64_t Size = sizeof(T)) {
58 uintptr_t Addr = uintptr_t(Ptr);
59 if (std::error_code EC = checkOffset(M, Addr, Size))
61 Obj = reinterpret_cast<const T *>(Addr);
62 return object_error::success;
65 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
67 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
68 assert(Str.size() <= 6 && "String too long, possible overflow.");
73 while (!Str.empty()) {
75 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
76 CharVal = Str[0] - 'A';
77 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
78 CharVal = Str[0] - 'a' + 26;
79 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
80 CharVal = Str[0] - '0' + 52;
81 else if (Str[0] == '+') // 62
83 else if (Str[0] == '/') // 63
88 Value = (Value * 64) + CharVal;
92 if (Value > std::numeric_limits<uint32_t>::max())
95 Result = static_cast<uint32_t>(Value);
99 template <typename coff_symbol_type>
100 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
101 const coff_symbol_type *Addr =
102 reinterpret_cast<const coff_symbol_type *>(Ref.p);
104 assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
106 // Verify that the symbol points to a valid entry in the symbol table.
107 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
109 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
110 "Symbol did not point to the beginning of a symbol");
116 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
117 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
120 // Verify that the section points to a valid entry in the section table.
121 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
122 report_fatal_error("Section was outside of section table.");
124 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
125 assert(Offset % sizeof(coff_section) == 0 &&
126 "Section did not point to the beginning of a section");
132 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
133 auto End = reinterpret_cast<uintptr_t>(StringTable);
135 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
136 Symb += 1 + Symb->NumberOfAuxSymbols;
137 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
138 } else if (SymbolTable32) {
139 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
140 Symb += 1 + Symb->NumberOfAuxSymbols;
141 Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
143 llvm_unreachable("no symbol table pointer!");
147 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
148 StringRef &Result) const {
149 COFFSymbolRef Symb = getCOFFSymbol(Ref);
150 return getSymbolName(Symb, Result);
153 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
154 uint64_t &Result) const {
155 COFFSymbolRef Symb = getCOFFSymbol(Ref);
157 if (Symb.isAnyUndefined()) {
158 Result = UnknownAddressOrSize;
159 return object_error::success;
161 if (Symb.isCommon()) {
162 Result = UnknownAddressOrSize;
163 return object_error::success;
165 int32_t SectionNumber = Symb.getSectionNumber();
166 if (!COFF::isReservedSectionNumber(SectionNumber)) {
167 const coff_section *Section = nullptr;
168 if (std::error_code EC = getSection(SectionNumber, Section))
171 Result = Section->VirtualAddress + Symb.getValue();
172 return object_error::success;
175 Result = Symb.getValue();
176 return object_error::success;
179 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
180 SymbolRef::Type &Result) const {
181 COFFSymbolRef Symb = getCOFFSymbol(Ref);
182 int32_t SectionNumber = Symb.getSectionNumber();
183 Result = SymbolRef::ST_Other;
185 if (Symb.isAnyUndefined()) {
186 Result = SymbolRef::ST_Unknown;
187 } else if (Symb.isFunctionDefinition()) {
188 Result = SymbolRef::ST_Function;
189 } else if (Symb.isCommon()) {
190 Result = SymbolRef::ST_Data;
191 } else if (Symb.isFileRecord()) {
192 Result = SymbolRef::ST_File;
193 } else if (SectionNumber == COFF::IMAGE_SYM_DEBUG) {
194 Result = SymbolRef::ST_Debug;
195 } else if (!COFF::isReservedSectionNumber(SectionNumber)) {
196 const coff_section *Section = nullptr;
197 if (std::error_code EC = getSection(SectionNumber, Section))
199 uint32_t Characteristics = Section->Characteristics;
200 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
201 Result = SymbolRef::ST_Function;
202 else if (Characteristics & (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
203 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA))
204 Result = SymbolRef::ST_Data;
206 return object_error::success;
209 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
210 COFFSymbolRef Symb = getCOFFSymbol(Ref);
211 uint32_t Result = SymbolRef::SF_None;
213 if (Symb.isExternal() || Symb.isWeakExternal())
214 Result |= SymbolRef::SF_Global;
216 if (Symb.isWeakExternal())
217 Result |= SymbolRef::SF_Weak;
219 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
220 Result |= SymbolRef::SF_Absolute;
222 if (Symb.isFileRecord())
223 Result |= SymbolRef::SF_FormatSpecific;
225 if (Symb.isSectionDefinition())
226 Result |= SymbolRef::SF_FormatSpecific;
229 Result |= SymbolRef::SF_Common;
231 if (Symb.isAnyUndefined())
232 Result |= SymbolRef::SF_Undefined;
237 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
238 uint64_t &Result) const {
239 COFFSymbolRef Symb = getCOFFSymbol(Ref);
241 if (Symb.isAnyUndefined()) {
242 Result = UnknownAddressOrSize;
243 return object_error::success;
245 if (Symb.isCommon()) {
246 Result = Symb.getValue();
247 return object_error::success;
250 // Let's attempt to get the size of the symbol by looking at the address of
251 // the symbol after the symbol in question.
253 if (std::error_code EC = getSymbolAddress(Ref, SymbAddr))
255 int32_t SectionNumber = Symb.getSectionNumber();
256 if (COFF::isReservedSectionNumber(SectionNumber)) {
257 // Absolute and debug symbols aren't sorted in any interesting way.
259 return object_error::success;
261 const section_iterator SecEnd = section_end();
262 uint64_t AfterAddr = UnknownAddressOrSize;
263 for (const symbol_iterator &SymbI : symbols()) {
264 section_iterator SecI = SecEnd;
265 if (std::error_code EC = SymbI->getSection(SecI))
267 // Check the symbol's section, skip it if it's in the wrong section.
268 // First, make sure it is in any section.
271 // Second, make sure it is in the same section as the symbol in question.
272 if (!sectionContainsSymbol(SecI->getRawDataRefImpl(), Ref))
275 if (std::error_code EC = SymbI->getAddress(Addr))
277 // We want to compare our symbol in question with the closest possible
278 // symbol that comes after.
279 if (AfterAddr > Addr && Addr > SymbAddr)
282 if (AfterAddr == UnknownAddressOrSize) {
283 // No symbol comes after this one, assume that everything after our symbol
285 const coff_section *Section = nullptr;
286 if (std::error_code EC = getSection(SectionNumber, Section))
288 Result = Section->SizeOfRawData - Symb.getValue();
290 // Take the difference between our symbol and the symbol that comes after
292 Result = AfterAddr - SymbAddr;
295 return object_error::success;
299 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
300 section_iterator &Result) const {
301 COFFSymbolRef Symb = getCOFFSymbol(Ref);
302 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
303 Result = section_end();
305 const coff_section *Sec = nullptr;
306 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
309 Ref.p = reinterpret_cast<uintptr_t>(Sec);
310 Result = section_iterator(SectionRef(Ref, this));
312 return object_error::success;
315 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
316 const coff_section *Sec = toSec(Ref);
318 Ref.p = reinterpret_cast<uintptr_t>(Sec);
321 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
322 StringRef &Result) const {
323 const coff_section *Sec = toSec(Ref);
324 return getSectionName(Sec, Result);
327 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
328 const coff_section *Sec = toSec(Ref);
329 return Sec->VirtualAddress;
332 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
333 return getSectionSize(toSec(Ref));
336 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
337 StringRef &Result) const {
338 const coff_section *Sec = toSec(Ref);
339 ArrayRef<uint8_t> Res;
340 std::error_code EC = getSectionContents(Sec, Res);
341 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
345 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
346 const coff_section *Sec = toSec(Ref);
347 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
350 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
351 const coff_section *Sec = toSec(Ref);
352 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
355 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
356 const coff_section *Sec = toSec(Ref);
357 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
360 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
361 const coff_section *Sec = toSec(Ref);
362 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
365 bool COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref) const {
366 // Sections marked 'Info', 'Remove', or 'Discardable' aren't required for
368 const coff_section *Sec = toSec(Ref);
369 return !(Sec->Characteristics &
370 (COFF::IMAGE_SCN_LNK_INFO | COFF::IMAGE_SCN_LNK_REMOVE |
371 COFF::IMAGE_SCN_MEM_DISCARDABLE));
374 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
375 const coff_section *Sec = toSec(Ref);
376 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
379 bool COFFObjectFile::isSectionZeroInit(DataRefImpl Ref) const {
380 const coff_section *Sec = toSec(Ref);
381 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
384 bool COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref) const {
385 const coff_section *Sec = toSec(Ref);
386 // Check if it's any sort of data section.
387 if (!(Sec->Characteristics & (COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
388 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)))
390 // If it's writable or executable or contains code, it isn't read-only data.
391 if (Sec->Characteristics &
392 (COFF::IMAGE_SCN_CNT_CODE | COFF::IMAGE_SCN_MEM_EXECUTE |
393 COFF::IMAGE_SCN_MEM_WRITE))
398 bool COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
399 DataRefImpl SymbRef) const {
400 const coff_section *Sec = toSec(SecRef);
401 COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
402 int32_t SecNumber = (Sec - SectionTable) + 1;
403 return SecNumber == Symb.getSectionNumber();
406 static uint32_t getNumberOfRelocations(const coff_section *Sec,
407 MemoryBufferRef M, const uint8_t *base) {
408 // The field for the number of relocations in COFF section table is only
409 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
410 // NumberOfRelocations field, and the actual relocation count is stored in the
411 // VirtualAddress field in the first relocation entry.
412 if (Sec->hasExtendedRelocations()) {
413 const coff_relocation *FirstReloc;
414 if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
415 base + Sec->PointerToRelocations)))
417 return FirstReloc->VirtualAddress;
419 return Sec->NumberOfRelocations;
422 static const coff_relocation *
423 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
424 uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
427 auto begin = reinterpret_cast<const coff_relocation *>(
428 Base + Sec->PointerToRelocations);
429 if (Sec->hasExtendedRelocations()) {
430 // Skip the first relocation entry repurposed to store the number of
434 if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
439 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
440 const coff_section *Sec = toSec(Ref);
441 const coff_relocation *begin = getFirstReloc(Sec, Data, base());
443 Ret.p = reinterpret_cast<uintptr_t>(begin);
444 return relocation_iterator(RelocationRef(Ret, this));
447 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
448 const coff_section *Sec = toSec(Ref);
449 const coff_relocation *I = getFirstReloc(Sec, Data, base());
451 I += getNumberOfRelocations(Sec, Data, base());
453 Ret.p = reinterpret_cast<uintptr_t>(I);
454 return relocation_iterator(RelocationRef(Ret, this));
457 // Initialize the pointer to the symbol table.
458 std::error_code COFFObjectFile::initSymbolTablePtr() {
460 if (std::error_code EC = getObject(
461 SymbolTable16, Data, base() + getPointerToSymbolTable(),
462 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
465 if (COFFBigObjHeader)
466 if (std::error_code EC = getObject(
467 SymbolTable32, Data, base() + getPointerToSymbolTable(),
468 (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
471 // Find string table. The first four byte of the string table contains the
472 // total size of the string table, including the size field itself. If the
473 // string table is empty, the value of the first four byte would be 4.
474 uint32_t StringTableOffset = getPointerToSymbolTable() +
475 getNumberOfSymbols() * getSymbolTableEntrySize();
476 const uint8_t *StringTableAddr = base() + StringTableOffset;
477 const ulittle32_t *StringTableSizePtr;
478 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
480 StringTableSize = *StringTableSizePtr;
481 if (std::error_code EC =
482 getObject(StringTable, Data, StringTableAddr, StringTableSize))
485 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
486 // tools like cvtres write a size of 0 for an empty table instead of 4.
487 if (StringTableSize < 4)
490 // Check that the string table is null terminated if has any in it.
491 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
492 return object_error::parse_failed;
493 return object_error::success;
496 // Returns the file offset for the given VA.
497 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
498 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
499 : (uint64_t)PE32PlusHeader->ImageBase;
500 uint64_t Rva = Addr - ImageBase;
501 assert(Rva <= UINT32_MAX);
502 return getRvaPtr((uint32_t)Rva, Res);
505 // Returns the file offset for the given RVA.
506 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
507 for (const SectionRef &S : sections()) {
508 const coff_section *Section = getCOFFSection(S);
509 uint32_t SectionStart = Section->VirtualAddress;
510 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
511 if (SectionStart <= Addr && Addr < SectionEnd) {
512 uint32_t Offset = Addr - SectionStart;
513 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
514 return object_error::success;
517 return object_error::parse_failed;
520 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
522 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
523 StringRef &Name) const {
524 uintptr_t IntPtr = 0;
525 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
527 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
528 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
529 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
530 return object_error::success;
533 // Find the import table.
534 std::error_code COFFObjectFile::initImportTablePtr() {
535 // First, we get the RVA of the import table. If the file lacks a pointer to
536 // the import table, do nothing.
537 const data_directory *DataEntry;
538 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
539 return object_error::success;
541 // Do nothing if the pointer to import table is NULL.
542 if (DataEntry->RelativeVirtualAddress == 0)
543 return object_error::success;
545 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
546 // -1 because the last entry is the null entry.
547 NumberOfImportDirectory = DataEntry->Size /
548 sizeof(import_directory_table_entry) - 1;
550 // Find the section that contains the RVA. This is needed because the RVA is
551 // the import table's memory address which is different from its file offset.
552 uintptr_t IntPtr = 0;
553 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
555 ImportDirectory = reinterpret_cast<
556 const import_directory_table_entry *>(IntPtr);
557 return object_error::success;
560 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
561 std::error_code COFFObjectFile::initDelayImportTablePtr() {
562 const data_directory *DataEntry;
563 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
564 return object_error::success;
565 if (DataEntry->RelativeVirtualAddress == 0)
566 return object_error::success;
568 uint32_t RVA = DataEntry->RelativeVirtualAddress;
569 NumberOfDelayImportDirectory = DataEntry->Size /
570 sizeof(delay_import_directory_table_entry) - 1;
572 uintptr_t IntPtr = 0;
573 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
575 DelayImportDirectory = reinterpret_cast<
576 const delay_import_directory_table_entry *>(IntPtr);
577 return object_error::success;
580 // Find the export table.
581 std::error_code COFFObjectFile::initExportTablePtr() {
582 // First, we get the RVA of the export table. If the file lacks a pointer to
583 // the export table, do nothing.
584 const data_directory *DataEntry;
585 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
586 return object_error::success;
588 // Do nothing if the pointer to export table is NULL.
589 if (DataEntry->RelativeVirtualAddress == 0)
590 return object_error::success;
592 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
593 uintptr_t IntPtr = 0;
594 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
597 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
598 return object_error::success;
601 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
602 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
603 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
604 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
605 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
606 ImportDirectory(nullptr), NumberOfImportDirectory(0),
607 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
608 ExportDirectory(nullptr) {
609 // Check that we at least have enough room for a header.
610 if (!checkSize(Data, EC, sizeof(coff_file_header)))
613 // The current location in the file where we are looking at.
616 // PE header is optional and is present only in executables. If it exists,
617 // it is placed right after COFF header.
618 bool HasPEHeader = false;
620 // Check if this is a PE/COFF file.
621 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
622 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
623 // PE signature to find 'normal' COFF header.
624 const auto *DH = reinterpret_cast<const dos_header *>(base());
625 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
626 CurPtr = DH->AddressOfNewExeHeader;
627 // Check the PE magic bytes. ("PE\0\0")
628 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
629 EC = object_error::parse_failed;
632 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
637 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
640 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
641 // import libraries share a common prefix but bigobj is more restrictive.
642 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
643 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
644 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
645 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
648 // Verify that we are dealing with bigobj.
649 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
650 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
651 sizeof(COFF::BigObjMagic)) == 0) {
652 COFFHeader = nullptr;
653 CurPtr += sizeof(coff_bigobj_file_header);
655 // It's not a bigobj.
656 COFFBigObjHeader = nullptr;
660 // The prior checkSize call may have failed. This isn't a hard error
661 // because we were just trying to sniff out bigobj.
662 EC = object_error::success;
663 CurPtr += sizeof(coff_file_header);
665 if (COFFHeader->isImportLibrary())
670 const pe32_header *Header;
671 if ((EC = getObject(Header, Data, base() + CurPtr)))
674 const uint8_t *DataDirAddr;
675 uint64_t DataDirSize;
676 if (Header->Magic == COFF::PE32Header::PE32) {
678 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
679 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
680 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
681 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
682 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
683 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
685 // It's neither PE32 nor PE32+.
686 EC = object_error::parse_failed;
689 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
691 CurPtr += COFFHeader->SizeOfOptionalHeader;
694 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
695 (uint64_t)getNumberOfSections() * sizeof(coff_section))))
698 // Initialize the pointer to the symbol table.
699 if (getPointerToSymbolTable() != 0) {
700 if ((EC = initSymbolTablePtr()))
703 // We had better not have any symbols if we don't have a symbol table.
704 if (getNumberOfSymbols() != 0) {
705 EC = object_error::parse_failed;
710 // Initialize the pointer to the beginning of the import table.
711 if ((EC = initImportTablePtr()))
713 if ((EC = initDelayImportTablePtr()))
716 // Initialize the pointer to the export table.
717 if ((EC = initExportTablePtr()))
720 EC = object_error::success;
723 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
725 Ret.p = getSymbolTable();
726 return basic_symbol_iterator(SymbolRef(Ret, this));
729 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
730 // The symbol table ends where the string table begins.
732 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
733 return basic_symbol_iterator(SymbolRef(Ret, this));
736 import_directory_iterator COFFObjectFile::import_directory_begin() const {
737 return import_directory_iterator(
738 ImportDirectoryEntryRef(ImportDirectory, 0, this));
741 import_directory_iterator COFFObjectFile::import_directory_end() const {
742 return import_directory_iterator(
743 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
746 delay_import_directory_iterator
747 COFFObjectFile::delay_import_directory_begin() const {
748 return delay_import_directory_iterator(
749 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
752 delay_import_directory_iterator
753 COFFObjectFile::delay_import_directory_end() const {
754 return delay_import_directory_iterator(
755 DelayImportDirectoryEntryRef(
756 DelayImportDirectory, NumberOfDelayImportDirectory, this));
759 export_directory_iterator COFFObjectFile::export_directory_begin() const {
760 return export_directory_iterator(
761 ExportDirectoryEntryRef(ExportDirectory, 0, this));
764 export_directory_iterator COFFObjectFile::export_directory_end() const {
765 if (!ExportDirectory)
766 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
767 ExportDirectoryEntryRef Ref(ExportDirectory,
768 ExportDirectory->AddressTableEntries, this);
769 return export_directory_iterator(Ref);
772 section_iterator COFFObjectFile::section_begin() const {
774 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
775 return section_iterator(SectionRef(Ret, this));
778 section_iterator COFFObjectFile::section_end() const {
781 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
782 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
783 return section_iterator(SectionRef(Ret, this));
786 uint8_t COFFObjectFile::getBytesInAddress() const {
787 return getArch() == Triple::x86_64 ? 8 : 4;
790 StringRef COFFObjectFile::getFileFormatName() const {
791 switch(getMachine()) {
792 case COFF::IMAGE_FILE_MACHINE_I386:
794 case COFF::IMAGE_FILE_MACHINE_AMD64:
795 return "COFF-x86-64";
796 case COFF::IMAGE_FILE_MACHINE_ARMNT:
799 return "COFF-<unknown arch>";
803 unsigned COFFObjectFile::getArch() const {
804 switch (getMachine()) {
805 case COFF::IMAGE_FILE_MACHINE_I386:
807 case COFF::IMAGE_FILE_MACHINE_AMD64:
808 return Triple::x86_64;
809 case COFF::IMAGE_FILE_MACHINE_ARMNT:
810 return Triple::thumb;
812 return Triple::UnknownArch;
816 iterator_range<import_directory_iterator>
817 COFFObjectFile::import_directories() const {
818 return make_range(import_directory_begin(), import_directory_end());
821 iterator_range<delay_import_directory_iterator>
822 COFFObjectFile::delay_import_directories() const {
823 return make_range(delay_import_directory_begin(),
824 delay_import_directory_end());
827 iterator_range<export_directory_iterator>
828 COFFObjectFile::export_directories() const {
829 return make_range(export_directory_begin(), export_directory_end());
832 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
834 return object_error::success;
838 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
839 Res = PE32PlusHeader;
840 return object_error::success;
844 COFFObjectFile::getDataDirectory(uint32_t Index,
845 const data_directory *&Res) const {
846 // Error if if there's no data directory or the index is out of range.
847 if (!DataDirectory) {
849 return object_error::parse_failed;
851 assert(PE32Header || PE32PlusHeader);
852 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
853 : PE32PlusHeader->NumberOfRvaAndSize;
854 if (Index >= NumEnt) {
856 return object_error::parse_failed;
858 Res = &DataDirectory[Index];
859 return object_error::success;
862 std::error_code COFFObjectFile::getSection(int32_t Index,
863 const coff_section *&Result) const {
865 if (COFF::isReservedSectionNumber(Index))
866 return object_error::success;
867 if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
868 // We already verified the section table data, so no need to check again.
869 Result = SectionTable + (Index - 1);
870 return object_error::success;
872 return object_error::parse_failed;
875 std::error_code COFFObjectFile::getString(uint32_t Offset,
876 StringRef &Result) const {
877 if (StringTableSize <= 4)
878 // Tried to get a string from an empty string table.
879 return object_error::parse_failed;
880 if (Offset >= StringTableSize)
881 return object_error::unexpected_eof;
882 Result = StringRef(StringTable + Offset);
883 return object_error::success;
886 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
887 StringRef &Res) const {
888 // Check for string table entry. First 4 bytes are 0.
889 if (Symbol.getStringTableOffset().Zeroes == 0) {
890 uint32_t Offset = Symbol.getStringTableOffset().Offset;
891 if (std::error_code EC = getString(Offset, Res))
893 return object_error::success;
896 if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
897 // Null terminated, let ::strlen figure out the length.
898 Res = StringRef(Symbol.getShortName());
900 // Not null terminated, use all 8 bytes.
901 Res = StringRef(Symbol.getShortName(), COFF::NameSize);
902 return object_error::success;
906 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
907 const uint8_t *Aux = nullptr;
909 size_t SymbolSize = getSymbolTableEntrySize();
910 if (Symbol.getNumberOfAuxSymbols() > 0) {
911 // AUX data comes immediately after the symbol in COFF
912 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
914 // Verify that the Aux symbol points to a valid entry in the symbol table.
915 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
916 if (Offset < getPointerToSymbolTable() ||
918 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
919 report_fatal_error("Aux Symbol data was outside of symbol table.");
921 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
922 "Aux Symbol data did not point to the beginning of a symbol");
925 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
928 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
929 StringRef &Res) const {
931 if (Sec->Name[COFF::NameSize - 1] == 0)
932 // Null terminated, let ::strlen figure out the length.
935 // Not null terminated, use all 8 bytes.
936 Name = StringRef(Sec->Name, COFF::NameSize);
938 // Check for string table entry. First byte is '/'.
939 if (Name.startswith("/")) {
941 if (Name.startswith("//")) {
942 if (decodeBase64StringEntry(Name.substr(2), Offset))
943 return object_error::parse_failed;
945 if (Name.substr(1).getAsInteger(10, Offset))
946 return object_error::parse_failed;
948 if (std::error_code EC = getString(Offset, Name))
953 return object_error::success;
956 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
957 // SizeOfRawData and VirtualSize change what they represent depending on
958 // whether or not we have an executable image.
960 // For object files, SizeOfRawData contains the size of section's data;
961 // VirtualSize is always zero.
963 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
964 // actual section size is in VirtualSize. It is possible for VirtualSize to
965 // be greater than SizeOfRawData; the contents past that point should be
966 // considered to be zero.
967 uint32_t SectionSize;
968 if (Sec->VirtualSize)
969 SectionSize = std::min(Sec->VirtualSize, Sec->SizeOfRawData);
971 SectionSize = Sec->SizeOfRawData;
977 COFFObjectFile::getSectionContents(const coff_section *Sec,
978 ArrayRef<uint8_t> &Res) const {
979 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
980 // don't do anything interesting for them.
981 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
982 "BSS sections don't have contents!");
983 // The only thing that we need to verify is that the contents is contained
984 // within the file bounds. We don't need to make sure it doesn't cover other
985 // data, as there's nothing that says that is not allowed.
986 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
987 uint32_t SectionSize = getSectionSize(Sec);
988 if (checkOffset(Data, ConStart, SectionSize))
989 return object_error::parse_failed;
990 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
991 return object_error::success;
994 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
995 return reinterpret_cast<const coff_relocation*>(Rel.p);
998 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
999 Rel.p = reinterpret_cast<uintptr_t>(
1000 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1003 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
1004 uint64_t &Res) const {
1005 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
1008 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
1009 uint64_t &Res) const {
1010 const coff_relocation *R = toRel(Rel);
1011 const support::ulittle32_t *VirtualAddressPtr;
1012 if (std::error_code EC =
1013 getObject(VirtualAddressPtr, Data, &R->VirtualAddress))
1015 Res = *VirtualAddressPtr;
1016 return object_error::success;
1019 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1020 const coff_relocation *R = toRel(Rel);
1022 if (R->SymbolTableIndex >= getNumberOfSymbols())
1023 return symbol_end();
1025 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1026 else if (SymbolTable32)
1027 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1029 return symbol_end();
1030 return symbol_iterator(SymbolRef(Ref, this));
1033 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
1034 uint64_t &Res) const {
1035 const coff_relocation* R = toRel(Rel);
1037 return object_error::success;
1040 const coff_section *
1041 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1042 return toSec(Section.getRawDataRefImpl());
1045 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1047 return toSymb<coff_symbol16>(Ref);
1049 return toSymb<coff_symbol32>(Ref);
1050 llvm_unreachable("no symbol table pointer!");
1053 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1054 return getCOFFSymbol(Symbol.getRawDataRefImpl());
1057 const coff_relocation *
1058 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1059 return toRel(Reloc.getRawDataRefImpl());
1062 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1063 case COFF::reloc_type: \
1064 Res = #reloc_type; \
1068 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
1069 SmallVectorImpl<char> &Result) const {
1070 const coff_relocation *Reloc = toRel(Rel);
1072 switch (getMachine()) {
1073 case COFF::IMAGE_FILE_MACHINE_AMD64:
1074 switch (Reloc->Type) {
1075 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1076 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1077 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1078 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1079 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1080 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1081 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1082 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1083 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1084 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1085 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1086 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1087 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1088 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1089 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1090 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1091 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1096 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1097 switch (Reloc->Type) {
1098 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1099 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1100 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1101 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1102 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1103 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1104 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1105 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1106 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1107 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1108 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1109 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1110 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1111 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1112 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1117 case COFF::IMAGE_FILE_MACHINE_I386:
1118 switch (Reloc->Type) {
1119 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1120 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1121 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1122 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1123 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1124 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1125 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1126 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1127 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1128 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1129 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1137 Result.append(Res.begin(), Res.end());
1138 return object_error::success;
1141 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1144 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
1145 SmallVectorImpl<char> &Result) const {
1146 const coff_relocation *Reloc = toRel(Rel);
1148 ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1149 if (std::error_code EC = Symb.getError())
1151 Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1153 if (std::error_code EC = getSymbolName(Sym, SymName))
1155 Result.append(SymName.begin(), SymName.end());
1156 return object_error::success;
1159 bool COFFObjectFile::isRelocatableObject() const {
1160 return !DataDirectory;
1163 bool ImportDirectoryEntryRef::
1164 operator==(const ImportDirectoryEntryRef &Other) const {
1165 return ImportTable == Other.ImportTable && Index == Other.Index;
1168 void ImportDirectoryEntryRef::moveNext() {
1172 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1173 const import_directory_table_entry *&Result) const {
1174 Result = ImportTable + Index;
1175 return object_error::success;
1178 static imported_symbol_iterator
1179 makeImportedSymbolIterator(const COFFObjectFile *Object,
1180 uintptr_t Ptr, int Index) {
1181 if (Object->getBytesInAddress() == 4) {
1182 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1183 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1185 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1186 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1189 static imported_symbol_iterator
1190 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1191 uintptr_t IntPtr = 0;
1192 Object->getRvaPtr(RVA, IntPtr);
1193 return makeImportedSymbolIterator(Object, IntPtr, 0);
1196 static imported_symbol_iterator
1197 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1198 uintptr_t IntPtr = 0;
1199 Object->getRvaPtr(RVA, IntPtr);
1200 // Forward the pointer to the last entry which is null.
1202 if (Object->getBytesInAddress() == 4) {
1203 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1207 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1211 return makeImportedSymbolIterator(Object, IntPtr, Index);
1214 imported_symbol_iterator
1215 ImportDirectoryEntryRef::imported_symbol_begin() const {
1216 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1220 imported_symbol_iterator
1221 ImportDirectoryEntryRef::imported_symbol_end() const {
1222 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1226 iterator_range<imported_symbol_iterator>
1227 ImportDirectoryEntryRef::imported_symbols() const {
1228 return make_range(imported_symbol_begin(), imported_symbol_end());
1231 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1232 uintptr_t IntPtr = 0;
1233 if (std::error_code EC =
1234 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1236 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1237 return object_error::success;
1241 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1242 Result = ImportTable[Index].ImportLookupTableRVA;
1243 return object_error::success;
1247 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1248 Result = ImportTable[Index].ImportAddressTableRVA;
1249 return object_error::success;
1252 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1253 const import_lookup_table_entry32 *&Result) const {
1254 uintptr_t IntPtr = 0;
1255 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1256 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1258 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1259 return object_error::success;
1262 bool DelayImportDirectoryEntryRef::
1263 operator==(const DelayImportDirectoryEntryRef &Other) const {
1264 return Table == Other.Table && Index == Other.Index;
1267 void DelayImportDirectoryEntryRef::moveNext() {
1271 imported_symbol_iterator
1272 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1273 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1277 imported_symbol_iterator
1278 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1279 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1283 iterator_range<imported_symbol_iterator>
1284 DelayImportDirectoryEntryRef::imported_symbols() const {
1285 return make_range(imported_symbol_begin(), imported_symbol_end());
1288 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1289 uintptr_t IntPtr = 0;
1290 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1292 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1293 return object_error::success;
1296 std::error_code DelayImportDirectoryEntryRef::
1297 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1299 return object_error::success;
1302 std::error_code DelayImportDirectoryEntryRef::
1303 getImportAddress(int AddrIndex, uint64_t &Result) const {
1304 uint32_t RVA = Table[Index].DelayImportAddressTable +
1305 AddrIndex * (OwningObject->is64() ? 8 : 4);
1306 uintptr_t IntPtr = 0;
1307 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1309 if (OwningObject->is64())
1310 Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1312 Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1313 return object_error::success;
1316 bool ExportDirectoryEntryRef::
1317 operator==(const ExportDirectoryEntryRef &Other) const {
1318 return ExportTable == Other.ExportTable && Index == Other.Index;
1321 void ExportDirectoryEntryRef::moveNext() {
1325 // Returns the name of the current export symbol. If the symbol is exported only
1326 // by ordinal, the empty string is set as a result.
1327 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1328 uintptr_t IntPtr = 0;
1329 if (std::error_code EC =
1330 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1332 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1333 return object_error::success;
1336 // Returns the starting ordinal number.
1338 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1339 Result = ExportTable->OrdinalBase;
1340 return object_error::success;
1343 // Returns the export ordinal of the current export symbol.
1344 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1345 Result = ExportTable->OrdinalBase + Index;
1346 return object_error::success;
1349 // Returns the address of the current export symbol.
1350 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1351 uintptr_t IntPtr = 0;
1352 if (std::error_code EC =
1353 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1355 const export_address_table_entry *entry =
1356 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1357 Result = entry[Index].ExportRVA;
1358 return object_error::success;
1361 // Returns the name of the current export symbol. If the symbol is exported only
1362 // by ordinal, the empty string is set as a result.
1364 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1365 uintptr_t IntPtr = 0;
1366 if (std::error_code EC =
1367 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1369 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1371 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1373 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1374 I < E; ++I, ++Offset) {
1377 if (std::error_code EC =
1378 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1380 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1381 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1383 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1384 return object_error::success;
1387 return object_error::success;
1390 bool ImportedSymbolRef::
1391 operator==(const ImportedSymbolRef &Other) const {
1392 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1393 && Index == Other.Index;
1396 void ImportedSymbolRef::moveNext() {
1401 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1404 // If a symbol is imported only by ordinal, it has no name.
1405 if (Entry32[Index].isOrdinal())
1406 return object_error::success;
1407 RVA = Entry32[Index].getHintNameRVA();
1409 if (Entry64[Index].isOrdinal())
1410 return object_error::success;
1411 RVA = Entry64[Index].getHintNameRVA();
1413 uintptr_t IntPtr = 0;
1414 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1416 // +2 because the first two bytes is hint.
1417 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1418 return object_error::success;
1421 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1424 if (Entry32[Index].isOrdinal()) {
1425 Result = Entry32[Index].getOrdinal();
1426 return object_error::success;
1428 RVA = Entry32[Index].getHintNameRVA();
1430 if (Entry64[Index].isOrdinal()) {
1431 Result = Entry64[Index].getOrdinal();
1432 return object_error::success;
1434 RVA = Entry64[Index].getHintNameRVA();
1436 uintptr_t IntPtr = 0;
1437 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1439 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1440 return object_error::success;
1443 ErrorOr<std::unique_ptr<COFFObjectFile>>
1444 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1446 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1449 return std::move(Ret);