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;
27 using std::error_code;
29 using support::ulittle8_t;
30 using support::ulittle16_t;
31 using support::ulittle32_t;
32 using support::little16_t;
34 // Returns false if size is greater than the buffer size. And sets ec.
35 static bool checkSize(const MemoryBuffer *M, error_code &EC, uint64_t Size) {
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 error_code getObject(const T *&Obj, const MemoryBuffer *M,
47 const uint8_t *Ptr, const size_t Size = sizeof(T)) {
48 uintptr_t Addr = uintptr_t(Ptr);
49 if (Addr + Size < Addr ||
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 error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
134 StringRef &Result) const {
135 const coff_symbol *Symb = toSymb(Ref);
136 return getSymbolName(Symb, Result);
139 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 (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 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 (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 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 (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;
225 error_code 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 (error_code EC = getSection(Symb->SectionNumber, Sec)) return EC;
234 Ref.p = reinterpret_cast<uintptr_t>(Sec);
235 Result = section_iterator(SectionRef(Ref, this));
237 return object_error::success;
240 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
241 const coff_section *Sec = toSec(Ref);
243 Ref.p = reinterpret_cast<uintptr_t>(Sec);
246 error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
247 StringRef &Result) const {
248 const coff_section *Sec = toSec(Ref);
249 return getSectionName(Sec, Result);
252 error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
253 uint64_t &Result) const {
254 const coff_section *Sec = toSec(Ref);
255 Result = Sec->VirtualAddress;
256 return object_error::success;
259 error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
260 uint64_t &Result) const {
261 const coff_section *Sec = toSec(Ref);
262 Result = Sec->SizeOfRawData;
263 return object_error::success;
266 error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
267 StringRef &Result) const {
268 const coff_section *Sec = toSec(Ref);
269 ArrayRef<uint8_t> Res;
270 error_code EC = getSectionContents(Sec, Res);
271 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
275 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
276 uint64_t &Res) const {
277 const coff_section *Sec = toSec(Ref);
279 return object_error::parse_failed;
280 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
281 return object_error::success;
284 error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
285 bool &Result) const {
286 const coff_section *Sec = toSec(Ref);
287 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
288 return object_error::success;
291 error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
292 bool &Result) const {
293 const coff_section *Sec = toSec(Ref);
294 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
295 return object_error::success;
298 error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
299 bool &Result) const {
300 const coff_section *Sec = toSec(Ref);
301 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
302 return object_error::success;
305 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
306 bool &Result) const {
307 // FIXME: Unimplemented
309 return object_error::success;
312 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
313 bool &Result) const {
314 const coff_section *Sec = toSec(Ref);
315 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
316 return object_error::success;
319 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
320 bool &Result) const {
321 // FIXME: Unimplemented.
323 return object_error::success;
326 error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
327 bool &Result) const {
328 // FIXME: Unimplemented.
330 return object_error::success;
333 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
335 bool &Result) const {
336 const coff_section *Sec = toSec(SecRef);
337 const coff_symbol *Symb = toSymb(SymbRef);
338 const coff_section *SymbSec = nullptr;
339 if (error_code EC = getSection(Symb->SectionNumber, SymbSec)) return EC;
344 return object_error::success;
347 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
348 const coff_section *Sec = toSec(Ref);
350 if (Sec->NumberOfRelocations == 0) {
353 auto begin = reinterpret_cast<const coff_relocation*>(
354 base() + Sec->PointerToRelocations);
355 if (Sec->hasExtendedRelocations()) {
356 // Skip the first relocation entry repurposed to store the number of
360 Ret.p = reinterpret_cast<uintptr_t>(begin);
362 return relocation_iterator(RelocationRef(Ret, this));
365 static uint32_t getNumberOfRelocations(const coff_section *Sec,
366 const uint8_t *base) {
367 // The field for the number of relocations in COFF section table is only
368 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
369 // NumberOfRelocations field, and the actual relocation count is stored in the
370 // VirtualAddress field in the first relocation entry.
371 if (Sec->hasExtendedRelocations()) {
372 auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
373 base + Sec->PointerToRelocations);
374 return FirstReloc->VirtualAddress;
376 return Sec->NumberOfRelocations;
379 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
380 const coff_section *Sec = toSec(Ref);
382 if (Sec->NumberOfRelocations == 0) {
385 auto begin = reinterpret_cast<const coff_relocation*>(
386 base() + Sec->PointerToRelocations);
387 uint32_t NumReloc = getNumberOfRelocations(Sec, base());
388 Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
390 return relocation_iterator(RelocationRef(Ret, this));
393 // Initialize the pointer to the symbol table.
394 error_code COFFObjectFile::initSymbolTablePtr() {
395 if (error_code EC = getObject(
396 SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
397 COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
400 // Find string table. The first four byte of the string table contains the
401 // total size of the string table, including the size field itself. If the
402 // string table is empty, the value of the first four byte would be 4.
403 const uint8_t *StringTableAddr =
404 base() + COFFHeader->PointerToSymbolTable +
405 COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
406 const ulittle32_t *StringTableSizePtr;
407 if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
409 StringTableSize = *StringTableSizePtr;
411 getObject(StringTable, Data, StringTableAddr, StringTableSize))
414 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
415 // tools like cvtres write a size of 0 for an empty table instead of 4.
416 if (StringTableSize < 4)
419 // Check that the string table is null terminated if has any in it.
420 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
421 return object_error::parse_failed;
422 return object_error::success;
425 // Returns the file offset for the given VA.
426 error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
427 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
428 : (uint64_t)PE32PlusHeader->ImageBase;
429 uint64_t Rva = Addr - ImageBase;
430 assert(Rva <= UINT32_MAX);
431 return getRvaPtr((uint32_t)Rva, Res);
434 // Returns the file offset for the given RVA.
435 error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
436 for (const SectionRef &S : sections()) {
437 const coff_section *Section = getCOFFSection(S);
438 uint32_t SectionStart = Section->VirtualAddress;
439 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
440 if (SectionStart <= Addr && Addr < SectionEnd) {
441 uint32_t Offset = Addr - SectionStart;
442 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
443 return object_error::success;
446 return object_error::parse_failed;
449 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
451 error_code COFFObjectFile::
452 getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const {
453 uintptr_t IntPtr = 0;
454 if (error_code EC = getRvaPtr(Rva, IntPtr))
456 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
457 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
458 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
459 return object_error::success;
462 // Find the import table.
463 error_code COFFObjectFile::initImportTablePtr() {
464 // First, we get the RVA of the import table. If the file lacks a pointer to
465 // the import table, do nothing.
466 const data_directory *DataEntry;
467 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
468 return object_error::success;
470 // Do nothing if the pointer to import table is NULL.
471 if (DataEntry->RelativeVirtualAddress == 0)
472 return object_error::success;
474 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
475 NumberOfImportDirectory = DataEntry->Size /
476 sizeof(import_directory_table_entry);
478 // Find the section that contains the RVA. This is needed because the RVA is
479 // the import table's memory address which is different from its file offset.
480 uintptr_t IntPtr = 0;
481 if (error_code EC = getRvaPtr(ImportTableRva, IntPtr))
483 ImportDirectory = reinterpret_cast<
484 const import_directory_table_entry *>(IntPtr);
485 return object_error::success;
488 // Find the export table.
489 error_code COFFObjectFile::initExportTablePtr() {
490 // First, we get the RVA of the export table. If the file lacks a pointer to
491 // the export table, do nothing.
492 const data_directory *DataEntry;
493 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
494 return object_error::success;
496 // Do nothing if the pointer to export table is NULL.
497 if (DataEntry->RelativeVirtualAddress == 0)
498 return object_error::success;
500 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
501 uintptr_t IntPtr = 0;
502 if (error_code EC = getRvaPtr(ExportTableRva, IntPtr))
505 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
506 return object_error::success;
509 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC,
511 : ObjectFile(Binary::ID_COFF, Object, BufferOwned), COFFHeader(nullptr),
512 PE32Header(nullptr), PE32PlusHeader(nullptr), DataDirectory(nullptr),
513 SectionTable(nullptr), SymbolTable(nullptr), StringTable(nullptr),
514 StringTableSize(0), ImportDirectory(nullptr), NumberOfImportDirectory(0),
515 ExportDirectory(nullptr) {
516 // Check that we at least have enough room for a header.
517 if (!checkSize(Data, EC, sizeof(coff_file_header))) return;
519 // The current location in the file where we are looking at.
522 // PE header is optional and is present only in executables. If it exists,
523 // it is placed right after COFF header.
524 bool HasPEHeader = false;
526 // Check if this is a PE/COFF file.
527 if (base()[0] == 0x4d && base()[1] == 0x5a) {
528 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
529 // PE signature to find 'normal' COFF header.
530 if (!checkSize(Data, EC, 0x3c + 8)) return;
531 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
532 // Check the PE magic bytes. ("PE\0\0")
533 if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
534 EC = object_error::parse_failed;
537 CurPtr += 4; // Skip the PE magic bytes.
541 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
543 CurPtr += sizeof(coff_file_header);
546 const pe32_header *Header;
547 if ((EC = getObject(Header, Data, base() + CurPtr)))
550 const uint8_t *DataDirAddr;
551 uint64_t DataDirSize;
552 if (Header->Magic == 0x10b) {
554 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
555 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
556 } else if (Header->Magic == 0x20b) {
557 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
558 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
559 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
561 // It's neither PE32 nor PE32+.
562 EC = object_error::parse_failed;
565 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
567 CurPtr += COFFHeader->SizeOfOptionalHeader;
570 if (COFFHeader->isImportLibrary())
573 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
574 COFFHeader->NumberOfSections * sizeof(coff_section))))
577 // Initialize the pointer to the symbol table.
578 if (COFFHeader->PointerToSymbolTable != 0)
579 if ((EC = initSymbolTablePtr()))
582 // Initialize the pointer to the beginning of the import table.
583 if ((EC = initImportTablePtr()))
586 // Initialize the pointer to the export table.
587 if ((EC = initExportTablePtr()))
590 EC = object_error::success;
593 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
595 Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
596 return basic_symbol_iterator(SymbolRef(Ret, this));
599 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
600 // The symbol table ends where the string table begins.
602 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
603 return basic_symbol_iterator(SymbolRef(Ret, this));
606 library_iterator COFFObjectFile::needed_library_begin() const {
608 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
611 library_iterator COFFObjectFile::needed_library_end() const {
613 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
616 StringRef COFFObjectFile::getLoadName() const {
617 // COFF does not have this field.
621 import_directory_iterator COFFObjectFile::import_directory_begin() const {
622 return import_directory_iterator(
623 ImportDirectoryEntryRef(ImportDirectory, 0, this));
626 import_directory_iterator COFFObjectFile::import_directory_end() const {
627 return import_directory_iterator(
628 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
631 export_directory_iterator COFFObjectFile::export_directory_begin() const {
632 return export_directory_iterator(
633 ExportDirectoryEntryRef(ExportDirectory, 0, this));
636 export_directory_iterator COFFObjectFile::export_directory_end() const {
637 if (!ExportDirectory)
638 return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
639 ExportDirectoryEntryRef Ref(ExportDirectory,
640 ExportDirectory->AddressTableEntries, this);
641 return export_directory_iterator(Ref);
644 section_iterator COFFObjectFile::section_begin() const {
646 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
647 return section_iterator(SectionRef(Ret, this));
650 section_iterator COFFObjectFile::section_end() const {
652 int NumSections = COFFHeader->isImportLibrary()
653 ? 0 : COFFHeader->NumberOfSections;
654 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
655 return section_iterator(SectionRef(Ret, this));
658 uint8_t COFFObjectFile::getBytesInAddress() const {
659 return getArch() == Triple::x86_64 ? 8 : 4;
662 StringRef COFFObjectFile::getFileFormatName() const {
663 switch(COFFHeader->Machine) {
664 case COFF::IMAGE_FILE_MACHINE_I386:
666 case COFF::IMAGE_FILE_MACHINE_AMD64:
667 return "COFF-x86-64";
668 case COFF::IMAGE_FILE_MACHINE_ARMNT:
671 return "COFF-<unknown arch>";
675 unsigned COFFObjectFile::getArch() const {
676 switch(COFFHeader->Machine) {
677 case COFF::IMAGE_FILE_MACHINE_I386:
679 case COFF::IMAGE_FILE_MACHINE_AMD64:
680 return Triple::x86_64;
681 case COFF::IMAGE_FILE_MACHINE_ARMNT:
682 return Triple::thumb;
684 return Triple::UnknownArch;
688 // This method is kept here because lld uses this. As soon as we make
689 // lld to use getCOFFHeader, this method will be removed.
690 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
691 return getCOFFHeader(Res);
694 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
696 return object_error::success;
699 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
701 return object_error::success;
705 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
706 Res = PE32PlusHeader;
707 return object_error::success;
710 error_code COFFObjectFile::getDataDirectory(uint32_t Index,
711 const data_directory *&Res) const {
712 // Error if if there's no data directory or the index is out of range.
714 return object_error::parse_failed;
715 assert(PE32Header || PE32PlusHeader);
716 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
717 : PE32PlusHeader->NumberOfRvaAndSize;
719 return object_error::parse_failed;
720 Res = &DataDirectory[Index];
721 return object_error::success;
724 error_code COFFObjectFile::getSection(int32_t Index,
725 const coff_section *&Result) const {
726 // Check for special index values.
727 if (COFF::isReservedSectionNumber(Index))
729 else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
730 // We already verified the section table data, so no need to check again.
731 Result = SectionTable + (Index - 1);
733 return object_error::parse_failed;
734 return object_error::success;
737 error_code COFFObjectFile::getString(uint32_t Offset,
738 StringRef &Result) const {
739 if (StringTableSize <= 4)
740 // Tried to get a string from an empty string table.
741 return object_error::parse_failed;
742 if (Offset >= StringTableSize)
743 return object_error::unexpected_eof;
744 Result = StringRef(StringTable + Offset);
745 return object_error::success;
748 error_code COFFObjectFile::getSymbol(uint32_t Index,
749 const coff_symbol *&Result) const {
750 if (Index < COFFHeader->NumberOfSymbols)
751 Result = SymbolTable + Index;
753 return object_error::parse_failed;
754 return object_error::success;
757 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
758 StringRef &Res) const {
759 // Check for string table entry. First 4 bytes are 0.
760 if (Symbol->Name.Offset.Zeroes == 0) {
761 uint32_t Offset = Symbol->Name.Offset.Offset;
762 if (error_code EC = getString(Offset, Res))
764 return object_error::success;
767 if (Symbol->Name.ShortName[7] == 0)
768 // Null terminated, let ::strlen figure out the length.
769 Res = StringRef(Symbol->Name.ShortName);
771 // Not null terminated, use all 8 bytes.
772 Res = StringRef(Symbol->Name.ShortName, 8);
773 return object_error::success;
776 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
777 const coff_symbol *Symbol) const {
778 const uint8_t *Aux = nullptr;
780 if (Symbol->NumberOfAuxSymbols > 0) {
781 // AUX data comes immediately after the symbol in COFF
782 Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
784 // Verify that the Aux symbol points to a valid entry in the symbol table.
785 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
786 if (Offset < COFFHeader->PointerToSymbolTable
787 || Offset >= COFFHeader->PointerToSymbolTable
788 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
789 report_fatal_error("Aux Symbol data was outside of symbol table.");
791 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
792 == 0 && "Aux Symbol data did not point to the beginning of a symbol");
795 return ArrayRef<uint8_t>(Aux,
796 Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
799 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
800 StringRef &Res) const {
802 if (Sec->Name[7] == 0)
803 // Null terminated, let ::strlen figure out the length.
806 // Not null terminated, use all 8 bytes.
807 Name = StringRef(Sec->Name, 8);
809 // Check for string table entry. First byte is '/'.
810 if (Name[0] == '/') {
812 if (Name[1] == '/') {
813 if (decodeBase64StringEntry(Name.substr(2), Offset))
814 return object_error::parse_failed;
816 if (Name.substr(1).getAsInteger(10, Offset))
817 return object_error::parse_failed;
819 if (error_code EC = getString(Offset, Name))
824 return object_error::success;
827 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
828 ArrayRef<uint8_t> &Res) const {
829 // The only thing that we need to verify is that the contents is contained
830 // within the file bounds. We don't need to make sure it doesn't cover other
831 // data, as there's nothing that says that is not allowed.
832 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
833 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
834 if (ConEnd > uintptr_t(Data->getBufferEnd()))
835 return object_error::parse_failed;
836 Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
838 return object_error::success;
841 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
842 return reinterpret_cast<const coff_relocation*>(Rel.p);
845 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
846 Rel.p = reinterpret_cast<uintptr_t>(
847 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
850 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
851 uint64_t &Res) const {
852 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
855 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
856 uint64_t &Res) const {
857 Res = toRel(Rel)->VirtualAddress;
858 return object_error::success;
861 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
862 const coff_relocation* R = toRel(Rel);
864 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
865 return symbol_iterator(SymbolRef(Ref, this));
868 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
869 uint64_t &Res) const {
870 const coff_relocation* R = toRel(Rel);
872 return object_error::success;
876 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
877 return toSec(Section.getRawDataRefImpl());
881 COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
882 return toSymb(Symbol.getRawDataRefImpl());
885 const coff_relocation *
886 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
887 return toRel(Reloc.getRawDataRefImpl());
890 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
891 case COFF::reloc_type: \
895 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
896 SmallVectorImpl<char> &Result) const {
897 const coff_relocation *Reloc = toRel(Rel);
899 switch (COFFHeader->Machine) {
900 case COFF::IMAGE_FILE_MACHINE_AMD64:
901 switch (Reloc->Type) {
902 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
903 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
904 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
905 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
906 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
907 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
908 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
909 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
910 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
911 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
912 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
913 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
914 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
915 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
916 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
917 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
918 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
923 case COFF::IMAGE_FILE_MACHINE_ARMNT:
924 switch (Reloc->Type) {
925 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
926 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
927 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
928 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
929 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
930 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
931 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
932 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
933 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
934 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
935 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
936 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
937 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
938 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
939 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
944 case COFF::IMAGE_FILE_MACHINE_I386:
945 switch (Reloc->Type) {
946 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
947 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
948 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
949 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
950 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
951 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
952 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
953 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
954 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
955 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
956 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
964 Result.append(Res.begin(), Res.end());
965 return object_error::success;
968 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
970 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
971 SmallVectorImpl<char> &Result) const {
972 const coff_relocation *Reloc = toRel(Rel);
973 const coff_symbol *Symb = nullptr;
974 if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
976 Sym.p = reinterpret_cast<uintptr_t>(Symb);
978 if (error_code EC = getSymbolName(Sym, SymName)) return EC;
979 Result.append(SymName.begin(), SymName.end());
980 return object_error::success;
983 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
984 LibraryRef &Result) const {
985 report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
988 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
989 StringRef &Result) const {
990 report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
993 bool ImportDirectoryEntryRef::
994 operator==(const ImportDirectoryEntryRef &Other) const {
995 return ImportTable == Other.ImportTable && Index == Other.Index;
998 void ImportDirectoryEntryRef::moveNext() {
1002 error_code ImportDirectoryEntryRef::
1003 getImportTableEntry(const import_directory_table_entry *&Result) const {
1004 Result = ImportTable;
1005 return object_error::success;
1008 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1009 uintptr_t IntPtr = 0;
1010 if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
1012 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1013 return object_error::success;
1016 error_code ImportDirectoryEntryRef::getImportLookupEntry(
1017 const import_lookup_table_entry32 *&Result) const {
1018 uintptr_t IntPtr = 0;
1020 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
1022 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1023 return object_error::success;
1026 bool ExportDirectoryEntryRef::
1027 operator==(const ExportDirectoryEntryRef &Other) const {
1028 return ExportTable == Other.ExportTable && Index == Other.Index;
1031 void ExportDirectoryEntryRef::moveNext() {
1035 // Returns the name of the current export symbol. If the symbol is exported only
1036 // by ordinal, the empty string is set as a result.
1037 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1038 uintptr_t IntPtr = 0;
1039 if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1041 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1042 return object_error::success;
1045 // Returns the starting ordinal number.
1046 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1047 Result = ExportTable->OrdinalBase;
1048 return object_error::success;
1051 // Returns the export ordinal of the current export symbol.
1052 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1053 Result = ExportTable->OrdinalBase + Index;
1054 return object_error::success;
1057 // Returns the address of the current export symbol.
1058 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1059 uintptr_t IntPtr = 0;
1060 if (error_code EC = OwningObject->getRvaPtr(
1061 ExportTable->ExportAddressTableRVA, IntPtr))
1063 const export_address_table_entry *entry =
1064 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1065 Result = entry[Index].ExportRVA;
1066 return object_error::success;
1069 // Returns the name of the current export symbol. If the symbol is exported only
1070 // by ordinal, the empty string is set as a result.
1071 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1072 uintptr_t IntPtr = 0;
1073 if (error_code EC = OwningObject->getRvaPtr(
1074 ExportTable->OrdinalTableRVA, IntPtr))
1076 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1078 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1080 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1081 I < E; ++I, ++Offset) {
1084 if (error_code EC = OwningObject->getRvaPtr(
1085 ExportTable->NamePointerRVA, IntPtr))
1087 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1088 if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1090 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1091 return object_error::success;
1094 return object_error::success;
1097 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object,
1100 std::unique_ptr<COFFObjectFile> Ret(
1101 new COFFObjectFile(Object, EC, BufferOwned));
1104 return Ret.release();