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);
150 const coff_section *Section = nullptr;
151 if (std::error_code EC = getSection(Symb.getSectionNumber(), Section))
154 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED)
155 Result = UnknownAddressOrSize;
157 Result = Section->VirtualAddress + Symb.getValue();
159 Result = Symb.getValue();
160 return object_error::success;
163 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
164 SymbolRef::Type &Result) const {
165 COFFSymbolRef Symb = getCOFFSymbol(Ref);
166 Result = SymbolRef::ST_Other;
168 if (Symb.getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
169 Symb.getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED) {
170 Result = SymbolRef::ST_Unknown;
171 } else if (Symb.isFunctionDefinition()) {
172 Result = SymbolRef::ST_Function;
174 uint32_t Characteristics = 0;
175 if (!COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
176 const coff_section *Section = nullptr;
177 if (std::error_code EC = getSection(Symb.getSectionNumber(), Section))
179 Characteristics = Section->Characteristics;
181 if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
182 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
183 Result = SymbolRef::ST_Data;
185 return object_error::success;
188 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
189 COFFSymbolRef Symb = getCOFFSymbol(Ref);
190 uint32_t Result = SymbolRef::SF_None;
192 // TODO: Correctly set SF_FormatSpecific, SF_Common
194 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED) {
195 if (Symb.getValue() == 0)
196 Result |= SymbolRef::SF_Undefined;
198 Result |= SymbolRef::SF_Common;
202 // TODO: This are certainly too restrictive.
203 if (Symb.getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL)
204 Result |= SymbolRef::SF_Global;
206 if (Symb.getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
207 Result |= SymbolRef::SF_Weak;
209 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
210 Result |= SymbolRef::SF_Absolute;
215 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
216 uint64_t &Result) const {
217 // FIXME: Return the correct size. This requires looking at all the symbols
218 // in the same section as this symbol, and looking for either the next
219 // symbol, or the end of the section.
220 COFFSymbolRef Symb = getCOFFSymbol(Ref);
221 const coff_section *Section = nullptr;
222 if (std::error_code EC = getSection(Symb.getSectionNumber(), Section))
225 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED)
226 Result = UnknownAddressOrSize;
228 Result = Section->SizeOfRawData - Symb.getValue();
231 return object_error::success;
235 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
236 section_iterator &Result) const {
237 COFFSymbolRef Symb = getCOFFSymbol(Ref);
238 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
239 Result = section_end();
241 const coff_section *Sec = nullptr;
242 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
245 Ref.p = reinterpret_cast<uintptr_t>(Sec);
246 Result = section_iterator(SectionRef(Ref, this));
248 return object_error::success;
251 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
252 const coff_section *Sec = toSec(Ref);
254 Ref.p = reinterpret_cast<uintptr_t>(Sec);
257 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
258 StringRef &Result) const {
259 const coff_section *Sec = toSec(Ref);
260 return getSectionName(Sec, Result);
263 std::error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
264 uint64_t &Result) const {
265 const coff_section *Sec = toSec(Ref);
266 Result = Sec->VirtualAddress;
267 return object_error::success;
270 std::error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
271 uint64_t &Result) const {
272 const coff_section *Sec = toSec(Ref);
273 Result = Sec->SizeOfRawData;
274 return object_error::success;
277 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
278 StringRef &Result) const {
279 const coff_section *Sec = toSec(Ref);
280 ArrayRef<uint8_t> Res;
281 std::error_code EC = getSectionContents(Sec, Res);
282 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
286 std::error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
287 uint64_t &Res) const {
288 const coff_section *Sec = toSec(Ref);
290 return object_error::parse_failed;
291 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
292 return object_error::success;
295 std::error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
296 bool &Result) const {
297 const coff_section *Sec = toSec(Ref);
298 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
299 return object_error::success;
302 std::error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
303 bool &Result) const {
304 const coff_section *Sec = toSec(Ref);
305 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
306 return object_error::success;
309 std::error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
310 bool &Result) const {
311 const coff_section *Sec = toSec(Ref);
312 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
313 return object_error::success;
317 COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
318 bool &Result) const {
319 // FIXME: Unimplemented
321 return object_error::success;
324 std::error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
325 bool &Result) const {
326 const coff_section *Sec = toSec(Ref);
327 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
328 return object_error::success;
331 std::error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
332 bool &Result) const {
333 // FIXME: Unimplemented.
335 return object_error::success;
338 std::error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
339 bool &Result) const {
340 // FIXME: Unimplemented.
342 return object_error::success;
345 std::error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
347 bool &Result) const {
348 const coff_section *Sec = toSec(SecRef);
349 COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
350 const coff_section *SymbSec = nullptr;
351 if (std::error_code EC = getSection(Symb.getSectionNumber(), SymbSec))
357 return object_error::success;
360 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
361 const coff_section *Sec = toSec(Ref);
363 if (Sec->NumberOfRelocations == 0) {
366 auto begin = reinterpret_cast<const coff_relocation*>(
367 base() + Sec->PointerToRelocations);
368 if (Sec->hasExtendedRelocations()) {
369 // Skip the first relocation entry repurposed to store the number of
373 Ret.p = reinterpret_cast<uintptr_t>(begin);
375 return relocation_iterator(RelocationRef(Ret, this));
378 static uint32_t getNumberOfRelocations(const coff_section *Sec,
379 const uint8_t *base) {
380 // The field for the number of relocations in COFF section table is only
381 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
382 // NumberOfRelocations field, and the actual relocation count is stored in the
383 // VirtualAddress field in the first relocation entry.
384 if (Sec->hasExtendedRelocations()) {
385 auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
386 base + Sec->PointerToRelocations);
387 return FirstReloc->VirtualAddress;
389 return Sec->NumberOfRelocations;
392 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
393 const coff_section *Sec = toSec(Ref);
395 if (Sec->NumberOfRelocations == 0) {
398 auto begin = reinterpret_cast<const coff_relocation*>(
399 base() + Sec->PointerToRelocations);
400 uint32_t NumReloc = getNumberOfRelocations(Sec, base());
401 Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
403 return relocation_iterator(RelocationRef(Ret, this));
406 // Initialize the pointer to the symbol table.
407 std::error_code COFFObjectFile::initSymbolTablePtr() {
409 if (std::error_code EC =
410 getObject(SymbolTable16, Data, base() + getPointerToSymbolTable(),
411 getNumberOfSymbols() * getSymbolTableEntrySize()))
414 if (COFFBigObjHeader)
415 if (std::error_code EC =
416 getObject(SymbolTable32, Data, base() + getPointerToSymbolTable(),
417 getNumberOfSymbols() * getSymbolTableEntrySize()))
420 // Find string table. The first four byte of the string table contains the
421 // total size of the string table, including the size field itself. If the
422 // string table is empty, the value of the first four byte would be 4.
423 const uint8_t *StringTableAddr =
424 base() + getPointerToSymbolTable() +
425 getNumberOfSymbols() * getSymbolTableEntrySize();
426 const ulittle32_t *StringTableSizePtr;
427 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
429 StringTableSize = *StringTableSizePtr;
430 if (std::error_code EC =
431 getObject(StringTable, Data, StringTableAddr, StringTableSize))
434 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
435 // tools like cvtres write a size of 0 for an empty table instead of 4.
436 if (StringTableSize < 4)
439 // Check that the string table is null terminated if has any in it.
440 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
441 return object_error::parse_failed;
442 return object_error::success;
445 // Returns the file offset for the given VA.
446 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
447 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
448 : (uint64_t)PE32PlusHeader->ImageBase;
449 uint64_t Rva = Addr - ImageBase;
450 assert(Rva <= UINT32_MAX);
451 return getRvaPtr((uint32_t)Rva, Res);
454 // Returns the file offset for the given RVA.
455 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
456 for (const SectionRef &S : sections()) {
457 const coff_section *Section = getCOFFSection(S);
458 uint32_t SectionStart = Section->VirtualAddress;
459 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
460 if (SectionStart <= Addr && Addr < SectionEnd) {
461 uint32_t Offset = Addr - SectionStart;
462 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
463 return object_error::success;
466 return object_error::parse_failed;
469 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
471 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
472 StringRef &Name) const {
473 uintptr_t IntPtr = 0;
474 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
476 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
477 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
478 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
479 return object_error::success;
482 // Find the import table.
483 std::error_code COFFObjectFile::initImportTablePtr() {
484 // First, we get the RVA of the import table. If the file lacks a pointer to
485 // the import table, do nothing.
486 const data_directory *DataEntry;
487 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
488 return object_error::success;
490 // Do nothing if the pointer to import table is NULL.
491 if (DataEntry->RelativeVirtualAddress == 0)
492 return object_error::success;
494 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
495 // -1 because the last entry is the null entry.
496 NumberOfImportDirectory = DataEntry->Size /
497 sizeof(import_directory_table_entry) - 1;
499 // Find the section that contains the RVA. This is needed because the RVA is
500 // the import table's memory address which is different from its file offset.
501 uintptr_t IntPtr = 0;
502 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
504 ImportDirectory = reinterpret_cast<
505 const import_directory_table_entry *>(IntPtr);
506 return object_error::success;
509 // Find the export table.
510 std::error_code COFFObjectFile::initExportTablePtr() {
511 // First, we get the RVA of the export table. If the file lacks a pointer to
512 // the export table, do nothing.
513 const data_directory *DataEntry;
514 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
515 return object_error::success;
517 // Do nothing if the pointer to export table is NULL.
518 if (DataEntry->RelativeVirtualAddress == 0)
519 return object_error::success;
521 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
522 uintptr_t IntPtr = 0;
523 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
526 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
527 return object_error::success;
530 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
531 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
532 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
533 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
534 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
535 ImportDirectory(nullptr), NumberOfImportDirectory(0),
536 ExportDirectory(nullptr) {
537 // Check that we at least have enough room for a header.
538 if (!checkSize(Data, EC, sizeof(coff_file_header)))
541 // The current location in the file where we are looking at.
544 // PE header is optional and is present only in executables. If it exists,
545 // it is placed right after COFF header.
546 bool HasPEHeader = false;
548 // Check if this is a PE/COFF file.
549 if (base()[0] == 0x4d && base()[1] == 0x5a) {
550 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
551 // PE signature to find 'normal' COFF header.
552 if (!checkSize(Data, EC, 0x3c + 8))
554 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
555 // Check the PE magic bytes. ("PE\0\0")
556 if (std::memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) !=
558 EC = object_error::parse_failed;
561 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
565 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
568 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
569 // import libraries share a common prefix but bigobj is more restrictive.
570 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
571 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
572 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
573 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
576 // Verify that we are dealing with bigobj.
577 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
578 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
579 sizeof(COFF::BigObjMagic)) == 0) {
580 COFFHeader = nullptr;
581 CurPtr += sizeof(coff_bigobj_file_header);
583 // It's not a bigobj.
584 COFFBigObjHeader = nullptr;
588 // The prior checkSize call may have failed. This isn't a hard error
589 // because we were just trying to sniff out bigobj.
590 EC = object_error::success;
591 CurPtr += sizeof(coff_file_header);
593 if (COFFHeader->isImportLibrary())
598 const pe32_header *Header;
599 if ((EC = getObject(Header, Data, base() + CurPtr)))
602 const uint8_t *DataDirAddr;
603 uint64_t DataDirSize;
604 if (Header->Magic == 0x10b) {
606 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
607 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
608 } else if (Header->Magic == 0x20b) {
609 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
610 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
611 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
613 // It's neither PE32 nor PE32+.
614 EC = object_error::parse_failed;
617 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
619 CurPtr += COFFHeader->SizeOfOptionalHeader;
622 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
623 getNumberOfSections() * sizeof(coff_section))))
626 // Initialize the pointer to the symbol table.
627 if (getPointerToSymbolTable() != 0)
628 if ((EC = initSymbolTablePtr()))
631 // Initialize the pointer to the beginning of the import table.
632 if ((EC = initImportTablePtr()))
635 // Initialize the pointer to the export table.
636 if ((EC = initExportTablePtr()))
639 EC = object_error::success;
642 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
644 Ret.p = getSymbolTable();
645 return basic_symbol_iterator(SymbolRef(Ret, this));
648 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
649 // The symbol table ends where the string table begins.
651 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
652 return basic_symbol_iterator(SymbolRef(Ret, this));
655 import_directory_iterator COFFObjectFile::import_directory_begin() const {
656 return import_directory_iterator(
657 ImportDirectoryEntryRef(ImportDirectory, 0, this));
660 import_directory_iterator COFFObjectFile::import_directory_end() const {
661 return import_directory_iterator(
662 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
665 export_directory_iterator COFFObjectFile::export_directory_begin() const {
666 return export_directory_iterator(
667 ExportDirectoryEntryRef(ExportDirectory, 0, this));
670 export_directory_iterator COFFObjectFile::export_directory_end() const {
671 if (!ExportDirectory)
672 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
673 ExportDirectoryEntryRef Ref(ExportDirectory,
674 ExportDirectory->AddressTableEntries, this);
675 return export_directory_iterator(Ref);
678 section_iterator COFFObjectFile::section_begin() const {
680 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
681 return section_iterator(SectionRef(Ret, this));
684 section_iterator COFFObjectFile::section_end() const {
687 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
688 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
689 return section_iterator(SectionRef(Ret, this));
692 uint8_t COFFObjectFile::getBytesInAddress() const {
693 return getArch() == Triple::x86_64 ? 8 : 4;
696 StringRef COFFObjectFile::getFileFormatName() const {
697 switch(getMachine()) {
698 case COFF::IMAGE_FILE_MACHINE_I386:
700 case COFF::IMAGE_FILE_MACHINE_AMD64:
701 return "COFF-x86-64";
702 case COFF::IMAGE_FILE_MACHINE_ARMNT:
705 return "COFF-<unknown arch>";
709 unsigned COFFObjectFile::getArch() const {
710 switch (getMachine()) {
711 case COFF::IMAGE_FILE_MACHINE_I386:
713 case COFF::IMAGE_FILE_MACHINE_AMD64:
714 return Triple::x86_64;
715 case COFF::IMAGE_FILE_MACHINE_ARMNT:
716 return Triple::thumb;
718 return Triple::UnknownArch;
722 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
724 return object_error::success;
728 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
729 Res = PE32PlusHeader;
730 return object_error::success;
734 COFFObjectFile::getDataDirectory(uint32_t Index,
735 const data_directory *&Res) const {
736 // Error if if there's no data directory or the index is out of range.
738 return object_error::parse_failed;
739 assert(PE32Header || PE32PlusHeader);
740 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
741 : PE32PlusHeader->NumberOfRvaAndSize;
743 return object_error::parse_failed;
744 Res = &DataDirectory[Index];
745 return object_error::success;
748 std::error_code COFFObjectFile::getSection(int32_t Index,
749 const coff_section *&Result) const {
750 // Check for special index values.
751 if (COFF::isReservedSectionNumber(Index))
753 else if (Index > 0 && static_cast<uint32_t>(Index) <= getNumberOfSections())
754 // We already verified the section table data, so no need to check again.
755 Result = SectionTable + (Index - 1);
757 return object_error::parse_failed;
758 return object_error::success;
761 std::error_code COFFObjectFile::getString(uint32_t Offset,
762 StringRef &Result) const {
763 if (StringTableSize <= 4)
764 // Tried to get a string from an empty string table.
765 return object_error::parse_failed;
766 if (Offset >= StringTableSize)
767 return object_error::unexpected_eof;
768 Result = StringRef(StringTable + Offset);
769 return object_error::success;
772 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
773 StringRef &Res) const {
774 // Check for string table entry. First 4 bytes are 0.
775 if (Symbol.getStringTableOffset().Zeroes == 0) {
776 uint32_t Offset = Symbol.getStringTableOffset().Offset;
777 if (std::error_code EC = getString(Offset, Res))
779 return object_error::success;
782 if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
783 // Null terminated, let ::strlen figure out the length.
784 Res = StringRef(Symbol.getShortName());
786 // Not null terminated, use all 8 bytes.
787 Res = StringRef(Symbol.getShortName(), COFF::NameSize);
788 return object_error::success;
792 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
793 const uint8_t *Aux = nullptr;
795 size_t SymbolSize = getSymbolTableEntrySize();
796 if (Symbol.getNumberOfAuxSymbols() > 0) {
797 // AUX data comes immediately after the symbol in COFF
798 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
800 // Verify that the Aux symbol points to a valid entry in the symbol table.
801 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
802 if (Offset < getPointerToSymbolTable() ||
804 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
805 report_fatal_error("Aux Symbol data was outside of symbol table.");
807 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
808 "Aux Symbol data did not point to the beginning of a symbol");
811 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
814 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
815 StringRef &Res) const {
817 if (Sec->Name[COFF::NameSize - 1] == 0)
818 // Null terminated, let ::strlen figure out the length.
821 // Not null terminated, use all 8 bytes.
822 Name = StringRef(Sec->Name, COFF::NameSize);
824 // Check for string table entry. First byte is '/'.
825 if (Name[0] == '/') {
827 if (Name[1] == '/') {
828 if (decodeBase64StringEntry(Name.substr(2), Offset))
829 return object_error::parse_failed;
831 if (Name.substr(1).getAsInteger(10, Offset))
832 return object_error::parse_failed;
834 if (std::error_code EC = getString(Offset, Name))
839 return object_error::success;
843 COFFObjectFile::getSectionContents(const coff_section *Sec,
844 ArrayRef<uint8_t> &Res) const {
845 // PointerToRawData and SizeOfRawData won't make sense for BSS sections, don't
846 // do anything interesting for them.
847 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
848 "BSS sections don't have contents!");
849 // The only thing that we need to verify is that the contents is contained
850 // within the file bounds. We don't need to make sure it doesn't cover other
851 // data, as there's nothing that says that is not allowed.
852 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
853 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
854 if (ConEnd > uintptr_t(Data.getBufferEnd()))
855 return object_error::parse_failed;
856 Res = makeArrayRef(reinterpret_cast<const uint8_t*>(ConStart),
858 return object_error::success;
861 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
862 return reinterpret_cast<const coff_relocation*>(Rel.p);
865 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
866 Rel.p = reinterpret_cast<uintptr_t>(
867 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
870 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
871 uint64_t &Res) const {
872 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
875 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
876 uint64_t &Res) const {
877 Res = toRel(Rel)->VirtualAddress;
878 return object_error::success;
881 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
882 const coff_relocation *R = toRel(Rel);
885 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
886 else if (SymbolTable32)
887 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
889 llvm_unreachable("no symbol table pointer!");
890 return symbol_iterator(SymbolRef(Ref, this));
893 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
894 uint64_t &Res) const {
895 const coff_relocation* R = toRel(Rel);
897 return object_error::success;
901 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
902 return toSec(Section.getRawDataRefImpl());
905 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
907 return toSymb<coff_symbol16>(Ref);
909 return toSymb<coff_symbol32>(Ref);
910 llvm_unreachable("no symbol table pointer!");
913 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
914 return getCOFFSymbol(Symbol.getRawDataRefImpl());
917 const coff_relocation *
918 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
919 return toRel(Reloc.getRawDataRefImpl());
922 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
923 case COFF::reloc_type: \
928 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
929 SmallVectorImpl<char> &Result) const {
930 const coff_relocation *Reloc = toRel(Rel);
932 switch (getMachine()) {
933 case COFF::IMAGE_FILE_MACHINE_AMD64:
934 switch (Reloc->Type) {
935 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
936 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
937 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
938 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
939 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
940 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
941 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
942 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
943 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
944 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
945 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
946 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
947 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
948 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
949 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
950 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
951 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
956 case COFF::IMAGE_FILE_MACHINE_ARMNT:
957 switch (Reloc->Type) {
958 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
959 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
960 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
961 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
962 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
963 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
964 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
965 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
966 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
967 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
968 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
969 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
970 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
971 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
972 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
977 case COFF::IMAGE_FILE_MACHINE_I386:
978 switch (Reloc->Type) {
979 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
980 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
981 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
982 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
983 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
984 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
985 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
986 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
987 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
988 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
989 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
997 Result.append(Res.begin(), Res.end());
998 return object_error::success;
1001 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1004 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
1005 SmallVectorImpl<char> &Result) const {
1006 const coff_relocation *Reloc = toRel(Rel);
1008 ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1009 if (std::error_code EC = Symb.getError())
1011 Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1013 if (std::error_code EC = getSymbolName(Sym, SymName))
1015 Result.append(SymName.begin(), SymName.end());
1016 return object_error::success;
1019 bool COFFObjectFile::isRelocatableObject() const {
1020 return !DataDirectory;
1023 bool ImportDirectoryEntryRef::
1024 operator==(const ImportDirectoryEntryRef &Other) const {
1025 return ImportTable == Other.ImportTable && Index == Other.Index;
1028 void ImportDirectoryEntryRef::moveNext() {
1032 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1033 const import_directory_table_entry *&Result) const {
1034 Result = ImportTable + Index;
1035 return object_error::success;
1038 static imported_symbol_iterator
1039 makeImportedSymbolIterator(const COFFObjectFile *OwningObject,
1040 uintptr_t Ptr, int Index) {
1041 if (OwningObject->getBytesInAddress() == 4) {
1042 auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1043 return imported_symbol_iterator(ImportedSymbolRef(P, Index, OwningObject));
1045 auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1046 return imported_symbol_iterator(ImportedSymbolRef(P, Index, OwningObject));
1049 imported_symbol_iterator
1050 ImportDirectoryEntryRef::imported_symbol_begin() const {
1051 uintptr_t IntPtr = 0;
1052 OwningObject->getRvaPtr(ImportTable[Index].ImportLookupTableRVA, IntPtr);
1053 return makeImportedSymbolIterator(OwningObject, IntPtr, 0);
1056 imported_symbol_iterator
1057 ImportDirectoryEntryRef::imported_symbol_end() const {
1058 uintptr_t IntPtr = 0;
1059 OwningObject->getRvaPtr(ImportTable[Index].ImportLookupTableRVA, IntPtr);
1060 // Forward the pointer to the last entry which is null.
1062 if (OwningObject->getBytesInAddress() == 4) {
1063 auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1067 auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1071 return makeImportedSymbolIterator(OwningObject, IntPtr, Index);
1074 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1075 uintptr_t IntPtr = 0;
1076 if (std::error_code EC =
1077 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1079 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1080 return object_error::success;
1084 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1085 Result = ImportTable[Index].ImportLookupTableRVA;
1086 return object_error::success;
1090 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1091 Result = ImportTable[Index].ImportAddressTableRVA;
1092 return object_error::success;
1095 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1096 const import_lookup_table_entry32 *&Result) const {
1097 uintptr_t IntPtr = 0;
1098 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1099 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1101 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1102 return object_error::success;
1105 bool ExportDirectoryEntryRef::
1106 operator==(const ExportDirectoryEntryRef &Other) const {
1107 return ExportTable == Other.ExportTable && Index == Other.Index;
1110 void ExportDirectoryEntryRef::moveNext() {
1114 // Returns the name of the current export symbol. If the symbol is exported only
1115 // by ordinal, the empty string is set as a result.
1116 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1117 uintptr_t IntPtr = 0;
1118 if (std::error_code EC =
1119 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1121 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1122 return object_error::success;
1125 // Returns the starting ordinal number.
1127 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1128 Result = ExportTable->OrdinalBase;
1129 return object_error::success;
1132 // Returns the export ordinal of the current export symbol.
1133 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1134 Result = ExportTable->OrdinalBase + Index;
1135 return object_error::success;
1138 // Returns the address of the current export symbol.
1139 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1140 uintptr_t IntPtr = 0;
1141 if (std::error_code EC =
1142 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1144 const export_address_table_entry *entry =
1145 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1146 Result = entry[Index].ExportRVA;
1147 return object_error::success;
1150 // Returns the name of the current export symbol. If the symbol is exported only
1151 // by ordinal, the empty string is set as a result.
1153 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1154 uintptr_t IntPtr = 0;
1155 if (std::error_code EC =
1156 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1158 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1160 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1162 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1163 I < E; ++I, ++Offset) {
1166 if (std::error_code EC =
1167 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1169 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1170 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1172 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1173 return object_error::success;
1176 return object_error::success;
1179 bool ImportedSymbolRef::
1180 operator==(const ImportedSymbolRef &Other) const {
1181 return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1182 && Index == Other.Index;
1185 void ImportedSymbolRef::moveNext() {
1190 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1193 // If a symbol is imported only by ordinal, it has no name.
1194 if (Entry32[Index].isOrdinal())
1195 return object_error::success;
1196 RVA = Entry32[Index].getHintNameRVA();
1198 if (Entry64[Index].isOrdinal())
1199 return object_error::success;
1200 RVA = Entry64[Index].getHintNameRVA();
1202 uintptr_t IntPtr = 0;
1203 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1205 // +2 because the first two bytes is hint.
1206 Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1207 return object_error::success;
1210 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1213 if (Entry32[Index].isOrdinal()) {
1214 Result = Entry32[Index].getOrdinal();
1215 return object_error::success;
1217 RVA = Entry32[Index].getHintNameRVA();
1219 if (Entry64[Index].isOrdinal()) {
1220 Result = Entry64[Index].getOrdinal();
1221 return object_error::success;
1223 RVA = Entry64[Index].getHintNameRVA();
1225 uintptr_t IntPtr = 0;
1226 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1228 Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1229 return object_error::success;
1232 ErrorOr<std::unique_ptr<COFFObjectFile>>
1233 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1235 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1238 return std::move(Ret);