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(const MemoryBuffer &M, std::error_code &EC,
36 if (M.getBufferSize() < Size) {
37 EC = object_error::unexpected_eof;
43 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
44 // Returns unexpected_eof if error.
46 static std::error_code getObject(const T *&Obj, const MemoryBuffer &M,
48 const size_t Size = sizeof(T)) {
49 uintptr_t Addr = uintptr_t(Ptr);
50 if (Addr + Size < Addr || Addr + Size < Size ||
51 Addr + Size > uintptr_t(M.getBufferEnd())) {
52 return object_error::unexpected_eof;
54 Obj = reinterpret_cast<const T *>(Addr);
55 return object_error::success;
58 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
60 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
61 assert(Str.size() <= 6 && "String too long, possible overflow.");
66 while (!Str.empty()) {
68 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
69 CharVal = Str[0] - 'A';
70 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
71 CharVal = Str[0] - 'a' + 26;
72 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
73 CharVal = Str[0] - '0' + 52;
74 else if (Str[0] == '+') // 62
76 else if (Str[0] == '/') // 63
81 Value = (Value * 64) + CharVal;
85 if (Value > std::numeric_limits<uint32_t>::max())
88 Result = static_cast<uint32_t>(Value);
92 const coff_symbol *COFFObjectFile::toSymb(DataRefImpl Ref) const {
93 const coff_symbol *Addr = reinterpret_cast<const coff_symbol*>(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 < COFFHeader->PointerToSymbolTable
99 || Offset >= COFFHeader->PointerToSymbolTable
100 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
101 report_fatal_error("Symbol was outside of symbol table.");
103 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
104 == 0 && "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
116 || Addr >= (SectionTable + COFFHeader->NumberOfSections))
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 {
128 const coff_symbol *Symb = toSymb(Ref);
129 Symb += 1 + Symb->NumberOfAuxSymbols;
130 Ref.p = reinterpret_cast<uintptr_t>(Symb);
133 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
134 StringRef &Result) const {
135 const coff_symbol *Symb = toSymb(Ref);
136 return getSymbolName(Symb, Result);
139 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
140 uint64_t &Result) const {
141 const coff_symbol *Symb = toSymb(Ref);
142 const coff_section *Section = nullptr;
143 if (std::error_code EC = getSection(Symb->SectionNumber, Section))
146 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
147 Result = UnknownAddressOrSize;
149 Result = Section->VirtualAddress + Symb->Value;
151 Result = Symb->Value;
152 return object_error::success;
155 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
156 SymbolRef::Type &Result) const {
157 const coff_symbol *Symb = toSymb(Ref);
158 Result = SymbolRef::ST_Other;
159 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
160 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
161 Result = SymbolRef::ST_Unknown;
162 } else if (Symb->isFunctionDefinition()) {
163 Result = SymbolRef::ST_Function;
165 uint32_t Characteristics = 0;
166 if (!COFF::isReservedSectionNumber(Symb->SectionNumber)) {
167 const coff_section *Section = nullptr;
168 if (std::error_code EC = getSection(Symb->SectionNumber, Section))
170 Characteristics = Section->Characteristics;
172 if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
173 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
174 Result = SymbolRef::ST_Data;
176 return object_error::success;
179 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
180 const coff_symbol *Symb = toSymb(Ref);
181 uint32_t Result = SymbolRef::SF_None;
183 // TODO: Correctly set SF_FormatSpecific, SF_Common
185 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
186 if (Symb->Value == 0)
187 Result |= SymbolRef::SF_Undefined;
189 Result |= SymbolRef::SF_Common;
193 // TODO: This are certainly too restrictive.
194 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
195 Result |= SymbolRef::SF_Global;
197 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
198 Result |= SymbolRef::SF_Weak;
200 if (Symb->SectionNumber == COFF::IMAGE_SYM_ABSOLUTE)
201 Result |= SymbolRef::SF_Absolute;
206 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
207 uint64_t &Result) const {
208 // FIXME: Return the correct size. This requires looking at all the symbols
209 // in the same section as this symbol, and looking for either the next
210 // symbol, or the end of the section.
211 const coff_symbol *Symb = toSymb(Ref);
212 const coff_section *Section = nullptr;
213 if (std::error_code EC = getSection(Symb->SectionNumber, Section))
216 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
217 Result = UnknownAddressOrSize;
219 Result = Section->SizeOfRawData - Symb->Value;
222 return object_error::success;
226 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
227 section_iterator &Result) const {
228 const coff_symbol *Symb = toSymb(Ref);
229 if (COFF::isReservedSectionNumber(Symb->SectionNumber)) {
230 Result = section_end();
232 const coff_section *Sec = nullptr;
233 if (std::error_code EC = getSection(Symb->SectionNumber, Sec))
236 Ref.p = reinterpret_cast<uintptr_t>(Sec);
237 Result = section_iterator(SectionRef(Ref, this));
239 return object_error::success;
242 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
243 const coff_section *Sec = toSec(Ref);
245 Ref.p = reinterpret_cast<uintptr_t>(Sec);
248 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
249 StringRef &Result) const {
250 const coff_section *Sec = toSec(Ref);
251 return getSectionName(Sec, Result);
254 std::error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
255 uint64_t &Result) const {
256 const coff_section *Sec = toSec(Ref);
257 Result = Sec->VirtualAddress;
258 return object_error::success;
261 std::error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
262 uint64_t &Result) const {
263 const coff_section *Sec = toSec(Ref);
264 Result = Sec->SizeOfRawData;
265 return object_error::success;
268 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
269 StringRef &Result) const {
270 const coff_section *Sec = toSec(Ref);
271 ArrayRef<uint8_t> Res;
272 std::error_code EC = getSectionContents(Sec, Res);
273 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
277 std::error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
278 uint64_t &Res) const {
279 const coff_section *Sec = toSec(Ref);
281 return object_error::parse_failed;
282 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
283 return object_error::success;
286 std::error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
287 bool &Result) const {
288 const coff_section *Sec = toSec(Ref);
289 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
290 return object_error::success;
293 std::error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
294 bool &Result) const {
295 const coff_section *Sec = toSec(Ref);
296 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
297 return object_error::success;
300 std::error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
301 bool &Result) const {
302 const coff_section *Sec = toSec(Ref);
303 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
304 return object_error::success;
308 COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
309 bool &Result) const {
310 // FIXME: Unimplemented
312 return object_error::success;
315 std::error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
316 bool &Result) const {
317 const coff_section *Sec = toSec(Ref);
318 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
319 return object_error::success;
322 std::error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
323 bool &Result) const {
324 // FIXME: Unimplemented.
326 return object_error::success;
329 std::error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
330 bool &Result) const {
331 // FIXME: Unimplemented.
333 return object_error::success;
336 std::error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
338 bool &Result) const {
339 const coff_section *Sec = toSec(SecRef);
340 const coff_symbol *Symb = toSymb(SymbRef);
341 const coff_section *SymbSec = nullptr;
342 if (std::error_code EC = getSection(Symb->SectionNumber, SymbSec))
348 return object_error::success;
351 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
352 const coff_section *Sec = toSec(Ref);
354 if (Sec->NumberOfRelocations == 0) {
357 auto begin = reinterpret_cast<const coff_relocation*>(
358 base() + Sec->PointerToRelocations);
359 if (Sec->hasExtendedRelocations()) {
360 // Skip the first relocation entry repurposed to store the number of
364 Ret.p = reinterpret_cast<uintptr_t>(begin);
366 return relocation_iterator(RelocationRef(Ret, this));
369 static uint32_t getNumberOfRelocations(const coff_section *Sec,
370 const uint8_t *base) {
371 // The field for the number of relocations in COFF section table is only
372 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
373 // NumberOfRelocations field, and the actual relocation count is stored in the
374 // VirtualAddress field in the first relocation entry.
375 if (Sec->hasExtendedRelocations()) {
376 auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
377 base + Sec->PointerToRelocations);
378 return FirstReloc->VirtualAddress;
380 return Sec->NumberOfRelocations;
383 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
384 const coff_section *Sec = toSec(Ref);
386 if (Sec->NumberOfRelocations == 0) {
389 auto begin = reinterpret_cast<const coff_relocation*>(
390 base() + Sec->PointerToRelocations);
391 uint32_t NumReloc = getNumberOfRelocations(Sec, base());
392 Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
394 return relocation_iterator(RelocationRef(Ret, this));
397 // Initialize the pointer to the symbol table.
398 std::error_code COFFObjectFile::initSymbolTablePtr() {
399 if (std::error_code EC = getObject(
400 SymbolTable, *Data, base() + COFFHeader->PointerToSymbolTable,
401 COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
404 // Find string table. The first four byte of the string table contains the
405 // total size of the string table, including the size field itself. If the
406 // string table is empty, the value of the first four byte would be 4.
407 const uint8_t *StringTableAddr =
408 base() + COFFHeader->PointerToSymbolTable +
409 COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
410 const ulittle32_t *StringTableSizePtr;
411 if (std::error_code EC =
412 getObject(StringTableSizePtr, *Data, StringTableAddr))
414 StringTableSize = *StringTableSizePtr;
415 if (std::error_code EC =
416 getObject(StringTable, *Data, StringTableAddr, StringTableSize))
419 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
420 // tools like cvtres write a size of 0 for an empty table instead of 4.
421 if (StringTableSize < 4)
424 // Check that the string table is null terminated if has any in it.
425 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
426 return object_error::parse_failed;
427 return object_error::success;
430 // Returns the file offset for the given VA.
431 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
432 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
433 : (uint64_t)PE32PlusHeader->ImageBase;
434 uint64_t Rva = Addr - ImageBase;
435 assert(Rva <= UINT32_MAX);
436 return getRvaPtr((uint32_t)Rva, Res);
439 // Returns the file offset for the given RVA.
440 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
441 for (const SectionRef &S : sections()) {
442 const coff_section *Section = getCOFFSection(S);
443 uint32_t SectionStart = Section->VirtualAddress;
444 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
445 if (SectionStart <= Addr && Addr < SectionEnd) {
446 uint32_t Offset = Addr - SectionStart;
447 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
448 return object_error::success;
451 return object_error::parse_failed;
454 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
456 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
457 StringRef &Name) const {
458 uintptr_t IntPtr = 0;
459 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
461 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
462 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
463 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
464 return object_error::success;
467 // Find the import table.
468 std::error_code COFFObjectFile::initImportTablePtr() {
469 // First, we get the RVA of the import table. If the file lacks a pointer to
470 // the import table, do nothing.
471 const data_directory *DataEntry;
472 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
473 return object_error::success;
475 // Do nothing if the pointer to import table is NULL.
476 if (DataEntry->RelativeVirtualAddress == 0)
477 return object_error::success;
479 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
480 NumberOfImportDirectory = DataEntry->Size /
481 sizeof(import_directory_table_entry);
483 // Find the section that contains the RVA. This is needed because the RVA is
484 // the import table's memory address which is different from its file offset.
485 uintptr_t IntPtr = 0;
486 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
488 ImportDirectory = reinterpret_cast<
489 const import_directory_table_entry *>(IntPtr);
490 return object_error::success;
493 // Find the export table.
494 std::error_code COFFObjectFile::initExportTablePtr() {
495 // First, we get the RVA of the export table. If the file lacks a pointer to
496 // the export table, do nothing.
497 const data_directory *DataEntry;
498 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
499 return object_error::success;
501 // Do nothing if the pointer to export table is NULL.
502 if (DataEntry->RelativeVirtualAddress == 0)
503 return object_error::success;
505 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
506 uintptr_t IntPtr = 0;
507 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
510 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
511 return object_error::success;
514 COFFObjectFile::COFFObjectFile(std::unique_ptr<MemoryBuffer> Object,
516 : ObjectFile(Binary::ID_COFF, std::move(Object)), COFFHeader(nullptr),
517 PE32Header(nullptr), PE32PlusHeader(nullptr), DataDirectory(nullptr),
518 SectionTable(nullptr), SymbolTable(nullptr), StringTable(nullptr),
519 StringTableSize(0), ImportDirectory(nullptr), NumberOfImportDirectory(0),
520 ExportDirectory(nullptr) {
521 // Check that we at least have enough room for a header.
522 if (!checkSize(*Data, EC, sizeof(coff_file_header)))
525 // The current location in the file where we are looking at.
528 // PE header is optional and is present only in executables. If it exists,
529 // it is placed right after COFF header.
530 bool HasPEHeader = false;
532 // Check if this is a PE/COFF file.
533 if (base()[0] == 0x4d && base()[1] == 0x5a) {
534 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
535 // PE signature to find 'normal' COFF header.
536 if (!checkSize(*Data, EC, 0x3c + 8))
538 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
539 // Check the PE magic bytes. ("PE\0\0")
540 if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
541 EC = object_error::parse_failed;
544 CurPtr += 4; // Skip the PE magic bytes.
548 if ((EC = getObject(COFFHeader, *Data, base() + CurPtr)))
550 CurPtr += sizeof(coff_file_header);
553 const pe32_header *Header;
554 if ((EC = getObject(Header, *Data, base() + CurPtr)))
557 const uint8_t *DataDirAddr;
558 uint64_t DataDirSize;
559 if (Header->Magic == 0x10b) {
561 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
562 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
563 } else if (Header->Magic == 0x20b) {
564 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
565 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
566 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
568 // It's neither PE32 nor PE32+.
569 EC = object_error::parse_failed;
572 if ((EC = getObject(DataDirectory, *Data, DataDirAddr, DataDirSize)))
574 CurPtr += COFFHeader->SizeOfOptionalHeader;
577 if (COFFHeader->isImportLibrary())
580 if ((EC = getObject(SectionTable, *Data, base() + CurPtr,
581 COFFHeader->NumberOfSections * sizeof(coff_section))))
584 // Initialize the pointer to the symbol table.
585 if (COFFHeader->PointerToSymbolTable != 0)
586 if ((EC = initSymbolTablePtr()))
589 // Initialize the pointer to the beginning of the import table.
590 if ((EC = initImportTablePtr()))
593 // Initialize the pointer to the export table.
594 if ((EC = initExportTablePtr()))
597 EC = object_error::success;
600 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
602 Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
603 return basic_symbol_iterator(SymbolRef(Ret, this));
606 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
607 // The symbol table ends where the string table begins.
609 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
610 return basic_symbol_iterator(SymbolRef(Ret, this));
613 import_directory_iterator COFFObjectFile::import_directory_begin() const {
614 return import_directory_iterator(
615 ImportDirectoryEntryRef(ImportDirectory, 0, this));
618 import_directory_iterator COFFObjectFile::import_directory_end() const {
619 return import_directory_iterator(
620 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
623 export_directory_iterator COFFObjectFile::export_directory_begin() const {
624 return export_directory_iterator(
625 ExportDirectoryEntryRef(ExportDirectory, 0, this));
628 export_directory_iterator COFFObjectFile::export_directory_end() const {
629 if (!ExportDirectory)
630 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
631 ExportDirectoryEntryRef Ref(ExportDirectory,
632 ExportDirectory->AddressTableEntries, this);
633 return export_directory_iterator(Ref);
636 section_iterator COFFObjectFile::section_begin() const {
638 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
639 return section_iterator(SectionRef(Ret, this));
642 section_iterator COFFObjectFile::section_end() const {
644 int NumSections = COFFHeader->isImportLibrary()
645 ? 0 : COFFHeader->NumberOfSections;
646 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
647 return section_iterator(SectionRef(Ret, this));
650 uint8_t COFFObjectFile::getBytesInAddress() const {
651 return getArch() == Triple::x86_64 ? 8 : 4;
654 StringRef COFFObjectFile::getFileFormatName() const {
655 switch(COFFHeader->Machine) {
656 case COFF::IMAGE_FILE_MACHINE_I386:
658 case COFF::IMAGE_FILE_MACHINE_AMD64:
659 return "COFF-x86-64";
660 case COFF::IMAGE_FILE_MACHINE_ARMNT:
663 return "COFF-<unknown arch>";
667 unsigned COFFObjectFile::getArch() const {
668 switch(COFFHeader->Machine) {
669 case COFF::IMAGE_FILE_MACHINE_I386:
671 case COFF::IMAGE_FILE_MACHINE_AMD64:
672 return Triple::x86_64;
673 case COFF::IMAGE_FILE_MACHINE_ARMNT:
674 return Triple::thumb;
676 return Triple::UnknownArch;
680 // This method is kept here because lld uses this. As soon as we make
681 // lld to use getCOFFHeader, this method will be removed.
682 std::error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
683 return getCOFFHeader(Res);
687 COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
689 return object_error::success;
692 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
694 return object_error::success;
698 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
699 Res = PE32PlusHeader;
700 return object_error::success;
704 COFFObjectFile::getDataDirectory(uint32_t Index,
705 const data_directory *&Res) const {
706 // Error if if there's no data directory or the index is out of range.
708 return object_error::parse_failed;
709 assert(PE32Header || PE32PlusHeader);
710 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
711 : PE32PlusHeader->NumberOfRvaAndSize;
713 return object_error::parse_failed;
714 Res = &DataDirectory[Index];
715 return object_error::success;
718 std::error_code COFFObjectFile::getSection(int32_t Index,
719 const coff_section *&Result) const {
720 // Check for special index values.
721 if (COFF::isReservedSectionNumber(Index))
723 else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
724 // We already verified the section table data, so no need to check again.
725 Result = SectionTable + (Index - 1);
727 return object_error::parse_failed;
728 return object_error::success;
731 std::error_code COFFObjectFile::getString(uint32_t Offset,
732 StringRef &Result) const {
733 if (StringTableSize <= 4)
734 // Tried to get a string from an empty string table.
735 return object_error::parse_failed;
736 if (Offset >= StringTableSize)
737 return object_error::unexpected_eof;
738 Result = StringRef(StringTable + Offset);
739 return object_error::success;
742 std::error_code COFFObjectFile::getSymbol(uint32_t Index,
743 const coff_symbol *&Result) const {
744 if (Index < COFFHeader->NumberOfSymbols)
745 Result = SymbolTable + Index;
747 return object_error::parse_failed;
748 return object_error::success;
751 std::error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
752 StringRef &Res) const {
753 // Check for string table entry. First 4 bytes are 0.
754 if (Symbol->Name.Offset.Zeroes == 0) {
755 uint32_t Offset = Symbol->Name.Offset.Offset;
756 if (std::error_code EC = getString(Offset, Res))
758 return object_error::success;
761 if (Symbol->Name.ShortName[7] == 0)
762 // Null terminated, let ::strlen figure out the length.
763 Res = StringRef(Symbol->Name.ShortName);
765 // Not null terminated, use all 8 bytes.
766 Res = StringRef(Symbol->Name.ShortName, 8);
767 return object_error::success;
770 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
771 const coff_symbol *Symbol) const {
772 const uint8_t *Aux = nullptr;
774 if (Symbol->NumberOfAuxSymbols > 0) {
775 // AUX data comes immediately after the symbol in COFF
776 Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
778 // Verify that the Aux symbol points to a valid entry in the symbol table.
779 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
780 if (Offset < COFFHeader->PointerToSymbolTable
781 || Offset >= COFFHeader->PointerToSymbolTable
782 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
783 report_fatal_error("Aux Symbol data was outside of symbol table.");
785 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
786 == 0 && "Aux Symbol data did not point to the beginning of a symbol");
789 return ArrayRef<uint8_t>(Aux,
790 Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
793 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
794 StringRef &Res) const {
796 if (Sec->Name[7] == 0)
797 // Null terminated, let ::strlen figure out the length.
800 // Not null terminated, use all 8 bytes.
801 Name = StringRef(Sec->Name, 8);
803 // Check for string table entry. First byte is '/'.
804 if (Name[0] == '/') {
806 if (Name[1] == '/') {
807 if (decodeBase64StringEntry(Name.substr(2), Offset))
808 return object_error::parse_failed;
810 if (Name.substr(1).getAsInteger(10, Offset))
811 return object_error::parse_failed;
813 if (std::error_code EC = getString(Offset, Name))
818 return object_error::success;
822 COFFObjectFile::getSectionContents(const coff_section *Sec,
823 ArrayRef<uint8_t> &Res) const {
824 // The only thing that we need to verify is that the contents is contained
825 // within the file bounds. We don't need to make sure it doesn't cover other
826 // data, as there's nothing that says that is not allowed.
827 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
828 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
829 if (ConEnd > uintptr_t(Data->getBufferEnd()))
830 return object_error::parse_failed;
831 Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
833 return object_error::success;
836 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
837 return reinterpret_cast<const coff_relocation*>(Rel.p);
840 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
841 Rel.p = reinterpret_cast<uintptr_t>(
842 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
845 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
846 uint64_t &Res) const {
847 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
850 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
851 uint64_t &Res) const {
852 Res = toRel(Rel)->VirtualAddress;
853 return object_error::success;
856 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
857 const coff_relocation* R = toRel(Rel);
859 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
860 return symbol_iterator(SymbolRef(Ref, this));
863 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
864 uint64_t &Res) const {
865 const coff_relocation* R = toRel(Rel);
867 return object_error::success;
871 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
872 return toSec(Section.getRawDataRefImpl());
876 COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
877 return toSymb(Symbol.getRawDataRefImpl());
880 const coff_relocation *
881 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
882 return toRel(Reloc.getRawDataRefImpl());
885 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
886 case COFF::reloc_type: \
891 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
892 SmallVectorImpl<char> &Result) const {
893 const coff_relocation *Reloc = toRel(Rel);
895 switch (COFFHeader->Machine) {
896 case COFF::IMAGE_FILE_MACHINE_AMD64:
897 switch (Reloc->Type) {
898 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
899 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
900 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
901 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
902 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
903 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
904 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
905 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
906 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
907 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
908 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
909 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
910 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
911 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
912 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
913 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
914 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
919 case COFF::IMAGE_FILE_MACHINE_ARMNT:
920 switch (Reloc->Type) {
921 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
922 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
923 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
924 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
925 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
926 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
927 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
928 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
929 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
930 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
931 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
932 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
933 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
934 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
935 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
940 case COFF::IMAGE_FILE_MACHINE_I386:
941 switch (Reloc->Type) {
942 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
943 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
944 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
945 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
946 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
947 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
948 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
949 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
950 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
951 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
952 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
960 Result.append(Res.begin(), Res.end());
961 return object_error::success;
964 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
967 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
968 SmallVectorImpl<char> &Result) const {
969 const coff_relocation *Reloc = toRel(Rel);
970 const coff_symbol *Symb = nullptr;
971 if (std::error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb))
974 Sym.p = reinterpret_cast<uintptr_t>(Symb);
976 if (std::error_code EC = getSymbolName(Sym, SymName))
978 Result.append(SymName.begin(), SymName.end());
979 return object_error::success;
982 bool COFFObjectFile::isRelocatableObject() const {
983 return !DataDirectory;
986 bool ImportDirectoryEntryRef::
987 operator==(const ImportDirectoryEntryRef &Other) const {
988 return ImportTable == Other.ImportTable && Index == Other.Index;
991 void ImportDirectoryEntryRef::moveNext() {
995 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
996 const import_directory_table_entry *&Result) const {
997 Result = ImportTable;
998 return object_error::success;
1001 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1002 uintptr_t IntPtr = 0;
1003 if (std::error_code EC =
1004 OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
1006 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1007 return object_error::success;
1010 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1011 const import_lookup_table_entry32 *&Result) const {
1012 uintptr_t IntPtr = 0;
1013 if (std::error_code EC =
1014 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
1016 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1017 return object_error::success;
1020 bool ExportDirectoryEntryRef::
1021 operator==(const ExportDirectoryEntryRef &Other) const {
1022 return ExportTable == Other.ExportTable && Index == Other.Index;
1025 void ExportDirectoryEntryRef::moveNext() {
1029 // Returns the name of the current export symbol. If the symbol is exported only
1030 // by ordinal, the empty string is set as a result.
1031 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1032 uintptr_t IntPtr = 0;
1033 if (std::error_code EC =
1034 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1036 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1037 return object_error::success;
1040 // Returns the starting ordinal number.
1042 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1043 Result = ExportTable->OrdinalBase;
1044 return object_error::success;
1047 // Returns the export ordinal of the current export symbol.
1048 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1049 Result = ExportTable->OrdinalBase + Index;
1050 return object_error::success;
1053 // Returns the address of the current export symbol.
1054 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1055 uintptr_t IntPtr = 0;
1056 if (std::error_code EC =
1057 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1059 const export_address_table_entry *entry =
1060 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1061 Result = entry[Index].ExportRVA;
1062 return object_error::success;
1065 // Returns the name of the current export symbol. If the symbol is exported only
1066 // by ordinal, the empty string is set as a result.
1068 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1069 uintptr_t IntPtr = 0;
1070 if (std::error_code EC =
1071 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1073 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1075 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1077 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1078 I < E; ++I, ++Offset) {
1081 if (std::error_code EC =
1082 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1084 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1085 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1087 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1088 return object_error::success;
1091 return object_error::success;
1094 ErrorOr<std::unique_ptr<COFFObjectFile>>
1095 ObjectFile::createCOFFObjectFile(std::unique_ptr<MemoryBuffer> Object) {
1097 std::unique_ptr<COFFObjectFile> Ret(
1098 new COFFObjectFile(std::move(Object), EC));
1101 return std::move(Ret);