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::ulittle8_t;
29 using support::ulittle16_t;
30 using support::ulittle32_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 NumberOfImportDirectory = DataEntry->Size /
496 sizeof(import_directory_table_entry);
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 // The only thing that we need to verify is that the contents is contained
845 // within the file bounds. We don't need to make sure it doesn't cover other
846 // data, as there's nothing that says that is not allowed.
847 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
848 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
849 if (ConEnd > uintptr_t(Data.getBufferEnd()))
850 return object_error::parse_failed;
851 Res = makeArrayRef(reinterpret_cast<const uint8_t*>(ConStart),
853 return object_error::success;
856 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
857 return reinterpret_cast<const coff_relocation*>(Rel.p);
860 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
861 Rel.p = reinterpret_cast<uintptr_t>(
862 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
865 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
866 uint64_t &Res) const {
867 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
870 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
871 uint64_t &Res) const {
872 Res = toRel(Rel)->VirtualAddress;
873 return object_error::success;
876 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
877 const coff_relocation *R = toRel(Rel);
880 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
881 else if (SymbolTable32)
882 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
884 llvm_unreachable("no symbol table pointer!");
885 return symbol_iterator(SymbolRef(Ref, this));
888 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
889 uint64_t &Res) const {
890 const coff_relocation* R = toRel(Rel);
892 return object_error::success;
896 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
897 return toSec(Section.getRawDataRefImpl());
900 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
902 return toSymb<coff_symbol16>(Ref);
904 return toSymb<coff_symbol32>(Ref);
905 llvm_unreachable("no symbol table pointer!");
908 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
909 return getCOFFSymbol(Symbol.getRawDataRefImpl());
912 const coff_relocation *
913 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
914 return toRel(Reloc.getRawDataRefImpl());
917 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
918 case COFF::reloc_type: \
923 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
924 SmallVectorImpl<char> &Result) const {
925 const coff_relocation *Reloc = toRel(Rel);
927 switch (getMachine()) {
928 case COFF::IMAGE_FILE_MACHINE_AMD64:
929 switch (Reloc->Type) {
930 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
931 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
932 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
933 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
934 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
935 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
936 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
937 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
938 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
939 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
940 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
941 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
942 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
943 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
944 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
945 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
946 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
951 case COFF::IMAGE_FILE_MACHINE_ARMNT:
952 switch (Reloc->Type) {
953 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
954 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
955 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
956 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
957 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
958 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
959 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
960 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
961 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
962 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
963 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
964 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
965 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
966 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
967 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
972 case COFF::IMAGE_FILE_MACHINE_I386:
973 switch (Reloc->Type) {
974 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
975 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
976 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
977 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
978 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
979 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
980 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
981 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
982 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
983 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
984 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
992 Result.append(Res.begin(), Res.end());
993 return object_error::success;
996 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
999 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
1000 SmallVectorImpl<char> &Result) const {
1001 const coff_relocation *Reloc = toRel(Rel);
1003 ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1004 if (std::error_code EC = Symb.getError())
1006 Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1008 if (std::error_code EC = getSymbolName(Sym, SymName))
1010 Result.append(SymName.begin(), SymName.end());
1011 return object_error::success;
1014 bool COFFObjectFile::isRelocatableObject() const {
1015 return !DataDirectory;
1018 bool ImportDirectoryEntryRef::
1019 operator==(const ImportDirectoryEntryRef &Other) const {
1020 return ImportTable == Other.ImportTable && Index == Other.Index;
1023 void ImportDirectoryEntryRef::moveNext() {
1027 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1028 const import_directory_table_entry *&Result) const {
1029 Result = ImportTable;
1030 return object_error::success;
1033 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1034 uintptr_t IntPtr = 0;
1035 if (std::error_code EC =
1036 OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
1038 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1039 return object_error::success;
1042 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1043 const import_lookup_table_entry32 *&Result) const {
1044 uintptr_t IntPtr = 0;
1045 if (std::error_code EC =
1046 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
1048 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1049 return object_error::success;
1052 bool ExportDirectoryEntryRef::
1053 operator==(const ExportDirectoryEntryRef &Other) const {
1054 return ExportTable == Other.ExportTable && Index == Other.Index;
1057 void ExportDirectoryEntryRef::moveNext() {
1061 // Returns the name of the current export symbol. If the symbol is exported only
1062 // by ordinal, the empty string is set as a result.
1063 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1064 uintptr_t IntPtr = 0;
1065 if (std::error_code EC =
1066 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1068 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1069 return object_error::success;
1072 // Returns the starting ordinal number.
1074 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1075 Result = ExportTable->OrdinalBase;
1076 return object_error::success;
1079 // Returns the export ordinal of the current export symbol.
1080 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1081 Result = ExportTable->OrdinalBase + Index;
1082 return object_error::success;
1085 // Returns the address of the current export symbol.
1086 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1087 uintptr_t IntPtr = 0;
1088 if (std::error_code EC =
1089 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1091 const export_address_table_entry *entry =
1092 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1093 Result = entry[Index].ExportRVA;
1094 return object_error::success;
1097 // Returns the name of the current export symbol. If the symbol is exported only
1098 // by ordinal, the empty string is set as a result.
1100 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1101 uintptr_t IntPtr = 0;
1102 if (std::error_code EC =
1103 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1105 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1107 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1109 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1110 I < E; ++I, ++Offset) {
1113 if (std::error_code EC =
1114 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1116 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1117 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1119 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1120 return object_error::success;
1123 return object_error::success;
1126 ErrorOr<std::unique_ptr<COFFObjectFile>>
1127 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1129 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1132 return std::move(Ret);