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 return object_error::unexpected_eof;
53 Obj = reinterpret_cast<const T *>(Addr);
54 return object_error::success;
57 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
59 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
60 assert(Str.size() <= 6 && "String too long, possible overflow.");
65 while (!Str.empty()) {
67 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
68 CharVal = Str[0] - 'A';
69 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
70 CharVal = Str[0] - 'a' + 26;
71 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
72 CharVal = Str[0] - '0' + 52;
73 else if (Str[0] == '+') // 62
75 else if (Str[0] == '/') // 63
80 Value = (Value * 64) + CharVal;
84 if (Value > std::numeric_limits<uint32_t>::max())
87 Result = static_cast<uint32_t>(Value);
91 template <typename coff_symbol_type>
92 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
93 const coff_symbol_type *Addr =
94 reinterpret_cast<const coff_symbol_type *>(Ref.p);
97 // Verify that the symbol points to a valid entry in the symbol table.
98 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
99 if (Offset < getPointerToSymbolTable() ||
100 Offset >= getPointerToSymbolTable() +
101 (getNumberOfSymbols() * sizeof(coff_symbol_type)))
102 report_fatal_error("Symbol was outside of symbol table.");
104 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
105 "Symbol did not point to the beginning of a symbol");
111 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
112 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
115 // Verify that the section points to a valid entry in the section table.
116 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
117 report_fatal_error("Section was outside of section table.");
119 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
120 assert(Offset % sizeof(coff_section) == 0 &&
121 "Section did not point to the beginning of a section");
127 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
129 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
130 Symb += 1 + Symb->NumberOfAuxSymbols;
131 Ref.p = reinterpret_cast<uintptr_t>(Symb);
132 } else if (SymbolTable32) {
133 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
134 Symb += 1 + Symb->NumberOfAuxSymbols;
135 Ref.p = reinterpret_cast<uintptr_t>(Symb);
137 llvm_unreachable("no symbol table pointer!");
141 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
142 StringRef &Result) const {
143 COFFSymbolRef Symb = getCOFFSymbol(Ref);
144 return getSymbolName(Symb, Result);
147 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
148 uint64_t &Result) const {
149 COFFSymbolRef Symb = getCOFFSymbol(Ref);
151 if (Symb.isAnyUndefined()) {
152 Result = UnknownAddressOrSize;
153 return object_error::success;
155 if (Symb.isCommon()) {
156 Result = UnknownAddressOrSize;
157 return object_error::success;
159 int32_t SectionNumber = Symb.getSectionNumber();
160 if (!COFF::isReservedSectionNumber(SectionNumber)) {
161 const coff_section *Section = nullptr;
162 if (std::error_code EC = getSection(SectionNumber, Section))
165 Result = Section->VirtualAddress + Symb.getValue();
166 return object_error::success;
169 Result = Symb.getValue();
170 return object_error::success;
173 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
174 SymbolRef::Type &Result) const {
175 COFFSymbolRef Symb = getCOFFSymbol(Ref);
176 int32_t SectionNumber = Symb.getSectionNumber();
177 Result = SymbolRef::ST_Other;
179 if (Symb.isAnyUndefined()) {
180 Result = SymbolRef::ST_Unknown;
181 } else if (Symb.isFunctionDefinition()) {
182 Result = SymbolRef::ST_Function;
183 } else if (Symb.isCommon()) {
184 Result = SymbolRef::ST_Data;
185 } else if (Symb.isFileRecord()) {
186 Result = SymbolRef::ST_File;
187 } else if (SectionNumber == COFF::IMAGE_SYM_DEBUG) {
188 Result = SymbolRef::ST_Debug;
189 } else if (!COFF::isReservedSectionNumber(SectionNumber)) {
190 const coff_section *Section = nullptr;
191 if (std::error_code EC = getSection(SectionNumber, Section))
193 uint32_t Characteristics = Section->Characteristics;
194 if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
195 Result = SymbolRef::ST_Function;
196 else if (Characteristics & (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
197 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA))
198 Result = SymbolRef::ST_Data;
200 return object_error::success;
203 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
204 COFFSymbolRef Symb = getCOFFSymbol(Ref);
205 uint32_t Result = SymbolRef::SF_None;
207 if (Symb.isExternal() || Symb.isWeakExternal())
208 Result |= SymbolRef::SF_Global;
210 if (Symb.isWeakExternal())
211 Result |= SymbolRef::SF_Weak;
213 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
214 Result |= SymbolRef::SF_Absolute;
216 if (Symb.isFileRecord())
217 Result |= SymbolRef::SF_FormatSpecific;
219 if (Symb.isSectionDefinition())
220 Result |= SymbolRef::SF_FormatSpecific;
223 Result |= SymbolRef::SF_Common;
225 if (Symb.isAnyUndefined())
226 Result |= SymbolRef::SF_Undefined;
231 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
232 uint64_t &Result) const {
233 COFFSymbolRef Symb = getCOFFSymbol(Ref);
235 if (Symb.isAnyUndefined()) {
236 Result = UnknownAddressOrSize;
237 return object_error::success;
239 if (Symb.isCommon()) {
240 Result = Symb.getValue();
241 return object_error::success;
243 if (Symb.isFunctionDefinition()) {
244 ArrayRef<uint8_t> AuxData = getSymbolAuxData(Symb);
245 if (!AuxData.empty()) {
247 reinterpret_cast<const coff_aux_function_definition *>(
249 Result = CAFD->TotalSize;
250 return object_error::success;
253 // FIXME: Return the correct size. This requires looking at all the symbols
254 // in the same section as this symbol, and looking for either the next
255 // symbol, or the end of the section.
256 int32_t SectionNumber = Symb.getSectionNumber();
257 if (!COFF::isReservedSectionNumber(SectionNumber)) {
258 const coff_section *Section = nullptr;
259 if (std::error_code EC = getSection(SectionNumber, Section))
262 Result = Section->SizeOfRawData - Symb.getValue();
263 return object_error::success;
267 return object_error::success;
271 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
272 section_iterator &Result) const {
273 COFFSymbolRef Symb = getCOFFSymbol(Ref);
274 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
275 Result = section_end();
277 const coff_section *Sec = nullptr;
278 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
281 Ref.p = reinterpret_cast<uintptr_t>(Sec);
282 Result = section_iterator(SectionRef(Ref, this));
284 return object_error::success;
287 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
288 const coff_section *Sec = toSec(Ref);
290 Ref.p = reinterpret_cast<uintptr_t>(Sec);
293 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
294 StringRef &Result) const {
295 const coff_section *Sec = toSec(Ref);
296 return getSectionName(Sec, Result);
299 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
300 const coff_section *Sec = toSec(Ref);
301 return Sec->VirtualAddress;
304 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
305 return getSectionSize(toSec(Ref));
308 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
309 StringRef &Result) const {
310 const coff_section *Sec = toSec(Ref);
311 ArrayRef<uint8_t> Res;
312 std::error_code EC = getSectionContents(Sec, Res);
313 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
317 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
318 const coff_section *Sec = toSec(Ref);
319 return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
322 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
323 const coff_section *Sec = toSec(Ref);
324 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
327 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
328 const coff_section *Sec = toSec(Ref);
329 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
332 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
333 const coff_section *Sec = toSec(Ref);
334 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
337 bool COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref) const {
338 // FIXME: Unimplemented
342 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
343 const coff_section *Sec = toSec(Ref);
344 return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
347 bool COFFObjectFile::isSectionZeroInit(DataRefImpl Ref) const {
348 // FIXME: Unimplemented.
352 bool COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref) const {
353 // FIXME: Unimplemented.
357 bool COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
358 DataRefImpl SymbRef) const {
359 const coff_section *Sec = toSec(SecRef);
360 COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
361 int32_t SecNumber = (Sec - SectionTable) + 1;
362 return SecNumber == Symb.getSectionNumber();
365 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
366 const coff_section *Sec = toSec(Ref);
368 if (Sec->NumberOfRelocations == 0) {
371 auto begin = reinterpret_cast<const coff_relocation*>(
372 base() + Sec->PointerToRelocations);
373 if (Sec->hasExtendedRelocations()) {
374 // Skip the first relocation entry repurposed to store the number of
378 Ret.p = reinterpret_cast<uintptr_t>(begin);
380 return relocation_iterator(RelocationRef(Ret, this));
383 static uint32_t getNumberOfRelocations(const coff_section *Sec,
384 const uint8_t *base) {
385 // The field for the number of relocations in COFF section table is only
386 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
387 // NumberOfRelocations field, and the actual relocation count is stored in the
388 // VirtualAddress field in the first relocation entry.
389 if (Sec->hasExtendedRelocations()) {
390 auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
391 base + Sec->PointerToRelocations);
392 return FirstReloc->VirtualAddress;
394 return Sec->NumberOfRelocations;
397 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
398 const coff_section *Sec = toSec(Ref);
400 if (Sec->NumberOfRelocations == 0) {
403 auto begin = reinterpret_cast<const coff_relocation*>(
404 base() + Sec->PointerToRelocations);
405 uint32_t NumReloc = getNumberOfRelocations(Sec, base());
406 Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
408 return relocation_iterator(RelocationRef(Ret, this));
411 // Initialize the pointer to the symbol table.
412 std::error_code COFFObjectFile::initSymbolTablePtr() {
414 if (std::error_code EC =
415 getObject(SymbolTable16, Data, base() + getPointerToSymbolTable(),
416 getNumberOfSymbols() * getSymbolTableEntrySize()))
419 if (COFFBigObjHeader)
420 if (std::error_code EC =
421 getObject(SymbolTable32, Data, base() + getPointerToSymbolTable(),
422 getNumberOfSymbols() * getSymbolTableEntrySize()))
425 // Find string table. The first four byte of the string table contains the
426 // total size of the string table, including the size field itself. If the
427 // string table is empty, the value of the first four byte would be 4.
428 const uint8_t *StringTableAddr =
429 base() + getPointerToSymbolTable() +
430 getNumberOfSymbols() * getSymbolTableEntrySize();
431 const ulittle32_t *StringTableSizePtr;
432 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
434 StringTableSize = *StringTableSizePtr;
435 if (std::error_code EC =
436 getObject(StringTable, Data, StringTableAddr, StringTableSize))
439 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
440 // tools like cvtres write a size of 0 for an empty table instead of 4.
441 if (StringTableSize < 4)
444 // Check that the string table is null terminated if has any in it.
445 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
446 return object_error::parse_failed;
447 return object_error::success;
450 // Returns the file offset for the given VA.
451 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
452 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
453 : (uint64_t)PE32PlusHeader->ImageBase;
454 uint64_t Rva = Addr - ImageBase;
455 assert(Rva <= UINT32_MAX);
456 return getRvaPtr((uint32_t)Rva, Res);
459 // Returns the file offset for the given RVA.
460 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
461 for (const SectionRef &S : sections()) {
462 const coff_section *Section = getCOFFSection(S);
463 uint32_t SectionStart = Section->VirtualAddress;
464 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
465 if (SectionStart <= Addr && Addr < SectionEnd) {
466 uint32_t Offset = Addr - SectionStart;
467 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
468 return object_error::success;
471 return object_error::parse_failed;
474 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
476 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
477 StringRef &Name) const {
478 uintptr_t IntPtr = 0;
479 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
481 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
482 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
483 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
484 return object_error::success;
487 // Find the import table.
488 std::error_code COFFObjectFile::initImportTablePtr() {
489 // First, we get the RVA of the import table. If the file lacks a pointer to
490 // the import table, do nothing.
491 const data_directory *DataEntry;
492 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
493 return object_error::success;
495 // Do nothing if the pointer to import table is NULL.
496 if (DataEntry->RelativeVirtualAddress == 0)
497 return object_error::success;
499 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
500 // -1 because the last entry is the null entry.
501 NumberOfImportDirectory = DataEntry->Size /
502 sizeof(import_directory_table_entry) - 1;
504 // Find the section that contains the RVA. This is needed because the RVA is
505 // the import table's memory address which is different from its file offset.
506 uintptr_t IntPtr = 0;
507 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
509 ImportDirectory = reinterpret_cast<
510 const import_directory_table_entry *>(IntPtr);
511 return object_error::success;
514 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
515 std::error_code COFFObjectFile::initDelayImportTablePtr() {
516 const data_directory *DataEntry;
517 if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
518 return object_error::success;
519 if (DataEntry->RelativeVirtualAddress == 0)
520 return object_error::success;
522 uint32_t RVA = DataEntry->RelativeVirtualAddress;
523 NumberOfDelayImportDirectory = DataEntry->Size /
524 sizeof(delay_import_directory_table_entry) - 1;
526 uintptr_t IntPtr = 0;
527 if (std::error_code EC = getRvaPtr(RVA, IntPtr))
529 DelayImportDirectory = reinterpret_cast<
530 const delay_import_directory_table_entry *>(IntPtr);
531 return object_error::success;
534 // Find the export table.
535 std::error_code COFFObjectFile::initExportTablePtr() {
536 // First, we get the RVA of the export table. If the file lacks a pointer to
537 // the export table, do nothing.
538 const data_directory *DataEntry;
539 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
540 return object_error::success;
542 // Do nothing if the pointer to export table is NULL.
543 if (DataEntry->RelativeVirtualAddress == 0)
544 return object_error::success;
546 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
547 uintptr_t IntPtr = 0;
548 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
551 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
552 return object_error::success;
555 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
556 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
557 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
558 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
559 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
560 ImportDirectory(nullptr), NumberOfImportDirectory(0),
561 DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
562 ExportDirectory(nullptr) {
563 // Check that we at least have enough room for a header.
564 if (!checkSize(Data, EC, sizeof(coff_file_header)))
567 // The current location in the file where we are looking at.
570 // PE header is optional and is present only in executables. If it exists,
571 // it is placed right after COFF header.
572 bool HasPEHeader = false;
574 // Check if this is a PE/COFF file.
575 if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
576 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
577 // PE signature to find 'normal' COFF header.
578 const auto *DH = reinterpret_cast<const dos_header *>(base());
579 if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
580 CurPtr = DH->AddressOfNewExeHeader;
581 // Check the PE magic bytes. ("PE\0\0")
582 if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
583 EC = object_error::parse_failed;
586 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
591 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
594 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
595 // import libraries share a common prefix but bigobj is more restrictive.
596 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
597 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
598 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
599 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
602 // Verify that we are dealing with bigobj.
603 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
604 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
605 sizeof(COFF::BigObjMagic)) == 0) {
606 COFFHeader = nullptr;
607 CurPtr += sizeof(coff_bigobj_file_header);
609 // It's not a bigobj.
610 COFFBigObjHeader = nullptr;
614 // The prior checkSize call may have failed. This isn't a hard error
615 // because we were just trying to sniff out bigobj.
616 EC = object_error::success;
617 CurPtr += sizeof(coff_file_header);
619 if (COFFHeader->isImportLibrary())
624 const pe32_header *Header;
625 if ((EC = getObject(Header, Data, base() + CurPtr)))
628 const uint8_t *DataDirAddr;
629 uint64_t DataDirSize;
630 if (Header->Magic == COFF::PE32Header::PE32) {
632 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
633 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
634 } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
635 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
636 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
637 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
639 // It's neither PE32 nor PE32+.
640 EC = object_error::parse_failed;
643 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
645 CurPtr += COFFHeader->SizeOfOptionalHeader;
648 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
649 getNumberOfSections() * sizeof(coff_section))))
652 // Initialize the pointer to the symbol table.
653 if (getPointerToSymbolTable() != 0)
654 if ((EC = initSymbolTablePtr()))
657 // Initialize the pointer to the beginning of the import table.
658 if ((EC = initImportTablePtr()))
660 if ((EC = initDelayImportTablePtr()))
663 // Initialize the pointer to the export table.
664 if ((EC = initExportTablePtr()))
667 EC = object_error::success;
670 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
672 Ret.p = getSymbolTable();
673 return basic_symbol_iterator(SymbolRef(Ret, this));
676 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
677 // The symbol table ends where the string table begins.
679 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
680 return basic_symbol_iterator(SymbolRef(Ret, this));
683 import_directory_iterator COFFObjectFile::import_directory_begin() const {
684 return import_directory_iterator(
685 ImportDirectoryEntryRef(ImportDirectory, 0, this));
688 import_directory_iterator COFFObjectFile::import_directory_end() const {
689 return import_directory_iterator(
690 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
693 delay_import_directory_iterator
694 COFFObjectFile::delay_import_directory_begin() const {
695 return delay_import_directory_iterator(
696 DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
699 delay_import_directory_iterator
700 COFFObjectFile::delay_import_directory_end() const {
701 return delay_import_directory_iterator(
702 DelayImportDirectoryEntryRef(
703 DelayImportDirectory, NumberOfDelayImportDirectory, this));
706 export_directory_iterator COFFObjectFile::export_directory_begin() const {
707 return export_directory_iterator(
708 ExportDirectoryEntryRef(ExportDirectory, 0, this));
711 export_directory_iterator COFFObjectFile::export_directory_end() const {
712 if (!ExportDirectory)
713 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
714 ExportDirectoryEntryRef Ref(ExportDirectory,
715 ExportDirectory->AddressTableEntries, this);
716 return export_directory_iterator(Ref);
719 section_iterator COFFObjectFile::section_begin() const {
721 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
722 return section_iterator(SectionRef(Ret, this));
725 section_iterator COFFObjectFile::section_end() const {
728 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
729 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
730 return section_iterator(SectionRef(Ret, this));
733 uint8_t COFFObjectFile::getBytesInAddress() const {
734 return getArch() == Triple::x86_64 ? 8 : 4;
737 StringRef COFFObjectFile::getFileFormatName() const {
738 switch(getMachine()) {
739 case COFF::IMAGE_FILE_MACHINE_I386:
741 case COFF::IMAGE_FILE_MACHINE_AMD64:
742 return "COFF-x86-64";
743 case COFF::IMAGE_FILE_MACHINE_ARMNT:
746 return "COFF-<unknown arch>";
750 unsigned COFFObjectFile::getArch() const {
751 switch (getMachine()) {
752 case COFF::IMAGE_FILE_MACHINE_I386:
754 case COFF::IMAGE_FILE_MACHINE_AMD64:
755 return Triple::x86_64;
756 case COFF::IMAGE_FILE_MACHINE_ARMNT:
757 return Triple::thumb;
759 return Triple::UnknownArch;
763 iterator_range<import_directory_iterator>
764 COFFObjectFile::import_directories() const {
765 return make_range(import_directory_begin(), import_directory_end());
768 iterator_range<delay_import_directory_iterator>
769 COFFObjectFile::delay_import_directories() const {
770 return make_range(delay_import_directory_begin(),
771 delay_import_directory_end());
774 iterator_range<export_directory_iterator>
775 COFFObjectFile::export_directories() const {
776 return make_range(export_directory_begin(), export_directory_end());
779 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
781 return object_error::success;
785 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
786 Res = PE32PlusHeader;
787 return object_error::success;
791 COFFObjectFile::getDataDirectory(uint32_t Index,
792 const data_directory *&Res) const {
793 // Error if if there's no data directory or the index is out of range.
795 return object_error::parse_failed;
796 assert(PE32Header || PE32PlusHeader);
797 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
798 : PE32PlusHeader->NumberOfRvaAndSize;
800 return object_error::parse_failed;
801 Res = &DataDirectory[Index];
802 return object_error::success;
805 std::error_code COFFObjectFile::getSection(int32_t Index,
806 const coff_section *&Result) const {
807 // Check for special index values.
808 if (COFF::isReservedSectionNumber(Index))
810 else if (Index > 0 && static_cast<uint32_t>(Index) <= getNumberOfSections())
811 // We already verified the section table data, so no need to check again.
812 Result = SectionTable + (Index - 1);
814 return object_error::parse_failed;
815 return object_error::success;
818 std::error_code COFFObjectFile::getString(uint32_t Offset,
819 StringRef &Result) const {
820 if (StringTableSize <= 4)
821 // Tried to get a string from an empty string table.
822 return object_error::parse_failed;
823 if (Offset >= StringTableSize)
824 return object_error::unexpected_eof;
825 Result = StringRef(StringTable + Offset);
826 return object_error::success;
829 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
830 StringRef &Res) const {
831 // Check for string table entry. First 4 bytes are 0.
832 if (Symbol.getStringTableOffset().Zeroes == 0) {
833 uint32_t Offset = Symbol.getStringTableOffset().Offset;
834 if (std::error_code EC = getString(Offset, Res))
836 return object_error::success;
839 if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
840 // Null terminated, let ::strlen figure out the length.
841 Res = StringRef(Symbol.getShortName());
843 // Not null terminated, use all 8 bytes.
844 Res = StringRef(Symbol.getShortName(), COFF::NameSize);
845 return object_error::success;
849 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
850 const uint8_t *Aux = nullptr;
852 size_t SymbolSize = getSymbolTableEntrySize();
853 if (Symbol.getNumberOfAuxSymbols() > 0) {
854 // AUX data comes immediately after the symbol in COFF
855 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
857 // Verify that the Aux symbol points to a valid entry in the symbol table.
858 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
859 if (Offset < getPointerToSymbolTable() ||
861 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
862 report_fatal_error("Aux Symbol data was outside of symbol table.");
864 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
865 "Aux Symbol data did not point to the beginning of a symbol");
868 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
871 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
872 StringRef &Res) const {
874 if (Sec->Name[COFF::NameSize - 1] == 0)
875 // Null terminated, let ::strlen figure out the length.
878 // Not null terminated, use all 8 bytes.
879 Name = StringRef(Sec->Name, COFF::NameSize);
881 // Check for string table entry. First byte is '/'.
882 if (Name[0] == '/') {
884 if (Name[1] == '/') {
885 if (decodeBase64StringEntry(Name.substr(2), Offset))
886 return object_error::parse_failed;
888 if (Name.substr(1).getAsInteger(10, Offset))
889 return object_error::parse_failed;
891 if (std::error_code EC = getString(Offset, Name))
896 return object_error::success;
899 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
900 // SizeOfRawData and VirtualSize change what they represent depending on
901 // whether or not we have an executable image.
903 // For object files, SizeOfRawData contains the size of section's data;
904 // VirtualSize is always zero.
906 // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
907 // actual section size is in VirtualSize. It is possible for VirtualSize to
908 // be greater than SizeOfRawData; the contents past that point should be
909 // considered to be zero.
910 uint32_t SectionSize;
911 if (Sec->VirtualSize)
912 SectionSize = std::min(Sec->VirtualSize, Sec->SizeOfRawData);
914 SectionSize = Sec->SizeOfRawData;
920 COFFObjectFile::getSectionContents(const coff_section *Sec,
921 ArrayRef<uint8_t> &Res) const {
922 // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
923 // don't do anything interesting for them.
924 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
925 "BSS sections don't have contents!");
926 // The only thing that we need to verify is that the contents is contained
927 // within the file bounds. We don't need to make sure it doesn't cover other
928 // data, as there's nothing that says that is not allowed.
929 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
930 uint32_t SectionSize = getSectionSize(Sec);
931 uintptr_t ConEnd = ConStart + SectionSize;
932 if (ConEnd > uintptr_t(Data.getBufferEnd()))
933 return object_error::parse_failed;
934 Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
935 return object_error::success;
938 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
939 return reinterpret_cast<const coff_relocation*>(Rel.p);
942 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
943 Rel.p = reinterpret_cast<uintptr_t>(
944 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
947 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
948 uint64_t &Res) const {
949 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
952 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
953 uint64_t &Res) const {
954 Res = toRel(Rel)->VirtualAddress;
955 return object_error::success;
958 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
959 const coff_relocation *R = toRel(Rel);
962 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
963 else if (SymbolTable32)
964 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
966 llvm_unreachable("no symbol table pointer!");
967 return symbol_iterator(SymbolRef(Ref, this));
970 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
971 uint64_t &Res) const {
972 const coff_relocation* R = toRel(Rel);
974 return object_error::success;
978 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
979 return toSec(Section.getRawDataRefImpl());
982 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
984 return toSymb<coff_symbol16>(Ref);
986 return toSymb<coff_symbol32>(Ref);
987 llvm_unreachable("no symbol table pointer!");
990 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
991 return getCOFFSymbol(Symbol.getRawDataRefImpl());
994 const coff_relocation *
995 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
996 return toRel(Reloc.getRawDataRefImpl());
999 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
1000 case COFF::reloc_type: \
1001 Res = #reloc_type; \
1005 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
1006 SmallVectorImpl<char> &Result) const {
1007 const coff_relocation *Reloc = toRel(Rel);
1009 switch (getMachine()) {
1010 case COFF::IMAGE_FILE_MACHINE_AMD64:
1011 switch (Reloc->Type) {
1012 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1013 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1014 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1015 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1016 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1017 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1018 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1019 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1020 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1021 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1022 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1023 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1024 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1025 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1026 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1027 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1028 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1033 case COFF::IMAGE_FILE_MACHINE_ARMNT:
1034 switch (Reloc->Type) {
1035 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1036 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1037 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1038 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1039 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1040 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1041 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1042 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1043 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1044 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1045 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1046 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1047 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1048 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1049 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1054 case COFF::IMAGE_FILE_MACHINE_I386:
1055 switch (Reloc->Type) {
1056 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1057 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1058 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1059 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1060 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1061 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1062 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1063 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1064 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1065 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1066 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1074 Result.append(Res.begin(), Res.end());
1075 return object_error::success;
1078 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1081 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
1082 SmallVectorImpl<char> &Result) const {
1083 const coff_relocation *Reloc = toRel(Rel);
1085 ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1086 if (std::error_code EC = Symb.getError())
1088 Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1090 if (std::error_code EC = getSymbolName(Sym, SymName))
1092 Result.append(SymName.begin(), SymName.end());
1093 return object_error::success;
1096 bool COFFObjectFile::isRelocatableObject() const {
1097 return !DataDirectory;
1100 bool ImportDirectoryEntryRef::
1101 operator==(const ImportDirectoryEntryRef &Other) const {
1102 return ImportTable == Other.ImportTable && Index == Other.Index;
1105 void ImportDirectoryEntryRef::moveNext() {
1109 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1110 const import_directory_table_entry *&Result) const {
1111 Result = ImportTable + Index;
1112 return object_error::success;
1115 static imported_symbol_iterator
1116 makeImportedSymbolIterator(const COFFObjectFile *Object,
1117 uintptr_t Ptr, int Index) {
1118 if (Object->getBytesInAddress() == 4) {
1119 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1120 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1122 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1123 return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1126 static imported_symbol_iterator
1127 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1128 uintptr_t IntPtr = 0;
1129 Object->getRvaPtr(RVA, IntPtr);
1130 return makeImportedSymbolIterator(Object, IntPtr, 0);
1133 static imported_symbol_iterator
1134 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1135 uintptr_t IntPtr = 0;
1136 Object->getRvaPtr(RVA, IntPtr);
1137 // Forward the pointer to the last entry which is null.
1139 if (Object->getBytesInAddress() == 4) {
1140 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1144 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1148 return makeImportedSymbolIterator(Object, IntPtr, Index);
1151 imported_symbol_iterator
1152 ImportDirectoryEntryRef::imported_symbol_begin() const {
1153 return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1157 imported_symbol_iterator
1158 ImportDirectoryEntryRef::imported_symbol_end() const {
1159 return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1163 iterator_range<imported_symbol_iterator>
1164 ImportDirectoryEntryRef::imported_symbols() const {
1165 return make_range(imported_symbol_begin(), imported_symbol_end());
1168 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1169 uintptr_t IntPtr = 0;
1170 if (std::error_code EC =
1171 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1173 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1174 return object_error::success;
1178 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1179 Result = ImportTable[Index].ImportLookupTableRVA;
1180 return object_error::success;
1184 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1185 Result = ImportTable[Index].ImportAddressTableRVA;
1186 return object_error::success;
1189 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1190 const import_lookup_table_entry32 *&Result) const {
1191 uintptr_t IntPtr = 0;
1192 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1193 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1195 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1196 return object_error::success;
1199 bool DelayImportDirectoryEntryRef::
1200 operator==(const DelayImportDirectoryEntryRef &Other) const {
1201 return Table == Other.Table && Index == Other.Index;
1204 void DelayImportDirectoryEntryRef::moveNext() {
1208 imported_symbol_iterator
1209 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1210 return importedSymbolBegin(Table[Index].DelayImportNameTable,
1214 imported_symbol_iterator
1215 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1216 return importedSymbolEnd(Table[Index].DelayImportNameTable,
1220 iterator_range<imported_symbol_iterator>
1221 DelayImportDirectoryEntryRef::imported_symbols() const {
1222 return make_range(imported_symbol_begin(), imported_symbol_end());
1225 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1226 uintptr_t IntPtr = 0;
1227 if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1229 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1230 return object_error::success;
1233 std::error_code DelayImportDirectoryEntryRef::
1234 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1236 return object_error::success;
1239 bool ExportDirectoryEntryRef::
1240 operator==(const ExportDirectoryEntryRef &Other) const {
1241 return ExportTable == Other.ExportTable && Index == Other.Index;
1244 void ExportDirectoryEntryRef::moveNext() {
1248 // Returns the name of the current export symbol. If the symbol is exported only
1249 // by ordinal, the empty string is set as a result.
1250 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1251 uintptr_t IntPtr = 0;
1252 if (std::error_code EC =
1253 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1255 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1256 return object_error::success;
1259 // Returns the starting ordinal number.
1261 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1262 Result = ExportTable->OrdinalBase;
1263 return object_error::success;
1266 // Returns the export ordinal of the current export symbol.
1267 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1268 Result = ExportTable->OrdinalBase + Index;
1269 return object_error::success;
1272 // Returns the address of the current export symbol.
1273 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1274 uintptr_t IntPtr = 0;
1275 if (std::error_code EC =
1276 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1278 const export_address_table_entry *entry =
1279 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1280 Result = entry[Index].ExportRVA;
1281 return object_error::success;
1284 // Returns the name of the current export symbol. If the symbol is exported only
1285 // by ordinal, the empty string is set as a result.
1287 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1288 uintptr_t IntPtr = 0;
1289 if (std::error_code EC =
1290 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1292 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1294 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1296 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1297 I < E; ++I, ++Offset) {
1300 if (std::error_code EC =
1301 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1303 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1304 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1306 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1307 return object_error::success;
1310 return object_error::success;
1313 bool ImportedSymbolRef::
1314 operator==(const ImportedSymbolRef &Other) const {
1315 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1316 && Index == Other.Index;
1319 void ImportedSymbolRef::moveNext() {
1324 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1327 // If a symbol is imported only by ordinal, it has no name.
1328 if (Entry32[Index].isOrdinal())
1329 return object_error::success;
1330 RVA = Entry32[Index].getHintNameRVA();
1332 if (Entry64[Index].isOrdinal())
1333 return object_error::success;
1334 RVA = Entry64[Index].getHintNameRVA();
1336 uintptr_t IntPtr = 0;
1337 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1339 // +2 because the first two bytes is hint.
1340 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1341 return object_error::success;
1344 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1347 if (Entry32[Index].isOrdinal()) {
1348 Result = Entry32[Index].getOrdinal();
1349 return object_error::success;
1351 RVA = Entry32[Index].getHintNameRVA();
1353 if (Entry64[Index].isOrdinal()) {
1354 Result = Entry64[Index].getOrdinal();
1355 return object_error::success;
1357 RVA = Entry64[Index].getHintNameRVA();
1359 uintptr_t IntPtr = 0;
1360 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1362 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1363 return object_error::success;
1366 ErrorOr<std::unique_ptr<COFFObjectFile>>
1367 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1369 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1372 return std::move(Ret);