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::little16_t;
32 // Returns false if size is greater than the buffer size. And sets ec.
33 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
34 if (M.getBufferSize() < Size) {
35 EC = object_error::unexpected_eof;
41 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
42 // Returns unexpected_eof if error.
44 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
46 const size_t Size = sizeof(T)) {
47 uintptr_t Addr = uintptr_t(Ptr);
48 if (Addr + Size < Addr || Addr + Size < Size ||
49 Addr + Size > uintptr_t(M.getBufferEnd())) {
50 return object_error::unexpected_eof;
52 Obj = reinterpret_cast<const T *>(Addr);
53 return object_error::success;
56 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
58 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
59 assert(Str.size() <= 6 && "String too long, possible overflow.");
64 while (!Str.empty()) {
66 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
67 CharVal = Str[0] - 'A';
68 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
69 CharVal = Str[0] - 'a' + 26;
70 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
71 CharVal = Str[0] - '0' + 52;
72 else if (Str[0] == '+') // 62
74 else if (Str[0] == '/') // 63
79 Value = (Value * 64) + CharVal;
83 if (Value > std::numeric_limits<uint32_t>::max())
86 Result = static_cast<uint32_t>(Value);
90 template <typename coff_symbol_type>
91 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
92 const coff_symbol_type *Addr =
93 reinterpret_cast<const coff_symbol_type *>(Ref.p);
96 // Verify that the symbol points to a valid entry in the symbol table.
97 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
98 if (Offset < getPointerToSymbolTable() ||
99 Offset >= getPointerToSymbolTable() +
100 (getNumberOfSymbols() * sizeof(coff_symbol_type)))
101 report_fatal_error("Symbol was outside of symbol table.");
103 assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
104 "Symbol did not point to the beginning of a symbol");
110 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
111 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
114 // Verify that the section points to a valid entry in the section table.
115 if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
116 report_fatal_error("Section was outside of section table.");
118 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
119 assert(Offset % sizeof(coff_section) == 0 &&
120 "Section did not point to the beginning of a section");
126 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
128 const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
129 Symb += 1 + Symb->NumberOfAuxSymbols;
130 Ref.p = reinterpret_cast<uintptr_t>(Symb);
131 } else if (SymbolTable32) {
132 const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
133 Symb += 1 + Symb->NumberOfAuxSymbols;
134 Ref.p = reinterpret_cast<uintptr_t>(Symb);
136 llvm_unreachable("no symbol table pointer!");
140 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
141 StringRef &Result) const {
142 COFFSymbolRef Symb = getCOFFSymbol(Ref);
143 return getSymbolName(Symb, Result);
146 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
147 uint64_t &Result) const {
148 COFFSymbolRef Symb = getCOFFSymbol(Ref);
149 const coff_section *Section = nullptr;
150 if (std::error_code EC = getSection(Symb.getSectionNumber(), Section))
153 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED)
154 Result = UnknownAddressOrSize;
156 Result = Section->VirtualAddress + Symb.getValue();
158 Result = Symb.getValue();
159 return object_error::success;
162 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
163 SymbolRef::Type &Result) const {
164 COFFSymbolRef Symb = getCOFFSymbol(Ref);
165 Result = SymbolRef::ST_Other;
167 if (Symb.getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
168 Symb.getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED) {
169 Result = SymbolRef::ST_Unknown;
170 } else if (Symb.isFunctionDefinition()) {
171 Result = SymbolRef::ST_Function;
173 uint32_t Characteristics = 0;
174 if (!COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
175 const coff_section *Section = nullptr;
176 if (std::error_code EC = getSection(Symb.getSectionNumber(), Section))
178 Characteristics = Section->Characteristics;
180 if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
181 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
182 Result = SymbolRef::ST_Data;
184 return object_error::success;
187 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
188 COFFSymbolRef Symb = getCOFFSymbol(Ref);
189 uint32_t Result = SymbolRef::SF_None;
191 // TODO: Correctly set SF_FormatSpecific, SF_Common
193 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED) {
194 if (Symb.getValue() == 0)
195 Result |= SymbolRef::SF_Undefined;
197 Result |= SymbolRef::SF_Common;
201 // TODO: This are certainly too restrictive.
202 if (Symb.getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL)
203 Result |= SymbolRef::SF_Global;
205 if (Symb.getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
206 Result |= SymbolRef::SF_Weak;
208 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
209 Result |= SymbolRef::SF_Absolute;
214 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
215 uint64_t &Result) const {
216 // FIXME: Return the correct size. This requires looking at all the symbols
217 // in the same section as this symbol, and looking for either the next
218 // symbol, or the end of the section.
219 COFFSymbolRef Symb = getCOFFSymbol(Ref);
220 const coff_section *Section = nullptr;
221 if (std::error_code EC = getSection(Symb.getSectionNumber(), Section))
224 if (Symb.getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED)
225 Result = UnknownAddressOrSize;
227 Result = Section->SizeOfRawData - Symb.getValue();
230 return object_error::success;
234 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
235 section_iterator &Result) const {
236 COFFSymbolRef Symb = getCOFFSymbol(Ref);
237 if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
238 Result = section_end();
240 const coff_section *Sec = nullptr;
241 if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
244 Ref.p = reinterpret_cast<uintptr_t>(Sec);
245 Result = section_iterator(SectionRef(Ref, this));
247 return object_error::success;
250 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
251 const coff_section *Sec = toSec(Ref);
253 Ref.p = reinterpret_cast<uintptr_t>(Sec);
256 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
257 StringRef &Result) const {
258 const coff_section *Sec = toSec(Ref);
259 return getSectionName(Sec, Result);
262 std::error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
263 uint64_t &Result) const {
264 const coff_section *Sec = toSec(Ref);
265 Result = Sec->VirtualAddress;
266 return object_error::success;
269 std::error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
270 uint64_t &Result) const {
271 const coff_section *Sec = toSec(Ref);
272 Result = Sec->SizeOfRawData;
273 return object_error::success;
276 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
277 StringRef &Result) const {
278 const coff_section *Sec = toSec(Ref);
279 ArrayRef<uint8_t> Res;
280 std::error_code EC = getSectionContents(Sec, Res);
281 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
285 std::error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
286 uint64_t &Res) const {
287 const coff_section *Sec = toSec(Ref);
289 return object_error::parse_failed;
290 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
291 return object_error::success;
294 std::error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
295 bool &Result) const {
296 const coff_section *Sec = toSec(Ref);
297 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
298 return object_error::success;
301 std::error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
302 bool &Result) const {
303 const coff_section *Sec = toSec(Ref);
304 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
305 return object_error::success;
308 std::error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
309 bool &Result) const {
310 const coff_section *Sec = toSec(Ref);
311 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
312 return object_error::success;
316 COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
317 bool &Result) const {
318 // FIXME: Unimplemented
320 return object_error::success;
323 std::error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
324 bool &Result) const {
325 const coff_section *Sec = toSec(Ref);
326 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
327 return object_error::success;
330 std::error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
331 bool &Result) const {
332 // FIXME: Unimplemented.
334 return object_error::success;
337 std::error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
338 bool &Result) const {
339 // FIXME: Unimplemented.
341 return object_error::success;
344 std::error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
346 bool &Result) const {
347 const coff_section *Sec = toSec(SecRef);
348 COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
349 const coff_section *SymbSec = nullptr;
350 if (std::error_code EC = getSection(Symb.getSectionNumber(), SymbSec))
356 return object_error::success;
359 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
360 const coff_section *Sec = toSec(Ref);
362 if (Sec->NumberOfRelocations == 0) {
365 auto begin = reinterpret_cast<const coff_relocation*>(
366 base() + Sec->PointerToRelocations);
367 if (Sec->hasExtendedRelocations()) {
368 // Skip the first relocation entry repurposed to store the number of
372 Ret.p = reinterpret_cast<uintptr_t>(begin);
374 return relocation_iterator(RelocationRef(Ret, this));
377 static uint32_t getNumberOfRelocations(const coff_section *Sec,
378 const uint8_t *base) {
379 // The field for the number of relocations in COFF section table is only
380 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
381 // NumberOfRelocations field, and the actual relocation count is stored in the
382 // VirtualAddress field in the first relocation entry.
383 if (Sec->hasExtendedRelocations()) {
384 auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
385 base + Sec->PointerToRelocations);
386 return FirstReloc->VirtualAddress;
388 return Sec->NumberOfRelocations;
391 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
392 const coff_section *Sec = toSec(Ref);
394 if (Sec->NumberOfRelocations == 0) {
397 auto begin = reinterpret_cast<const coff_relocation*>(
398 base() + Sec->PointerToRelocations);
399 uint32_t NumReloc = getNumberOfRelocations(Sec, base());
400 Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
402 return relocation_iterator(RelocationRef(Ret, this));
405 // Initialize the pointer to the symbol table.
406 std::error_code COFFObjectFile::initSymbolTablePtr() {
408 if (std::error_code EC =
409 getObject(SymbolTable16, Data, base() + getPointerToSymbolTable(),
410 getNumberOfSymbols() * getSymbolTableEntrySize()))
413 if (COFFBigObjHeader)
414 if (std::error_code EC =
415 getObject(SymbolTable32, Data, base() + getPointerToSymbolTable(),
416 getNumberOfSymbols() * getSymbolTableEntrySize()))
419 // Find string table. The first four byte of the string table contains the
420 // total size of the string table, including the size field itself. If the
421 // string table is empty, the value of the first four byte would be 4.
422 const uint8_t *StringTableAddr =
423 base() + getPointerToSymbolTable() +
424 getNumberOfSymbols() * getSymbolTableEntrySize();
425 const ulittle32_t *StringTableSizePtr;
426 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
428 StringTableSize = *StringTableSizePtr;
429 if (std::error_code EC =
430 getObject(StringTable, Data, StringTableAddr, StringTableSize))
433 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
434 // tools like cvtres write a size of 0 for an empty table instead of 4.
435 if (StringTableSize < 4)
438 // Check that the string table is null terminated if has any in it.
439 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
440 return object_error::parse_failed;
441 return object_error::success;
444 // Returns the file offset for the given VA.
445 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
446 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
447 : (uint64_t)PE32PlusHeader->ImageBase;
448 uint64_t Rva = Addr - ImageBase;
449 assert(Rva <= UINT32_MAX);
450 return getRvaPtr((uint32_t)Rva, Res);
453 // Returns the file offset for the given RVA.
454 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
455 for (const SectionRef &S : sections()) {
456 const coff_section *Section = getCOFFSection(S);
457 uint32_t SectionStart = Section->VirtualAddress;
458 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
459 if (SectionStart <= Addr && Addr < SectionEnd) {
460 uint32_t Offset = Addr - SectionStart;
461 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
462 return object_error::success;
465 return object_error::parse_failed;
468 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
470 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
471 StringRef &Name) const {
472 uintptr_t IntPtr = 0;
473 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
475 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
476 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
477 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
478 return object_error::success;
481 // Find the import table.
482 std::error_code COFFObjectFile::initImportTablePtr() {
483 // First, we get the RVA of the import table. If the file lacks a pointer to
484 // the import table, do nothing.
485 const data_directory *DataEntry;
486 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
487 return object_error::success;
489 // Do nothing if the pointer to import table is NULL.
490 if (DataEntry->RelativeVirtualAddress == 0)
491 return object_error::success;
493 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
494 // -1 because the last entry is the null entry.
495 NumberOfImportDirectory = DataEntry->Size /
496 sizeof(import_directory_table_entry) - 1;
498 // Find the section that contains the RVA. This is needed because the RVA is
499 // the import table's memory address which is different from its file offset.
500 uintptr_t IntPtr = 0;
501 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
503 ImportDirectory = reinterpret_cast<
504 const import_directory_table_entry *>(IntPtr);
505 return object_error::success;
508 // Find the export table.
509 std::error_code COFFObjectFile::initExportTablePtr() {
510 // First, we get the RVA of the export table. If the file lacks a pointer to
511 // the export table, do nothing.
512 const data_directory *DataEntry;
513 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
514 return object_error::success;
516 // Do nothing if the pointer to export table is NULL.
517 if (DataEntry->RelativeVirtualAddress == 0)
518 return object_error::success;
520 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
521 uintptr_t IntPtr = 0;
522 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
525 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
526 return object_error::success;
529 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
530 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
531 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
532 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
533 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
534 ImportDirectory(nullptr), NumberOfImportDirectory(0),
535 ExportDirectory(nullptr) {
536 // Check that we at least have enough room for a header.
537 if (!checkSize(Data, EC, sizeof(coff_file_header)))
540 // The current location in the file where we are looking at.
543 // PE header is optional and is present only in executables. If it exists,
544 // it is placed right after COFF header.
545 bool HasPEHeader = false;
547 // Check if this is a PE/COFF file.
548 if (base()[0] == 0x4d && base()[1] == 0x5a) {
549 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
550 // PE signature to find 'normal' COFF header.
551 if (!checkSize(Data, EC, 0x3c + 8))
553 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
554 // Check the PE magic bytes. ("PE\0\0")
555 if (std::memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) !=
557 EC = object_error::parse_failed;
560 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
564 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
567 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
568 // import libraries share a common prefix but bigobj is more restrictive.
569 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
570 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
571 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
572 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
575 // Verify that we are dealing with bigobj.
576 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
577 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
578 sizeof(COFF::BigObjMagic)) == 0) {
579 COFFHeader = nullptr;
580 CurPtr += sizeof(coff_bigobj_file_header);
582 // It's not a bigobj.
583 COFFBigObjHeader = nullptr;
587 // The prior checkSize call may have failed. This isn't a hard error
588 // because we were just trying to sniff out bigobj.
589 EC = object_error::success;
590 CurPtr += sizeof(coff_file_header);
592 if (COFFHeader->isImportLibrary())
597 const pe32_header *Header;
598 if ((EC = getObject(Header, Data, base() + CurPtr)))
601 const uint8_t *DataDirAddr;
602 uint64_t DataDirSize;
603 if (Header->Magic == 0x10b) {
605 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
606 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
607 } else if (Header->Magic == 0x20b) {
608 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
609 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
610 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
612 // It's neither PE32 nor PE32+.
613 EC = object_error::parse_failed;
616 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
618 CurPtr += COFFHeader->SizeOfOptionalHeader;
621 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
622 getNumberOfSections() * sizeof(coff_section))))
625 // Initialize the pointer to the symbol table.
626 if (getPointerToSymbolTable() != 0)
627 if ((EC = initSymbolTablePtr()))
630 // Initialize the pointer to the beginning of the import table.
631 if ((EC = initImportTablePtr()))
634 // Initialize the pointer to the export table.
635 if ((EC = initExportTablePtr()))
638 EC = object_error::success;
641 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
643 Ret.p = getSymbolTable();
644 return basic_symbol_iterator(SymbolRef(Ret, this));
647 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
648 // The symbol table ends where the string table begins.
650 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
651 return basic_symbol_iterator(SymbolRef(Ret, this));
654 import_directory_iterator COFFObjectFile::import_directory_begin() const {
655 return import_directory_iterator(
656 ImportDirectoryEntryRef(ImportDirectory, 0, this));
659 import_directory_iterator COFFObjectFile::import_directory_end() const {
660 return import_directory_iterator(
661 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
664 export_directory_iterator COFFObjectFile::export_directory_begin() const {
665 return export_directory_iterator(
666 ExportDirectoryEntryRef(ExportDirectory, 0, this));
669 export_directory_iterator COFFObjectFile::export_directory_end() const {
670 if (!ExportDirectory)
671 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
672 ExportDirectoryEntryRef Ref(ExportDirectory,
673 ExportDirectory->AddressTableEntries, this);
674 return export_directory_iterator(Ref);
677 section_iterator COFFObjectFile::section_begin() const {
679 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
680 return section_iterator(SectionRef(Ret, this));
683 section_iterator COFFObjectFile::section_end() const {
686 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
687 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
688 return section_iterator(SectionRef(Ret, this));
691 uint8_t COFFObjectFile::getBytesInAddress() const {
692 return getArch() == Triple::x86_64 ? 8 : 4;
695 StringRef COFFObjectFile::getFileFormatName() const {
696 switch(getMachine()) {
697 case COFF::IMAGE_FILE_MACHINE_I386:
699 case COFF::IMAGE_FILE_MACHINE_AMD64:
700 return "COFF-x86-64";
701 case COFF::IMAGE_FILE_MACHINE_ARMNT:
704 return "COFF-<unknown arch>";
708 unsigned COFFObjectFile::getArch() const {
709 switch (getMachine()) {
710 case COFF::IMAGE_FILE_MACHINE_I386:
712 case COFF::IMAGE_FILE_MACHINE_AMD64:
713 return Triple::x86_64;
714 case COFF::IMAGE_FILE_MACHINE_ARMNT:
715 return Triple::thumb;
717 return Triple::UnknownArch;
721 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
723 return object_error::success;
727 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
728 Res = PE32PlusHeader;
729 return object_error::success;
733 COFFObjectFile::getDataDirectory(uint32_t Index,
734 const data_directory *&Res) const {
735 // Error if if there's no data directory or the index is out of range.
737 return object_error::parse_failed;
738 assert(PE32Header || PE32PlusHeader);
739 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
740 : PE32PlusHeader->NumberOfRvaAndSize;
742 return object_error::parse_failed;
743 Res = &DataDirectory[Index];
744 return object_error::success;
747 std::error_code COFFObjectFile::getSection(int32_t Index,
748 const coff_section *&Result) const {
749 // Check for special index values.
750 if (COFF::isReservedSectionNumber(Index))
752 else if (Index > 0 && static_cast<uint32_t>(Index) <= getNumberOfSections())
753 // We already verified the section table data, so no need to check again.
754 Result = SectionTable + (Index - 1);
756 return object_error::parse_failed;
757 return object_error::success;
760 std::error_code COFFObjectFile::getString(uint32_t Offset,
761 StringRef &Result) const {
762 if (StringTableSize <= 4)
763 // Tried to get a string from an empty string table.
764 return object_error::parse_failed;
765 if (Offset >= StringTableSize)
766 return object_error::unexpected_eof;
767 Result = StringRef(StringTable + Offset);
768 return object_error::success;
771 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
772 StringRef &Res) const {
773 // Check for string table entry. First 4 bytes are 0.
774 if (Symbol.getStringTableOffset().Zeroes == 0) {
775 uint32_t Offset = Symbol.getStringTableOffset().Offset;
776 if (std::error_code EC = getString(Offset, Res))
778 return object_error::success;
781 if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
782 // Null terminated, let ::strlen figure out the length.
783 Res = StringRef(Symbol.getShortName());
785 // Not null terminated, use all 8 bytes.
786 Res = StringRef(Symbol.getShortName(), COFF::NameSize);
787 return object_error::success;
791 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
792 const uint8_t *Aux = nullptr;
794 size_t SymbolSize = getSymbolTableEntrySize();
795 if (Symbol.getNumberOfAuxSymbols() > 0) {
796 // AUX data comes immediately after the symbol in COFF
797 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
799 // Verify that the Aux symbol points to a valid entry in the symbol table.
800 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
801 if (Offset < getPointerToSymbolTable() ||
803 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
804 report_fatal_error("Aux Symbol data was outside of symbol table.");
806 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
807 "Aux Symbol data did not point to the beginning of a symbol");
810 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
813 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
814 StringRef &Res) const {
816 if (Sec->Name[COFF::NameSize - 1] == 0)
817 // Null terminated, let ::strlen figure out the length.
820 // Not null terminated, use all 8 bytes.
821 Name = StringRef(Sec->Name, COFF::NameSize);
823 // Check for string table entry. First byte is '/'.
824 if (Name[0] == '/') {
826 if (Name[1] == '/') {
827 if (decodeBase64StringEntry(Name.substr(2), Offset))
828 return object_error::parse_failed;
830 if (Name.substr(1).getAsInteger(10, Offset))
831 return object_error::parse_failed;
833 if (std::error_code EC = getString(Offset, Name))
838 return object_error::success;
842 COFFObjectFile::getSectionContents(const coff_section *Sec,
843 ArrayRef<uint8_t> &Res) const {
844 // PointerToRawData and SizeOfRawData won't make sense for BSS sections, don't
845 // do anything interesting for them.
846 assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
847 "BSS sections don't have contents!");
848 // The only thing that we need to verify is that the contents is contained
849 // within the file bounds. We don't need to make sure it doesn't cover other
850 // data, as there's nothing that says that is not allowed.
851 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
852 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
853 if (ConEnd > uintptr_t(Data.getBufferEnd()))
854 return object_error::parse_failed;
855 Res = makeArrayRef(reinterpret_cast<const uint8_t*>(ConStart),
857 return object_error::success;
860 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
861 return reinterpret_cast<const coff_relocation*>(Rel.p);
864 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
865 Rel.p = reinterpret_cast<uintptr_t>(
866 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
869 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
870 uint64_t &Res) const {
871 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
874 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
875 uint64_t &Res) const {
876 Res = toRel(Rel)->VirtualAddress;
877 return object_error::success;
880 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
881 const coff_relocation *R = toRel(Rel);
884 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
885 else if (SymbolTable32)
886 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
888 llvm_unreachable("no symbol table pointer!");
889 return symbol_iterator(SymbolRef(Ref, this));
892 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
893 uint64_t &Res) const {
894 const coff_relocation* R = toRel(Rel);
896 return object_error::success;
900 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
901 return toSec(Section.getRawDataRefImpl());
904 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
906 return toSymb<coff_symbol16>(Ref);
908 return toSymb<coff_symbol32>(Ref);
909 llvm_unreachable("no symbol table pointer!");
912 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
913 return getCOFFSymbol(Symbol.getRawDataRefImpl());
916 const coff_relocation *
917 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
918 return toRel(Reloc.getRawDataRefImpl());
921 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
922 case COFF::reloc_type: \
927 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
928 SmallVectorImpl<char> &Result) const {
929 const coff_relocation *Reloc = toRel(Rel);
931 switch (getMachine()) {
932 case COFF::IMAGE_FILE_MACHINE_AMD64:
933 switch (Reloc->Type) {
934 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
935 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
936 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
937 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
938 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
939 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
940 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
941 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
942 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
943 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
944 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
945 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
946 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
947 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
948 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
949 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
950 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
955 case COFF::IMAGE_FILE_MACHINE_ARMNT:
956 switch (Reloc->Type) {
957 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
958 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
959 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
960 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
961 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
962 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
963 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
964 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
965 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
966 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
967 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
968 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
969 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
970 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
971 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
976 case COFF::IMAGE_FILE_MACHINE_I386:
977 switch (Reloc->Type) {
978 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
979 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
980 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
981 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
982 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
983 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
984 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
985 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
986 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
987 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
988 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
996 Result.append(Res.begin(), Res.end());
997 return object_error::success;
1000 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1003 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
1004 SmallVectorImpl<char> &Result) const {
1005 const coff_relocation *Reloc = toRel(Rel);
1007 ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1008 if (std::error_code EC = Symb.getError())
1010 Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1012 if (std::error_code EC = getSymbolName(Sym, SymName))
1014 Result.append(SymName.begin(), SymName.end());
1015 return object_error::success;
1018 bool COFFObjectFile::isRelocatableObject() const {
1019 return !DataDirectory;
1022 bool ImportDirectoryEntryRef::
1023 operator==(const ImportDirectoryEntryRef &Other) const {
1024 return ImportTable == Other.ImportTable && Index == Other.Index;
1027 void ImportDirectoryEntryRef::moveNext() {
1031 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1032 const import_directory_table_entry *&Result) const {
1033 Result = ImportTable + Index;
1034 return object_error::success;
1037 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1038 uintptr_t IntPtr = 0;
1039 if (std::error_code EC =
1040 OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1042 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1043 return object_error::success;
1047 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
1048 Result = ImportTable[Index].ImportLookupTableRVA;
1049 return object_error::success;
1053 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1054 Result = ImportTable[Index].ImportAddressTableRVA;
1055 return object_error::success;
1058 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1059 const import_lookup_table_entry32 *&Result) const {
1060 uintptr_t IntPtr = 0;
1061 uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1062 if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1064 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1065 return object_error::success;
1068 bool ExportDirectoryEntryRef::
1069 operator==(const ExportDirectoryEntryRef &Other) const {
1070 return ExportTable == Other.ExportTable && Index == Other.Index;
1073 void ExportDirectoryEntryRef::moveNext() {
1077 // Returns the name of the current export symbol. If the symbol is exported only
1078 // by ordinal, the empty string is set as a result.
1079 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1080 uintptr_t IntPtr = 0;
1081 if (std::error_code EC =
1082 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1084 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1085 return object_error::success;
1088 // Returns the starting ordinal number.
1090 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1091 Result = ExportTable->OrdinalBase;
1092 return object_error::success;
1095 // Returns the export ordinal of the current export symbol.
1096 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1097 Result = ExportTable->OrdinalBase + Index;
1098 return object_error::success;
1101 // Returns the address of the current export symbol.
1102 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1103 uintptr_t IntPtr = 0;
1104 if (std::error_code EC =
1105 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1107 const export_address_table_entry *entry =
1108 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1109 Result = entry[Index].ExportRVA;
1110 return object_error::success;
1113 // Returns the name of the current export symbol. If the symbol is exported only
1114 // by ordinal, the empty string is set as a result.
1116 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1117 uintptr_t IntPtr = 0;
1118 if (std::error_code EC =
1119 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1121 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1123 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1125 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1126 I < E; ++I, ++Offset) {
1129 if (std::error_code EC =
1130 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1132 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1133 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1135 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1136 return object_error::success;
1139 return object_error::success;
1142 ErrorOr<std::unique_ptr<COFFObjectFile>>
1143 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1145 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1148 return std::move(Ret);