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, 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 error_code getObject(const T *&Obj, const MemoryBuffer *M,
46 const uint8_t *Ptr, const size_t Size = sizeof(T)) {
47 uintptr_t Addr = uintptr_t(Ptr);
48 if (Addr + Size < Addr ||
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 error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
133 StringRef &Result) const {
134 const coff_symbol *Symb = toSymb(Ref);
135 return getSymbolName(Symb, Result);
138 error_code COFFObjectFile::getSymbolFileOffset(DataRefImpl Ref,
139 uint64_t &Result) const {
140 const coff_symbol *Symb = toSymb(Ref);
141 const coff_section *Section = NULL;
142 if (error_code EC = getSection(Symb->SectionNumber, Section))
145 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
146 Result = UnknownAddressOrSize;
148 Result = Section->PointerToRawData + Symb->Value;
150 Result = Symb->Value;
151 return object_error::success;
154 error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
155 uint64_t &Result) const {
156 const coff_symbol *Symb = toSymb(Ref);
157 const coff_section *Section = NULL;
158 if (error_code EC = getSection(Symb->SectionNumber, Section))
161 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
162 Result = UnknownAddressOrSize;
164 Result = Section->VirtualAddress + Symb->Value;
166 Result = Symb->Value;
167 return object_error::success;
170 error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
171 SymbolRef::Type &Result) const {
172 const coff_symbol *Symb = toSymb(Ref);
173 Result = SymbolRef::ST_Other;
174 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
175 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
176 Result = SymbolRef::ST_Unknown;
177 } else if (Symb->isFunctionDefinition()) {
178 Result = SymbolRef::ST_Function;
180 uint32_t Characteristics = 0;
181 if (!COFF::isReservedSectionNumber(Symb->SectionNumber)) {
182 const coff_section *Section = NULL;
183 if (error_code EC = getSection(Symb->SectionNumber, Section))
185 Characteristics = Section->Characteristics;
187 if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
188 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
189 Result = SymbolRef::ST_Data;
191 return object_error::success;
194 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
195 const coff_symbol *Symb = toSymb(Ref);
196 uint32_t Result = SymbolRef::SF_None;
198 // TODO: Correctly set SF_FormatSpecific, SF_Common
200 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
201 if (Symb->Value == 0)
202 Result |= SymbolRef::SF_Undefined;
204 Result |= SymbolRef::SF_Common;
208 // TODO: This are certainly too restrictive.
209 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
210 Result |= SymbolRef::SF_Global;
212 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
213 Result |= SymbolRef::SF_Weak;
215 if (Symb->SectionNumber == COFF::IMAGE_SYM_ABSOLUTE)
216 Result |= SymbolRef::SF_Absolute;
221 error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
222 uint64_t &Result) const {
223 // FIXME: Return the correct size. This requires looking at all the symbols
224 // in the same section as this symbol, and looking for either the next
225 // symbol, or the end of the section.
226 const coff_symbol *Symb = toSymb(Ref);
227 const coff_section *Section = NULL;
228 if (error_code EC = getSection(Symb->SectionNumber, Section))
231 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
232 Result = UnknownAddressOrSize;
234 Result = Section->SizeOfRawData - Symb->Value;
237 return object_error::success;
240 error_code COFFObjectFile::getSymbolSection(DataRefImpl Ref,
241 section_iterator &Result) const {
242 const coff_symbol *Symb = toSymb(Ref);
243 if (COFF::isReservedSectionNumber(Symb->SectionNumber)) {
244 Result = section_end();
246 const coff_section *Sec = 0;
247 if (error_code EC = getSection(Symb->SectionNumber, Sec)) return EC;
249 Ref.p = reinterpret_cast<uintptr_t>(Sec);
250 Result = section_iterator(SectionRef(Ref, this));
252 return object_error::success;
255 error_code COFFObjectFile::getSymbolValue(DataRefImpl Ref,
256 uint64_t &Result) const {
257 const coff_symbol *Symb = toSymb(Ref);
259 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
260 Result = UnknownAddressOrSize;
262 Result = Symb->Value;
264 return object_error::success;
267 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
268 const coff_section *Sec = toSec(Ref);
270 Ref.p = reinterpret_cast<uintptr_t>(Sec);
273 error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
274 StringRef &Result) const {
275 const coff_section *Sec = toSec(Ref);
276 return getSectionName(Sec, Result);
279 error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
280 uint64_t &Result) const {
281 const coff_section *Sec = toSec(Ref);
282 Result = Sec->VirtualAddress;
283 return object_error::success;
286 error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
287 uint64_t &Result) const {
288 const coff_section *Sec = toSec(Ref);
289 Result = Sec->SizeOfRawData;
290 return object_error::success;
293 error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
294 StringRef &Result) const {
295 const coff_section *Sec = toSec(Ref);
296 ArrayRef<uint8_t> Res;
297 error_code EC = getSectionContents(Sec, Res);
298 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
302 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
303 uint64_t &Res) const {
304 const coff_section *Sec = toSec(Ref);
306 return object_error::parse_failed;
307 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
308 return object_error::success;
311 error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
312 bool &Result) const {
313 const coff_section *Sec = toSec(Ref);
314 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
315 return object_error::success;
318 error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
319 bool &Result) const {
320 const coff_section *Sec = toSec(Ref);
321 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
322 return object_error::success;
325 error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
326 bool &Result) const {
327 const coff_section *Sec = toSec(Ref);
328 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
329 return object_error::success;
332 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
333 bool &Result) const {
334 // FIXME: Unimplemented
336 return object_error::success;
339 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
340 bool &Result) const {
341 const coff_section *Sec = toSec(Ref);
342 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
343 return object_error::success;
346 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
347 bool &Result) const {
348 // FIXME: Unimplemented.
350 return object_error::success;
353 error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
354 bool &Result) const {
355 // FIXME: Unimplemented.
357 return object_error::success;
360 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
362 bool &Result) const {
363 const coff_section *Sec = toSec(SecRef);
364 const coff_symbol *Symb = toSymb(SymbRef);
365 const coff_section *SymbSec = 0;
366 if (error_code EC = getSection(Symb->SectionNumber, SymbSec)) return EC;
371 return object_error::success;
374 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
375 const coff_section *Sec = toSec(Ref);
377 if (Sec->NumberOfRelocations == 0) {
380 auto begin = reinterpret_cast<const coff_relocation*>(
381 base() + Sec->PointerToRelocations);
382 if (Sec->hasExtendedRelocations()) {
383 // Skip the first relocation entry repurposed to store the number of
387 Ret.p = reinterpret_cast<uintptr_t>(begin);
389 return relocation_iterator(RelocationRef(Ret, this));
392 static uint32_t getNumberOfRelocations(const coff_section *Sec,
393 const uint8_t *base) {
394 // The field for the number of relocations in COFF section table is only
395 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
396 // NumberOfRelocations field, and the actual relocation count is stored in the
397 // VirtualAddress field in the first relocation entry.
398 if (Sec->hasExtendedRelocations()) {
399 auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
400 base + Sec->PointerToRelocations);
401 return FirstReloc->VirtualAddress;
403 return Sec->NumberOfRelocations;
406 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
407 const coff_section *Sec = toSec(Ref);
409 if (Sec->NumberOfRelocations == 0) {
412 auto begin = reinterpret_cast<const coff_relocation*>(
413 base() + Sec->PointerToRelocations);
414 uint32_t NumReloc = getNumberOfRelocations(Sec, base());
415 Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
417 return relocation_iterator(RelocationRef(Ret, this));
420 bool COFFObjectFile::section_rel_empty(DataRefImpl Ref) const {
421 const coff_section *Sec = toSec(Ref);
422 return Sec->NumberOfRelocations == 0;
425 // Initialize the pointer to the symbol table.
426 error_code COFFObjectFile::initSymbolTablePtr() {
427 if (error_code EC = getObject(
428 SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
429 COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
432 // Find string table. The first four byte of the string table contains the
433 // total size of the string table, including the size field itself. If the
434 // string table is empty, the value of the first four byte would be 4.
435 const uint8_t *StringTableAddr =
436 base() + COFFHeader->PointerToSymbolTable +
437 COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
438 const ulittle32_t *StringTableSizePtr;
439 if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
441 StringTableSize = *StringTableSizePtr;
443 getObject(StringTable, Data, StringTableAddr, StringTableSize))
446 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
447 // tools like cvtres write a size of 0 for an empty table instead of 4.
448 if (StringTableSize < 4)
451 // Check that the string table is null terminated if has any in it.
452 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
453 return object_error::parse_failed;
454 return object_error::success;
457 // Returns the file offset for the given VA.
458 error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
459 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
460 : (uint64_t)PE32PlusHeader->ImageBase;
461 uint64_t Rva = Addr - ImageBase;
462 assert(Rva <= UINT32_MAX);
463 return getRvaPtr((uint32_t)Rva, Res);
466 // Returns the file offset for the given RVA.
467 error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
468 for (const SectionRef &S : sections()) {
469 const coff_section *Section = getCOFFSection(S);
470 uint32_t SectionStart = Section->VirtualAddress;
471 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
472 if (SectionStart <= Addr && Addr < SectionEnd) {
473 uint32_t Offset = Addr - SectionStart;
474 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
475 return object_error::success;
478 return object_error::parse_failed;
481 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
483 error_code COFFObjectFile::
484 getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const {
485 uintptr_t IntPtr = 0;
486 if (error_code EC = getRvaPtr(Rva, IntPtr))
488 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
489 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
490 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
491 return object_error::success;
494 // Find the import table.
495 error_code COFFObjectFile::initImportTablePtr() {
496 // First, we get the RVA of the import table. If the file lacks a pointer to
497 // the import table, do nothing.
498 const data_directory *DataEntry;
499 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
500 return object_error::success;
502 // Do nothing if the pointer to import table is NULL.
503 if (DataEntry->RelativeVirtualAddress == 0)
504 return object_error::success;
506 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
507 NumberOfImportDirectory = DataEntry->Size /
508 sizeof(import_directory_table_entry);
510 // Find the section that contains the RVA. This is needed because the RVA is
511 // the import table's memory address which is different from its file offset.
512 uintptr_t IntPtr = 0;
513 if (error_code EC = getRvaPtr(ImportTableRva, IntPtr))
515 ImportDirectory = reinterpret_cast<
516 const import_directory_table_entry *>(IntPtr);
517 return object_error::success;
520 // Find the export table.
521 error_code COFFObjectFile::initExportTablePtr() {
522 // First, we get the RVA of the export table. If the file lacks a pointer to
523 // the export table, do nothing.
524 const data_directory *DataEntry;
525 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
526 return object_error::success;
528 // Do nothing if the pointer to export table is NULL.
529 if (DataEntry->RelativeVirtualAddress == 0)
530 return object_error::success;
532 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
533 uintptr_t IntPtr = 0;
534 if (error_code EC = getRvaPtr(ExportTableRva, IntPtr))
537 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
538 return object_error::success;
541 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC,
543 : ObjectFile(Binary::ID_COFF, Object, BufferOwned), COFFHeader(0),
544 PE32Header(0), PE32PlusHeader(0), DataDirectory(0), SectionTable(0),
545 SymbolTable(0), StringTable(0), StringTableSize(0), ImportDirectory(0),
546 NumberOfImportDirectory(0), ExportDirectory(0) {
547 // Check that we at least have enough room for a header.
548 if (!checkSize(Data, EC, sizeof(coff_file_header))) return;
550 // The current location in the file where we are looking at.
553 // PE header is optional and is present only in executables. If it exists,
554 // it is placed right after COFF header.
555 bool HasPEHeader = false;
557 // Check if this is a PE/COFF file.
558 if (base()[0] == 0x4d && base()[1] == 0x5a) {
559 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
560 // PE signature to find 'normal' COFF header.
561 if (!checkSize(Data, EC, 0x3c + 8)) return;
562 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
563 // Check the PE magic bytes. ("PE\0\0")
564 if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
565 EC = object_error::parse_failed;
568 CurPtr += 4; // Skip the PE magic bytes.
572 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
574 CurPtr += sizeof(coff_file_header);
577 const pe32_header *Header;
578 if ((EC = getObject(Header, Data, base() + CurPtr)))
581 const uint8_t *DataDirAddr;
582 uint64_t DataDirSize;
583 if (Header->Magic == 0x10b) {
585 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
586 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
587 } else if (Header->Magic == 0x20b) {
588 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
589 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
590 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
592 // It's neither PE32 nor PE32+.
593 EC = object_error::parse_failed;
596 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
598 CurPtr += COFFHeader->SizeOfOptionalHeader;
601 if (COFFHeader->isImportLibrary())
604 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
605 COFFHeader->NumberOfSections * sizeof(coff_section))))
608 // Initialize the pointer to the symbol table.
609 if (COFFHeader->PointerToSymbolTable != 0)
610 if ((EC = initSymbolTablePtr()))
613 // Initialize the pointer to the beginning of the import table.
614 if ((EC = initImportTablePtr()))
617 // Initialize the pointer to the export table.
618 if ((EC = initExportTablePtr()))
621 EC = object_error::success;
624 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
626 Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
627 return basic_symbol_iterator(SymbolRef(Ret, this));
630 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
631 // The symbol table ends where the string table begins.
633 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
634 return basic_symbol_iterator(SymbolRef(Ret, this));
637 library_iterator COFFObjectFile::needed_library_begin() const {
639 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
642 library_iterator COFFObjectFile::needed_library_end() const {
644 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
647 StringRef COFFObjectFile::getLoadName() const {
648 // COFF does not have this field.
652 import_directory_iterator COFFObjectFile::import_directory_begin() const {
653 return import_directory_iterator(
654 ImportDirectoryEntryRef(ImportDirectory, 0, this));
657 import_directory_iterator COFFObjectFile::import_directory_end() const {
658 return import_directory_iterator(
659 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
662 export_directory_iterator COFFObjectFile::export_directory_begin() const {
663 return export_directory_iterator(
664 ExportDirectoryEntryRef(ExportDirectory, 0, this));
667 export_directory_iterator COFFObjectFile::export_directory_end() const {
668 if (ExportDirectory == 0)
669 return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this));
670 ExportDirectoryEntryRef Ref(ExportDirectory,
671 ExportDirectory->AddressTableEntries, this);
672 return export_directory_iterator(Ref);
675 section_iterator COFFObjectFile::section_begin() const {
677 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
678 return section_iterator(SectionRef(Ret, this));
681 section_iterator COFFObjectFile::section_end() const {
683 int NumSections = COFFHeader->isImportLibrary()
684 ? 0 : COFFHeader->NumberOfSections;
685 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
686 return section_iterator(SectionRef(Ret, this));
689 uint8_t COFFObjectFile::getBytesInAddress() const {
690 return getArch() == Triple::x86_64 ? 8 : 4;
693 StringRef COFFObjectFile::getFileFormatName() const {
694 switch(COFFHeader->Machine) {
695 case COFF::IMAGE_FILE_MACHINE_I386:
697 case COFF::IMAGE_FILE_MACHINE_AMD64:
698 return "COFF-x86-64";
699 case COFF::IMAGE_FILE_MACHINE_ARMNT:
702 return "COFF-<unknown arch>";
706 unsigned COFFObjectFile::getArch() const {
707 switch(COFFHeader->Machine) {
708 case COFF::IMAGE_FILE_MACHINE_I386:
710 case COFF::IMAGE_FILE_MACHINE_AMD64:
711 return Triple::x86_64;
712 case COFF::IMAGE_FILE_MACHINE_ARMNT:
713 return Triple::thumb;
715 return Triple::UnknownArch;
719 // This method is kept here because lld uses this. As soon as we make
720 // lld to use getCOFFHeader, this method will be removed.
721 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
722 return getCOFFHeader(Res);
725 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
727 return object_error::success;
730 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
732 return object_error::success;
736 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
737 Res = PE32PlusHeader;
738 return object_error::success;
741 error_code COFFObjectFile::getDataDirectory(uint32_t Index,
742 const data_directory *&Res) const {
743 // Error if if there's no data directory or the index is out of range.
745 return object_error::parse_failed;
746 assert(PE32Header || PE32PlusHeader);
747 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
748 : PE32PlusHeader->NumberOfRvaAndSize;
750 return object_error::parse_failed;
751 Res = &DataDirectory[Index];
752 return object_error::success;
755 error_code COFFObjectFile::getSection(int32_t Index,
756 const coff_section *&Result) const {
757 // Check for special index values.
758 if (COFF::isReservedSectionNumber(Index))
760 else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
761 // We already verified the section table data, so no need to check again.
762 Result = SectionTable + (Index - 1);
764 return object_error::parse_failed;
765 return object_error::success;
768 error_code COFFObjectFile::getString(uint32_t Offset,
769 StringRef &Result) const {
770 if (StringTableSize <= 4)
771 // Tried to get a string from an empty string table.
772 return object_error::parse_failed;
773 if (Offset >= StringTableSize)
774 return object_error::unexpected_eof;
775 Result = StringRef(StringTable + Offset);
776 return object_error::success;
779 error_code COFFObjectFile::getSymbol(uint32_t Index,
780 const coff_symbol *&Result) const {
781 if (Index < COFFHeader->NumberOfSymbols)
782 Result = SymbolTable + Index;
784 return object_error::parse_failed;
785 return object_error::success;
788 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
789 StringRef &Res) const {
790 // Check for string table entry. First 4 bytes are 0.
791 if (Symbol->Name.Offset.Zeroes == 0) {
792 uint32_t Offset = Symbol->Name.Offset.Offset;
793 if (error_code EC = getString(Offset, Res))
795 return object_error::success;
798 if (Symbol->Name.ShortName[7] == 0)
799 // Null terminated, let ::strlen figure out the length.
800 Res = StringRef(Symbol->Name.ShortName);
802 // Not null terminated, use all 8 bytes.
803 Res = StringRef(Symbol->Name.ShortName, 8);
804 return object_error::success;
807 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
808 const coff_symbol *Symbol) const {
809 const uint8_t *Aux = NULL;
811 if (Symbol->NumberOfAuxSymbols > 0) {
812 // AUX data comes immediately after the symbol in COFF
813 Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
815 // Verify that the Aux symbol points to a valid entry in the symbol table.
816 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
817 if (Offset < COFFHeader->PointerToSymbolTable
818 || Offset >= COFFHeader->PointerToSymbolTable
819 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
820 report_fatal_error("Aux Symbol data was outside of symbol table.");
822 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
823 == 0 && "Aux Symbol data did not point to the beginning of a symbol");
826 return ArrayRef<uint8_t>(Aux,
827 Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
830 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
831 StringRef &Res) const {
833 if (Sec->Name[7] == 0)
834 // Null terminated, let ::strlen figure out the length.
837 // Not null terminated, use all 8 bytes.
838 Name = StringRef(Sec->Name, 8);
840 // Check for string table entry. First byte is '/'.
841 if (Name[0] == '/') {
843 if (Name[1] == '/') {
844 if (decodeBase64StringEntry(Name.substr(2), Offset))
845 return object_error::parse_failed;
847 if (Name.substr(1).getAsInteger(10, Offset))
848 return object_error::parse_failed;
850 if (error_code EC = getString(Offset, Name))
855 return object_error::success;
858 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
859 ArrayRef<uint8_t> &Res) const {
860 // The only thing that we need to verify is that the contents is contained
861 // within the file bounds. We don't need to make sure it doesn't cover other
862 // data, as there's nothing that says that is not allowed.
863 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
864 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
865 if (ConEnd > uintptr_t(Data->getBufferEnd()))
866 return object_error::parse_failed;
867 Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
869 return object_error::success;
872 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
873 return reinterpret_cast<const coff_relocation*>(Rel.p);
876 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
877 Rel.p = reinterpret_cast<uintptr_t>(
878 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
881 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
882 uint64_t &Res) const {
883 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
886 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
887 uint64_t &Res) const {
888 Res = toRel(Rel)->VirtualAddress;
889 return object_error::success;
892 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
893 const coff_relocation* R = toRel(Rel);
895 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
896 return symbol_iterator(SymbolRef(Ref, this));
899 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
900 uint64_t &Res) const {
901 const coff_relocation* R = toRel(Rel);
903 return object_error::success;
907 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
908 return toSec(Section.getRawDataRefImpl());
912 COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
913 return toSymb(Symbol.getRawDataRefImpl());
916 const coff_relocation *
917 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
918 return toRel(Reloc.getRawDataRefImpl());
921 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
922 case COFF::reloc_type: \
926 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
927 SmallVectorImpl<char> &Result) const {
928 const coff_relocation *Reloc = toRel(Rel);
930 switch (COFFHeader->Machine) {
931 case COFF::IMAGE_FILE_MACHINE_AMD64:
932 switch (Reloc->Type) {
933 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
934 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
935 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
936 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
937 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
938 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
939 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
940 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
941 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
942 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
943 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
944 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
945 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
946 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
947 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
948 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
949 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
954 case COFF::IMAGE_FILE_MACHINE_I386:
955 switch (Reloc->Type) {
956 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
957 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
958 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
959 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
960 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
961 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
962 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
963 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
964 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
965 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
966 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
974 Result.append(Res.begin(), Res.end());
975 return object_error::success;
978 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
980 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
981 SmallVectorImpl<char> &Result) const {
982 const coff_relocation *Reloc = toRel(Rel);
983 const coff_symbol *Symb = 0;
984 if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
986 Sym.p = reinterpret_cast<uintptr_t>(Symb);
988 if (error_code EC = getSymbolName(Sym, SymName)) return EC;
989 Result.append(SymName.begin(), SymName.end());
990 return object_error::success;
993 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
994 LibraryRef &Result) const {
995 report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
998 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
999 StringRef &Result) const {
1000 report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
1003 bool ImportDirectoryEntryRef::
1004 operator==(const ImportDirectoryEntryRef &Other) const {
1005 return ImportTable == Other.ImportTable && Index == Other.Index;
1008 void ImportDirectoryEntryRef::moveNext() {
1012 error_code ImportDirectoryEntryRef::
1013 getImportTableEntry(const import_directory_table_entry *&Result) const {
1014 Result = ImportTable;
1015 return object_error::success;
1018 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1019 uintptr_t IntPtr = 0;
1020 if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
1022 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1023 return object_error::success;
1026 error_code ImportDirectoryEntryRef::getImportLookupEntry(
1027 const import_lookup_table_entry32 *&Result) const {
1028 uintptr_t IntPtr = 0;
1030 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
1032 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1033 return object_error::success;
1036 bool ExportDirectoryEntryRef::
1037 operator==(const ExportDirectoryEntryRef &Other) const {
1038 return ExportTable == Other.ExportTable && Index == Other.Index;
1041 void ExportDirectoryEntryRef::moveNext() {
1045 // Returns the name of the current export symbol. If the symbol is exported only
1046 // by ordinal, the empty string is set as a result.
1047 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1048 uintptr_t IntPtr = 0;
1049 if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1051 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1052 return object_error::success;
1055 // Returns the starting ordinal number.
1056 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1057 Result = ExportTable->OrdinalBase;
1058 return object_error::success;
1061 // Returns the export ordinal of the current export symbol.
1062 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1063 Result = ExportTable->OrdinalBase + Index;
1064 return object_error::success;
1067 // Returns the address of the current export symbol.
1068 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1069 uintptr_t IntPtr = 0;
1070 if (error_code EC = OwningObject->getRvaPtr(
1071 ExportTable->ExportAddressTableRVA, IntPtr))
1073 const export_address_table_entry *entry =
1074 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1075 Result = entry[Index].ExportRVA;
1076 return object_error::success;
1079 // Returns the name of the current export symbol. If the symbol is exported only
1080 // by ordinal, the empty string is set as a result.
1081 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1082 uintptr_t IntPtr = 0;
1083 if (error_code EC = OwningObject->getRvaPtr(
1084 ExportTable->OrdinalTableRVA, IntPtr))
1086 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1088 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1090 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1091 I < E; ++I, ++Offset) {
1094 if (error_code EC = OwningObject->getRvaPtr(
1095 ExportTable->NamePointerRVA, IntPtr))
1097 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1098 if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1100 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1101 return object_error::success;
1104 return object_error::success;
1107 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object,
1110 std::unique_ptr<COFFObjectFile> Ret(
1111 new COFFObjectFile(Object, EC, BufferOwned));
1114 return Ret.release();