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 const coff_symbol *COFFObjectFile::toSymb(DataRefImpl Ref) const {
92 const coff_symbol *Addr = reinterpret_cast<const coff_symbol*>(Ref.p);
95 // Verify that the symbol points to a valid entry in the symbol table.
96 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
97 if (Offset < COFFHeader->PointerToSymbolTable
98 || Offset >= COFFHeader->PointerToSymbolTable
99 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
100 report_fatal_error("Symbol was outside of symbol table.");
102 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
103 == 0 && "Symbol did not point to the beginning of a symbol");
109 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
110 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
113 // Verify that the section points to a valid entry in the section table.
114 if (Addr < SectionTable
115 || Addr >= (SectionTable + COFFHeader->NumberOfSections))
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 {
127 const coff_symbol *Symb = toSymb(Ref);
128 Symb += 1 + Symb->NumberOfAuxSymbols;
129 Ref.p = reinterpret_cast<uintptr_t>(Symb);
132 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
133 StringRef &Result) const {
134 const coff_symbol *Symb = toSymb(Ref);
135 return getSymbolName(Symb, Result);
138 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
139 uint64_t &Result) const {
140 const coff_symbol *Symb = toSymb(Ref);
141 const coff_section *Section = nullptr;
142 if (std::error_code EC = getSection(Symb->SectionNumber, Section))
145 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
146 Result = UnknownAddressOrSize;
148 Result = Section->VirtualAddress + Symb->Value;
150 Result = Symb->Value;
151 return object_error::success;
154 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
155 SymbolRef::Type &Result) const {
156 const coff_symbol *Symb = toSymb(Ref);
157 Result = SymbolRef::ST_Other;
158 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
159 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
160 Result = SymbolRef::ST_Unknown;
161 } else if (Symb->isFunctionDefinition()) {
162 Result = SymbolRef::ST_Function;
164 uint32_t Characteristics = 0;
165 if (!COFF::isReservedSectionNumber(Symb->SectionNumber)) {
166 const coff_section *Section = nullptr;
167 if (std::error_code EC = getSection(Symb->SectionNumber, Section))
169 Characteristics = Section->Characteristics;
171 if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
172 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
173 Result = SymbolRef::ST_Data;
175 return object_error::success;
178 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
179 const coff_symbol *Symb = toSymb(Ref);
180 uint32_t Result = SymbolRef::SF_None;
182 // TODO: Correctly set SF_FormatSpecific, SF_Common
184 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
185 if (Symb->Value == 0)
186 Result |= SymbolRef::SF_Undefined;
188 Result |= SymbolRef::SF_Common;
192 // TODO: This are certainly too restrictive.
193 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
194 Result |= SymbolRef::SF_Global;
196 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
197 Result |= SymbolRef::SF_Weak;
199 if (Symb->SectionNumber == COFF::IMAGE_SYM_ABSOLUTE)
200 Result |= SymbolRef::SF_Absolute;
205 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
206 uint64_t &Result) const {
207 // FIXME: Return the correct size. This requires looking at all the symbols
208 // in the same section as this symbol, and looking for either the next
209 // symbol, or the end of the section.
210 const coff_symbol *Symb = toSymb(Ref);
211 const coff_section *Section = nullptr;
212 if (std::error_code EC = getSection(Symb->SectionNumber, Section))
215 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
216 Result = UnknownAddressOrSize;
218 Result = Section->SizeOfRawData - Symb->Value;
221 return object_error::success;
225 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
226 section_iterator &Result) const {
227 const coff_symbol *Symb = toSymb(Ref);
228 if (COFF::isReservedSectionNumber(Symb->SectionNumber)) {
229 Result = section_end();
231 const coff_section *Sec = nullptr;
232 if (std::error_code EC = getSection(Symb->SectionNumber, Sec))
235 Ref.p = reinterpret_cast<uintptr_t>(Sec);
236 Result = section_iterator(SectionRef(Ref, this));
238 return object_error::success;
241 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
242 const coff_section *Sec = toSec(Ref);
244 Ref.p = reinterpret_cast<uintptr_t>(Sec);
247 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
248 StringRef &Result) const {
249 const coff_section *Sec = toSec(Ref);
250 return getSectionName(Sec, Result);
253 std::error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
254 uint64_t &Result) const {
255 const coff_section *Sec = toSec(Ref);
256 Result = Sec->VirtualAddress;
257 return object_error::success;
260 std::error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
261 uint64_t &Result) const {
262 const coff_section *Sec = toSec(Ref);
263 Result = Sec->SizeOfRawData;
264 return object_error::success;
267 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
268 StringRef &Result) const {
269 const coff_section *Sec = toSec(Ref);
270 ArrayRef<uint8_t> Res;
271 std::error_code EC = getSectionContents(Sec, Res);
272 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
276 std::error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
277 uint64_t &Res) const {
278 const coff_section *Sec = toSec(Ref);
280 return object_error::parse_failed;
281 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
282 return object_error::success;
285 std::error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
286 bool &Result) const {
287 const coff_section *Sec = toSec(Ref);
288 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
289 return object_error::success;
292 std::error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
293 bool &Result) const {
294 const coff_section *Sec = toSec(Ref);
295 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
296 return object_error::success;
299 std::error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
300 bool &Result) const {
301 const coff_section *Sec = toSec(Ref);
302 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
303 return object_error::success;
307 COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
308 bool &Result) const {
309 // FIXME: Unimplemented
311 return object_error::success;
314 std::error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
315 bool &Result) const {
316 const coff_section *Sec = toSec(Ref);
317 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
318 return object_error::success;
321 std::error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
322 bool &Result) const {
323 // FIXME: Unimplemented.
325 return object_error::success;
328 std::error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
329 bool &Result) const {
330 // FIXME: Unimplemented.
332 return object_error::success;
335 std::error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
337 bool &Result) const {
338 const coff_section *Sec = toSec(SecRef);
339 const coff_symbol *Symb = toSymb(SymbRef);
340 const coff_section *SymbSec = nullptr;
341 if (std::error_code EC = getSection(Symb->SectionNumber, SymbSec))
347 return object_error::success;
350 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
351 const coff_section *Sec = toSec(Ref);
353 if (Sec->NumberOfRelocations == 0) {
356 auto begin = reinterpret_cast<const coff_relocation*>(
357 base() + Sec->PointerToRelocations);
358 if (Sec->hasExtendedRelocations()) {
359 // Skip the first relocation entry repurposed to store the number of
363 Ret.p = reinterpret_cast<uintptr_t>(begin);
365 return relocation_iterator(RelocationRef(Ret, this));
368 static uint32_t getNumberOfRelocations(const coff_section *Sec,
369 const uint8_t *base) {
370 // The field for the number of relocations in COFF section table is only
371 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
372 // NumberOfRelocations field, and the actual relocation count is stored in the
373 // VirtualAddress field in the first relocation entry.
374 if (Sec->hasExtendedRelocations()) {
375 auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
376 base + Sec->PointerToRelocations);
377 return FirstReloc->VirtualAddress;
379 return Sec->NumberOfRelocations;
382 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
383 const coff_section *Sec = toSec(Ref);
385 if (Sec->NumberOfRelocations == 0) {
388 auto begin = reinterpret_cast<const coff_relocation*>(
389 base() + Sec->PointerToRelocations);
390 uint32_t NumReloc = getNumberOfRelocations(Sec, base());
391 Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
393 return relocation_iterator(RelocationRef(Ret, this));
396 // Initialize the pointer to the symbol table.
397 std::error_code COFFObjectFile::initSymbolTablePtr() {
398 if (std::error_code EC = getObject(
399 SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
400 COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
403 // Find string table. The first four byte of the string table contains the
404 // total size of the string table, including the size field itself. If the
405 // string table is empty, the value of the first four byte would be 4.
406 const uint8_t *StringTableAddr =
407 base() + COFFHeader->PointerToSymbolTable +
408 COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
409 const ulittle32_t *StringTableSizePtr;
410 if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
412 StringTableSize = *StringTableSizePtr;
413 if (std::error_code EC =
414 getObject(StringTable, Data, StringTableAddr, StringTableSize))
417 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
418 // tools like cvtres write a size of 0 for an empty table instead of 4.
419 if (StringTableSize < 4)
422 // Check that the string table is null terminated if has any in it.
423 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
424 return object_error::parse_failed;
425 return object_error::success;
428 // Returns the file offset for the given VA.
429 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
430 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
431 : (uint64_t)PE32PlusHeader->ImageBase;
432 uint64_t Rva = Addr - ImageBase;
433 assert(Rva <= UINT32_MAX);
434 return getRvaPtr((uint32_t)Rva, Res);
437 // Returns the file offset for the given RVA.
438 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
439 for (const SectionRef &S : sections()) {
440 const coff_section *Section = getCOFFSection(S);
441 uint32_t SectionStart = Section->VirtualAddress;
442 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
443 if (SectionStart <= Addr && Addr < SectionEnd) {
444 uint32_t Offset = Addr - SectionStart;
445 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
446 return object_error::success;
449 return object_error::parse_failed;
452 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
454 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
455 StringRef &Name) const {
456 uintptr_t IntPtr = 0;
457 if (std::error_code EC = getRvaPtr(Rva, IntPtr))
459 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
460 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
461 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
462 return object_error::success;
465 // Find the import table.
466 std::error_code COFFObjectFile::initImportTablePtr() {
467 // First, we get the RVA of the import table. If the file lacks a pointer to
468 // the import table, do nothing.
469 const data_directory *DataEntry;
470 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
471 return object_error::success;
473 // Do nothing if the pointer to import table is NULL.
474 if (DataEntry->RelativeVirtualAddress == 0)
475 return object_error::success;
477 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
478 NumberOfImportDirectory = DataEntry->Size /
479 sizeof(import_directory_table_entry);
481 // Find the section that contains the RVA. This is needed because the RVA is
482 // the import table's memory address which is different from its file offset.
483 uintptr_t IntPtr = 0;
484 if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
486 ImportDirectory = reinterpret_cast<
487 const import_directory_table_entry *>(IntPtr);
488 return object_error::success;
491 // Find the export table.
492 std::error_code COFFObjectFile::initExportTablePtr() {
493 // First, we get the RVA of the export table. If the file lacks a pointer to
494 // the export table, do nothing.
495 const data_directory *DataEntry;
496 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
497 return object_error::success;
499 // Do nothing if the pointer to export table is NULL.
500 if (DataEntry->RelativeVirtualAddress == 0)
501 return object_error::success;
503 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
504 uintptr_t IntPtr = 0;
505 if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
508 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
509 return object_error::success;
512 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
513 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
514 PE32Header(nullptr), PE32PlusHeader(nullptr), DataDirectory(nullptr),
515 SectionTable(nullptr), SymbolTable(nullptr), StringTable(nullptr),
516 StringTableSize(0), ImportDirectory(nullptr), NumberOfImportDirectory(0),
517 ExportDirectory(nullptr) {
518 // Check that we at least have enough room for a header.
519 if (!checkSize(Data, EC, sizeof(coff_file_header)))
522 // The current location in the file where we are looking at.
525 // PE header is optional and is present only in executables. If it exists,
526 // it is placed right after COFF header.
527 bool HasPEHeader = false;
529 // Check if this is a PE/COFF file.
530 if (base()[0] == 0x4d && base()[1] == 0x5a) {
531 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
532 // PE signature to find 'normal' COFF header.
533 if (!checkSize(Data, EC, 0x3c + 8))
535 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
536 // Check the PE magic bytes. ("PE\0\0")
537 if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
538 EC = object_error::parse_failed;
541 CurPtr += 4; // Skip the PE magic bytes.
545 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
547 CurPtr += sizeof(coff_file_header);
550 const pe32_header *Header;
551 if ((EC = getObject(Header, Data, base() + CurPtr)))
554 const uint8_t *DataDirAddr;
555 uint64_t DataDirSize;
556 if (Header->Magic == 0x10b) {
558 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
559 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
560 } else if (Header->Magic == 0x20b) {
561 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
562 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
563 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
565 // It's neither PE32 nor PE32+.
566 EC = object_error::parse_failed;
569 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
571 CurPtr += COFFHeader->SizeOfOptionalHeader;
574 if (COFFHeader->isImportLibrary())
577 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
578 COFFHeader->NumberOfSections * sizeof(coff_section))))
581 // Initialize the pointer to the symbol table.
582 if (COFFHeader->PointerToSymbolTable != 0)
583 if ((EC = initSymbolTablePtr()))
586 // Initialize the pointer to the beginning of the import table.
587 if ((EC = initImportTablePtr()))
590 // Initialize the pointer to the export table.
591 if ((EC = initExportTablePtr()))
594 EC = object_error::success;
597 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
599 Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
600 return basic_symbol_iterator(SymbolRef(Ret, this));
603 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
604 // The symbol table ends where the string table begins.
606 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
607 return basic_symbol_iterator(SymbolRef(Ret, this));
610 import_directory_iterator COFFObjectFile::import_directory_begin() const {
611 return import_directory_iterator(
612 ImportDirectoryEntryRef(ImportDirectory, 0, this));
615 import_directory_iterator COFFObjectFile::import_directory_end() const {
616 return import_directory_iterator(
617 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
620 export_directory_iterator COFFObjectFile::export_directory_begin() const {
621 return export_directory_iterator(
622 ExportDirectoryEntryRef(ExportDirectory, 0, this));
625 export_directory_iterator COFFObjectFile::export_directory_end() const {
626 if (!ExportDirectory)
627 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
628 ExportDirectoryEntryRef Ref(ExportDirectory,
629 ExportDirectory->AddressTableEntries, this);
630 return export_directory_iterator(Ref);
633 section_iterator COFFObjectFile::section_begin() const {
635 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
636 return section_iterator(SectionRef(Ret, this));
639 section_iterator COFFObjectFile::section_end() const {
641 int NumSections = COFFHeader->isImportLibrary()
642 ? 0 : COFFHeader->NumberOfSections;
643 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
644 return section_iterator(SectionRef(Ret, this));
647 uint8_t COFFObjectFile::getBytesInAddress() const {
648 return getArch() == Triple::x86_64 ? 8 : 4;
651 StringRef COFFObjectFile::getFileFormatName() const {
652 switch(COFFHeader->Machine) {
653 case COFF::IMAGE_FILE_MACHINE_I386:
655 case COFF::IMAGE_FILE_MACHINE_AMD64:
656 return "COFF-x86-64";
657 case COFF::IMAGE_FILE_MACHINE_ARMNT:
660 return "COFF-<unknown arch>";
664 unsigned COFFObjectFile::getArch() const {
665 switch(COFFHeader->Machine) {
666 case COFF::IMAGE_FILE_MACHINE_I386:
668 case COFF::IMAGE_FILE_MACHINE_AMD64:
669 return Triple::x86_64;
670 case COFF::IMAGE_FILE_MACHINE_ARMNT:
671 return Triple::thumb;
673 return Triple::UnknownArch;
677 // This method is kept here because lld uses this. As soon as we make
678 // lld to use getCOFFHeader, this method will be removed.
679 std::error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
680 return getCOFFHeader(Res);
684 COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
686 return object_error::success;
689 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
691 return object_error::success;
695 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
696 Res = PE32PlusHeader;
697 return object_error::success;
701 COFFObjectFile::getDataDirectory(uint32_t Index,
702 const data_directory *&Res) const {
703 // Error if if there's no data directory or the index is out of range.
705 return object_error::parse_failed;
706 assert(PE32Header || PE32PlusHeader);
707 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
708 : PE32PlusHeader->NumberOfRvaAndSize;
710 return object_error::parse_failed;
711 Res = &DataDirectory[Index];
712 return object_error::success;
715 std::error_code COFFObjectFile::getSection(int32_t Index,
716 const coff_section *&Result) const {
717 // Check for special index values.
718 if (COFF::isReservedSectionNumber(Index))
720 else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
721 // We already verified the section table data, so no need to check again.
722 Result = SectionTable + (Index - 1);
724 return object_error::parse_failed;
725 return object_error::success;
728 std::error_code COFFObjectFile::getString(uint32_t Offset,
729 StringRef &Result) const {
730 if (StringTableSize <= 4)
731 // Tried to get a string from an empty string table.
732 return object_error::parse_failed;
733 if (Offset >= StringTableSize)
734 return object_error::unexpected_eof;
735 Result = StringRef(StringTable + Offset);
736 return object_error::success;
739 std::error_code COFFObjectFile::getSymbol(uint32_t Index,
740 const coff_symbol *&Result) const {
741 if (Index < COFFHeader->NumberOfSymbols)
742 Result = SymbolTable + Index;
744 return object_error::parse_failed;
745 return object_error::success;
748 std::error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
749 StringRef &Res) const {
750 // Check for string table entry. First 4 bytes are 0.
751 if (Symbol->Name.Offset.Zeroes == 0) {
752 uint32_t Offset = Symbol->Name.Offset.Offset;
753 if (std::error_code EC = getString(Offset, Res))
755 return object_error::success;
758 if (Symbol->Name.ShortName[7] == 0)
759 // Null terminated, let ::strlen figure out the length.
760 Res = StringRef(Symbol->Name.ShortName);
762 // Not null terminated, use all 8 bytes.
763 Res = StringRef(Symbol->Name.ShortName, 8);
764 return object_error::success;
767 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
768 const coff_symbol *Symbol) const {
769 const uint8_t *Aux = nullptr;
771 if (Symbol->NumberOfAuxSymbols > 0) {
772 // AUX data comes immediately after the symbol in COFF
773 Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
775 // Verify that the Aux symbol points to a valid entry in the symbol table.
776 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
777 if (Offset < COFFHeader->PointerToSymbolTable
778 || Offset >= COFFHeader->PointerToSymbolTable
779 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
780 report_fatal_error("Aux Symbol data was outside of symbol table.");
782 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
783 == 0 && "Aux Symbol data did not point to the beginning of a symbol");
786 return makeArrayRef(Aux, Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
789 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
790 StringRef &Res) const {
792 if (Sec->Name[7] == 0)
793 // Null terminated, let ::strlen figure out the length.
796 // Not null terminated, use all 8 bytes.
797 Name = StringRef(Sec->Name, 8);
799 // Check for string table entry. First byte is '/'.
800 if (Name[0] == '/') {
802 if (Name[1] == '/') {
803 if (decodeBase64StringEntry(Name.substr(2), Offset))
804 return object_error::parse_failed;
806 if (Name.substr(1).getAsInteger(10, Offset))
807 return object_error::parse_failed;
809 if (std::error_code EC = getString(Offset, Name))
814 return object_error::success;
818 COFFObjectFile::getSectionContents(const coff_section *Sec,
819 ArrayRef<uint8_t> &Res) const {
820 // The only thing that we need to verify is that the contents is contained
821 // within the file bounds. We don't need to make sure it doesn't cover other
822 // data, as there's nothing that says that is not allowed.
823 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
824 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
825 if (ConEnd > uintptr_t(Data.getBufferEnd()))
826 return object_error::parse_failed;
827 Res = makeArrayRef(reinterpret_cast<const uint8_t*>(ConStart),
829 return object_error::success;
832 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
833 return reinterpret_cast<const coff_relocation*>(Rel.p);
836 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
837 Rel.p = reinterpret_cast<uintptr_t>(
838 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
841 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
842 uint64_t &Res) const {
843 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
846 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
847 uint64_t &Res) const {
848 Res = toRel(Rel)->VirtualAddress;
849 return object_error::success;
852 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
853 const coff_relocation* R = toRel(Rel);
855 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
856 return symbol_iterator(SymbolRef(Ref, this));
859 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
860 uint64_t &Res) const {
861 const coff_relocation* R = toRel(Rel);
863 return object_error::success;
867 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
868 return toSec(Section.getRawDataRefImpl());
872 COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
873 return toSymb(Symbol.getRawDataRefImpl());
876 const coff_relocation *
877 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
878 return toRel(Reloc.getRawDataRefImpl());
881 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
882 case COFF::reloc_type: \
887 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
888 SmallVectorImpl<char> &Result) const {
889 const coff_relocation *Reloc = toRel(Rel);
891 switch (COFFHeader->Machine) {
892 case COFF::IMAGE_FILE_MACHINE_AMD64:
893 switch (Reloc->Type) {
894 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
895 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
896 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
897 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
898 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
899 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
900 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
901 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
902 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
903 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
904 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
905 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
906 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
907 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
908 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
909 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
910 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
915 case COFF::IMAGE_FILE_MACHINE_ARMNT:
916 switch (Reloc->Type) {
917 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
918 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
919 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
920 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
921 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
922 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
923 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
924 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
925 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
926 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
927 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
928 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
929 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
930 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
931 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
936 case COFF::IMAGE_FILE_MACHINE_I386:
937 switch (Reloc->Type) {
938 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
939 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
940 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
941 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
942 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
943 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
944 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
945 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
946 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
947 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
948 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
956 Result.append(Res.begin(), Res.end());
957 return object_error::success;
960 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
963 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
964 SmallVectorImpl<char> &Result) const {
965 const coff_relocation *Reloc = toRel(Rel);
966 const coff_symbol *Symb = nullptr;
967 if (std::error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb))
970 Sym.p = reinterpret_cast<uintptr_t>(Symb);
972 if (std::error_code EC = getSymbolName(Sym, SymName))
974 Result.append(SymName.begin(), SymName.end());
975 return object_error::success;
978 bool COFFObjectFile::isRelocatableObject() const {
979 return !DataDirectory;
982 bool ImportDirectoryEntryRef::
983 operator==(const ImportDirectoryEntryRef &Other) const {
984 return ImportTable == Other.ImportTable && Index == Other.Index;
987 void ImportDirectoryEntryRef::moveNext() {
991 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
992 const import_directory_table_entry *&Result) const {
993 Result = ImportTable;
994 return object_error::success;
997 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
998 uintptr_t IntPtr = 0;
999 if (std::error_code EC =
1000 OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
1002 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1003 return object_error::success;
1006 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1007 const import_lookup_table_entry32 *&Result) const {
1008 uintptr_t IntPtr = 0;
1009 if (std::error_code EC =
1010 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
1012 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1013 return object_error::success;
1016 bool ExportDirectoryEntryRef::
1017 operator==(const ExportDirectoryEntryRef &Other) const {
1018 return ExportTable == Other.ExportTable && Index == Other.Index;
1021 void ExportDirectoryEntryRef::moveNext() {
1025 // Returns the name of the current export symbol. If the symbol is exported only
1026 // by ordinal, the empty string is set as a result.
1027 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1028 uintptr_t IntPtr = 0;
1029 if (std::error_code EC =
1030 OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1032 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1033 return object_error::success;
1036 // Returns the starting ordinal number.
1038 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1039 Result = ExportTable->OrdinalBase;
1040 return object_error::success;
1043 // Returns the export ordinal of the current export symbol.
1044 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1045 Result = ExportTable->OrdinalBase + Index;
1046 return object_error::success;
1049 // Returns the address of the current export symbol.
1050 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1051 uintptr_t IntPtr = 0;
1052 if (std::error_code EC =
1053 OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1055 const export_address_table_entry *entry =
1056 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1057 Result = entry[Index].ExportRVA;
1058 return object_error::success;
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.
1064 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1065 uintptr_t IntPtr = 0;
1066 if (std::error_code EC =
1067 OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1069 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1071 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1073 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1074 I < E; ++I, ++Offset) {
1077 if (std::error_code EC =
1078 OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1080 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1081 if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1083 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1084 return object_error::success;
1087 return object_error::success;
1090 ErrorOr<std::unique_ptr<COFFObjectFile>>
1091 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1093 std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1096 return std::move(Ret);