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 NumberOfImportDirectory = DataEntry->Size /
495 sizeof(import_directory_table_entry);
497 // Find the section that contains the RVA. This is needed because the RVA is
498 // the import table's memory address which is different from its file offset.
499 uintptr_t IntPtr = 0;
500 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
502 ImportDirectory = reinterpret_cast<
503 const import_directory_table_entry *>(IntPtr);
504 return object_error::success;
507 // Find the export table.
508 std::error_code COFFObjectFile::initExportTablePtr() {
509 // First, we get the RVA of the export table. If the file lacks a pointer to
510 // the export table, do nothing.
511 const data_directory *DataEntry;
512 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
513 return object_error::success;
515 // Do nothing if the pointer to export table is NULL.
516 if (DataEntry->RelativeVirtualAddress == 0)
517 return object_error::success;
519 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
520 uintptr_t IntPtr = 0;
521 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
524 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
525 return object_error::success;
528 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
529 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
530 COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
531 DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
532 SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
533 ImportDirectory(nullptr), NumberOfImportDirectory(0),
534 ExportDirectory(nullptr) {
535 // Check that we at least have enough room for a header.
536 if (!checkSize(Data, EC, sizeof(coff_file_header)))
539 // The current location in the file where we are looking at.
542 // PE header is optional and is present only in executables. If it exists,
543 // it is placed right after COFF header.
544 bool HasPEHeader = false;
546 // Check if this is a PE/COFF file.
547 if (base()[0] == 0x4d && base()[1] == 0x5a) {
548 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
549 // PE signature to find 'normal' COFF header.
550 if (!checkSize(Data, EC, 0x3c + 8))
552 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
553 // Check the PE magic bytes. ("PE\0\0")
554 if (std::memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) !=
556 EC = object_error::parse_failed;
559 CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
563 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
566 // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
567 // import libraries share a common prefix but bigobj is more restrictive.
568 if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
569 COFFHeader->NumberOfSections == uint16_t(0xffff) &&
570 checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
571 if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
574 // Verify that we are dealing with bigobj.
575 if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
576 std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
577 sizeof(COFF::BigObjMagic)) == 0) {
578 COFFHeader = nullptr;
579 CurPtr += sizeof(coff_bigobj_file_header);
581 // It's not a bigobj.
582 COFFBigObjHeader = nullptr;
586 // The prior checkSize call may have failed. This isn't a hard error
587 // because we were just trying to sniff out bigobj.
588 EC = object_error::success;
589 CurPtr += sizeof(coff_file_header);
591 if (COFFHeader->isImportLibrary())
596 const pe32_header *Header;
597 if ((EC = getObject(Header, Data, base() + CurPtr)))
600 const uint8_t *DataDirAddr;
601 uint64_t DataDirSize;
602 if (Header->Magic == 0x10b) {
604 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
605 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
606 } else if (Header->Magic == 0x20b) {
607 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
608 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
609 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
611 // It's neither PE32 nor PE32+.
612 EC = object_error::parse_failed;
615 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
617 CurPtr += COFFHeader->SizeOfOptionalHeader;
620 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
621 getNumberOfSections() * sizeof(coff_section))))
624 // Initialize the pointer to the symbol table.
625 if (getPointerToSymbolTable() != 0)
626 if ((EC = initSymbolTablePtr()))
629 // Initialize the pointer to the beginning of the import table.
630 if ((EC = initImportTablePtr()))
633 // Initialize the pointer to the export table.
634 if ((EC = initExportTablePtr()))
637 EC = object_error::success;
640 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
642 Ret.p = getSymbolTable();
643 return basic_symbol_iterator(SymbolRef(Ret, this));
646 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
647 // The symbol table ends where the string table begins.
649 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
650 return basic_symbol_iterator(SymbolRef(Ret, this));
653 import_directory_iterator COFFObjectFile::import_directory_begin() const {
654 return import_directory_iterator(
655 ImportDirectoryEntryRef(ImportDirectory, 0, this));
658 import_directory_iterator COFFObjectFile::import_directory_end() const {
659 return import_directory_iterator(
660 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
663 export_directory_iterator COFFObjectFile::export_directory_begin() const {
664 return export_directory_iterator(
665 ExportDirectoryEntryRef(ExportDirectory, 0, this));
668 export_directory_iterator COFFObjectFile::export_directory_end() const {
669 if (!ExportDirectory)
670 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
671 ExportDirectoryEntryRef Ref(ExportDirectory,
672 ExportDirectory->AddressTableEntries, this);
673 return export_directory_iterator(Ref);
676 section_iterator COFFObjectFile::section_begin() const {
678 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
679 return section_iterator(SectionRef(Ret, this));
682 section_iterator COFFObjectFile::section_end() const {
685 COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
686 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
687 return section_iterator(SectionRef(Ret, this));
690 uint8_t COFFObjectFile::getBytesInAddress() const {
691 return getArch() == Triple::x86_64 ? 8 : 4;
694 StringRef COFFObjectFile::getFileFormatName() const {
695 switch(getMachine()) {
696 case COFF::IMAGE_FILE_MACHINE_I386:
698 case COFF::IMAGE_FILE_MACHINE_AMD64:
699 return "COFF-x86-64";
700 case COFF::IMAGE_FILE_MACHINE_ARMNT:
703 return "COFF-<unknown arch>";
707 unsigned COFFObjectFile::getArch() const {
708 switch (getMachine()) {
709 case COFF::IMAGE_FILE_MACHINE_I386:
711 case COFF::IMAGE_FILE_MACHINE_AMD64:
712 return Triple::x86_64;
713 case COFF::IMAGE_FILE_MACHINE_ARMNT:
714 return Triple::thumb;
716 return Triple::UnknownArch;
720 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
722 return object_error::success;
726 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
727 Res = PE32PlusHeader;
728 return object_error::success;
732 COFFObjectFile::getDataDirectory(uint32_t Index,
733 const data_directory *&Res) const {
734 // Error if if there's no data directory or the index is out of range.
736 return object_error::parse_failed;
737 assert(PE32Header || PE32PlusHeader);
738 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
739 : PE32PlusHeader->NumberOfRvaAndSize;
741 return object_error::parse_failed;
742 Res = &DataDirectory[Index];
743 return object_error::success;
746 std::error_code COFFObjectFile::getSection(int32_t Index,
747 const coff_section *&Result) const {
748 // Check for special index values.
749 if (COFF::isReservedSectionNumber(Index))
751 else if (Index > 0 && static_cast<uint32_t>(Index) <= getNumberOfSections())
752 // We already verified the section table data, so no need to check again.
753 Result = SectionTable + (Index - 1);
755 return object_error::parse_failed;
756 return object_error::success;
759 std::error_code COFFObjectFile::getString(uint32_t Offset,
760 StringRef &Result) const {
761 if (StringTableSize <= 4)
762 // Tried to get a string from an empty string table.
763 return object_error::parse_failed;
764 if (Offset >= StringTableSize)
765 return object_error::unexpected_eof;
766 Result = StringRef(StringTable + Offset);
767 return object_error::success;
770 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
771 StringRef &Res) const {
772 // Check for string table entry. First 4 bytes are 0.
773 if (Symbol.getStringTableOffset().Zeroes == 0) {
774 uint32_t Offset = Symbol.getStringTableOffset().Offset;
775 if (std::error_code EC = getString(Offset, Res))
777 return object_error::success;
780 if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
781 // Null terminated, let ::strlen figure out the length.
782 Res = StringRef(Symbol.getShortName());
784 // Not null terminated, use all 8 bytes.
785 Res = StringRef(Symbol.getShortName(), COFF::NameSize);
786 return object_error::success;
790 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
791 const uint8_t *Aux = nullptr;
793 size_t SymbolSize = getSymbolTableEntrySize();
794 if (Symbol.getNumberOfAuxSymbols() > 0) {
795 // AUX data comes immediately after the symbol in COFF
796 Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
798 // Verify that the Aux symbol points to a valid entry in the symbol table.
799 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
800 if (Offset < getPointerToSymbolTable() ||
802 getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
803 report_fatal_error("Aux Symbol data was outside of symbol table.");
805 assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
806 "Aux Symbol data did not point to the beginning of a symbol");
809 return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
812 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
813 StringRef &Res) const {
815 if (Sec->Name[COFF::NameSize - 1] == 0)
816 // Null terminated, let ::strlen figure out the length.
819 // Not null terminated, use all 8 bytes.
820 Name = StringRef(Sec->Name, COFF::NameSize);
822 // Check for string table entry. First byte is '/'.
823 if (Name[0] == '/') {
825 if (Name[1] == '/') {
826 if (decodeBase64StringEntry(Name.substr(2), Offset))
827 return object_error::parse_failed;
829 if (Name.substr(1).getAsInteger(10, Offset))
830 return object_error::parse_failed;
832 if (std::error_code EC = getString(Offset, Name))
837 return object_error::success;
841 COFFObjectFile::getSectionContents(const coff_section *Sec,
842 ArrayRef<uint8_t> &Res) const {
843 // The only thing that we need to verify is that the contents is contained
844 // within the file bounds. We don't need to make sure it doesn't cover other
845 // data, as there's nothing that says that is not allowed.
846 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
847 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
848 if (ConEnd > uintptr_t(Data.getBufferEnd()))
849 return object_error::parse_failed;
850 Res = makeArrayRef(reinterpret_cast<const uint8_t*>(ConStart),
852 return object_error::success;
855 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
856 return reinterpret_cast<const coff_relocation*>(Rel.p);
859 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
860 Rel.p = reinterpret_cast<uintptr_t>(
861 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
864 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
865 uint64_t &Res) const {
866 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
869 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
870 uint64_t &Res) const {
871 Res = toRel(Rel)->VirtualAddress;
872 return object_error::success;
875 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
876 const coff_relocation *R = toRel(Rel);
879 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
880 else if (SymbolTable32)
881 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
883 llvm_unreachable("no symbol table pointer!");
884 return symbol_iterator(SymbolRef(Ref, this));
887 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
888 uint64_t &Res) const {
889 const coff_relocation* R = toRel(Rel);
891 return object_error::success;
895 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
896 return toSec(Section.getRawDataRefImpl());
899 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
901 return toSymb<coff_symbol16>(Ref);
903 return toSymb<coff_symbol32>(Ref);
904 llvm_unreachable("no symbol table pointer!");
907 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
908 return getCOFFSymbol(Symbol.getRawDataRefImpl());
911 const coff_relocation *
912 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
913 return toRel(Reloc.getRawDataRefImpl());
916 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
917 case COFF::reloc_type: \
922 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
923 SmallVectorImpl<char> &Result) const {
924 const coff_relocation *Reloc = toRel(Rel);
926 switch (getMachine()) {
927 case COFF::IMAGE_FILE_MACHINE_AMD64:
928 switch (Reloc->Type) {
929 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
930 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
931 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
932 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
933 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
934 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
935 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
936 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
937 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
938 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
939 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
940 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
941 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
942 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
943 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
944 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
945 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
950 case COFF::IMAGE_FILE_MACHINE_ARMNT:
951 switch (Reloc->Type) {
952 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
953 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
954 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
955 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
956 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
957 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
958 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
959 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
960 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
961 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
962 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
963 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
964 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
965 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
966 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
971 case COFF::IMAGE_FILE_MACHINE_I386:
972 switch (Reloc->Type) {
973 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
974 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
975 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
976 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
977 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
978 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
979 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
980 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
981 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
982 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
983 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
991 Result.append(Res.begin(), Res.end());
992 return object_error::success;
995 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
998 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
999 SmallVectorImpl<char> &Result) const {
1000 const coff_relocation *Reloc = toRel(Rel);
1002 ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1003 if (std::error_code EC = Symb.getError())
1005 Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1007 if (std::error_code EC = getSymbolName(Sym, SymName))
1009 Result.append(SymName.begin(), SymName.end());
1010 return object_error::success;
1013 bool COFFObjectFile::isRelocatableObject() const {
1014 return !DataDirectory;
1017 bool ImportDirectoryEntryRef::
1018 operator==(const ImportDirectoryEntryRef &Other) const {
1019 return ImportTable == Other.ImportTable && Index == Other.Index;
1022 void ImportDirectoryEntryRef::moveNext() {
1026 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1027 const import_directory_table_entry *&Result) const {
1028 Result = ImportTable;
1029 return object_error::success;
1032 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1033 uintptr_t IntPtr = 0;
1034 if (std::error_code EC =
1035 OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
1037 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1038 return object_error::success;
1041 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1042 const import_lookup_table_entry32 *&Result) const {
1043 uintptr_t IntPtr = 0;
1044 if (std::error_code EC =
1045 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
1047 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1048 return object_error::success;
1051 bool ExportDirectoryEntryRef::
1052 operator==(const ExportDirectoryEntryRef &Other) const {
1053 return ExportTable == Other.ExportTable && Index == Other.Index;
1056 void ExportDirectoryEntryRef::moveNext() {
1060 // Returns the name of the current export symbol. If the symbol is exported only
1061 // by ordinal, the empty string is set as a result.
1062 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1063 uintptr_t IntPtr = 0;
1064 if (std::error_code EC =
1065 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1067 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1068 return object_error::success;
1071 // Returns the starting ordinal number.
1073 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1074 Result = ExportTable->OrdinalBase;
1075 return object_error::success;
1078 // Returns the export ordinal of the current export symbol.
1079 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1080 Result = ExportTable->OrdinalBase + Index;
1081 return object_error::success;
1084 // Returns the address of the current export symbol.
1085 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1086 uintptr_t IntPtr = 0;
1087 if (std::error_code EC =
1088 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1090 const export_address_table_entry *entry =
1091 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1092 Result = entry[Index].ExportRVA;
1093 return object_error::success;
1096 // Returns the name of the current export symbol. If the symbol is exported only
1097 // by ordinal, the empty string is set as a result.
1099 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1100 uintptr_t IntPtr = 0;
1101 if (std::error_code EC =
1102 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1104 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1106 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1108 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1109 I < E; ++I, ++Offset) {
1112 if (std::error_code EC =
1113 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1115 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1116 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1118 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1119 return object_error::success;
1122 return object_error::success;
1125 ErrorOr<std::unique_ptr<COFFObjectFile>>
1126 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1128 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1131 return std::move(Ret);