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 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
256 const coff_section *Sec = toSec(Ref);
258 Ref.p = reinterpret_cast<uintptr_t>(Sec);
261 error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
262 StringRef &Result) const {
263 const coff_section *Sec = toSec(Ref);
264 return getSectionName(Sec, Result);
267 error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
268 uint64_t &Result) const {
269 const coff_section *Sec = toSec(Ref);
270 Result = Sec->VirtualAddress;
271 return object_error::success;
274 error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
275 uint64_t &Result) const {
276 const coff_section *Sec = toSec(Ref);
277 Result = Sec->SizeOfRawData;
278 return object_error::success;
281 error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
282 StringRef &Result) const {
283 const coff_section *Sec = toSec(Ref);
284 ArrayRef<uint8_t> Res;
285 error_code EC = getSectionContents(Sec, Res);
286 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
290 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
291 uint64_t &Res) const {
292 const coff_section *Sec = toSec(Ref);
294 return object_error::parse_failed;
295 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
296 return object_error::success;
299 error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
300 bool &Result) const {
301 const coff_section *Sec = toSec(Ref);
302 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
303 return object_error::success;
306 error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
307 bool &Result) const {
308 const coff_section *Sec = toSec(Ref);
309 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
310 return object_error::success;
313 error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
314 bool &Result) const {
315 const coff_section *Sec = toSec(Ref);
316 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
317 return object_error::success;
320 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
321 bool &Result) const {
322 // FIXME: Unimplemented
324 return object_error::success;
327 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
328 bool &Result) const {
329 const coff_section *Sec = toSec(Ref);
330 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
331 return object_error::success;
334 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
335 bool &Result) const {
336 // FIXME: Unimplemented.
338 return object_error::success;
341 error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
342 bool &Result) const {
343 // FIXME: Unimplemented.
345 return object_error::success;
348 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
350 bool &Result) const {
351 const coff_section *Sec = toSec(SecRef);
352 const coff_symbol *Symb = toSymb(SymbRef);
353 const coff_section *SymbSec = 0;
354 if (error_code EC = getSection(Symb->SectionNumber, SymbSec)) return EC;
359 return object_error::success;
362 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
363 const coff_section *Sec = toSec(Ref);
365 if (Sec->NumberOfRelocations == 0) {
368 auto begin = reinterpret_cast<const coff_relocation*>(
369 base() + Sec->PointerToRelocations);
370 if (Sec->hasExtendedRelocations()) {
371 // Skip the first relocation entry repurposed to store the number of
375 Ret.p = reinterpret_cast<uintptr_t>(begin);
377 return relocation_iterator(RelocationRef(Ret, this));
380 static uint32_t getNumberOfRelocations(const coff_section *Sec,
381 const uint8_t *base) {
382 // The field for the number of relocations in COFF section table is only
383 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
384 // NumberOfRelocations field, and the actual relocation count is stored in the
385 // VirtualAddress field in the first relocation entry.
386 if (Sec->hasExtendedRelocations()) {
387 auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
388 base + Sec->PointerToRelocations);
389 return FirstReloc->VirtualAddress;
391 return Sec->NumberOfRelocations;
394 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
395 const coff_section *Sec = toSec(Ref);
397 if (Sec->NumberOfRelocations == 0) {
400 auto begin = reinterpret_cast<const coff_relocation*>(
401 base() + Sec->PointerToRelocations);
402 uint32_t NumReloc = getNumberOfRelocations(Sec, base());
403 Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
405 return relocation_iterator(RelocationRef(Ret, this));
408 bool COFFObjectFile::section_rel_empty(DataRefImpl Ref) const {
409 const coff_section *Sec = toSec(Ref);
410 return Sec->NumberOfRelocations == 0;
413 // Initialize the pointer to the symbol table.
414 error_code COFFObjectFile::initSymbolTablePtr() {
415 if (error_code EC = getObject(
416 SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
417 COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
420 // Find string table. The first four byte of the string table contains the
421 // total size of the string table, including the size field itself. If the
422 // string table is empty, the value of the first four byte would be 4.
423 const uint8_t *StringTableAddr =
424 base() + COFFHeader->PointerToSymbolTable +
425 COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
426 const ulittle32_t *StringTableSizePtr;
427 if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
429 StringTableSize = *StringTableSizePtr;
431 getObject(StringTable, Data, StringTableAddr, StringTableSize))
434 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
435 // tools like cvtres write a size of 0 for an empty table instead of 4.
436 if (StringTableSize < 4)
439 // Check that the string table is null terminated if has any in it.
440 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
441 return object_error::parse_failed;
442 return object_error::success;
445 // Returns the file offset for the given VA.
446 error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
447 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
448 : (uint64_t)PE32PlusHeader->ImageBase;
449 uint64_t Rva = Addr - ImageBase;
450 assert(Rva <= UINT32_MAX);
451 return getRvaPtr((uint32_t)Rva, Res);
454 // Returns the file offset for the given RVA.
455 error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
456 for (const SectionRef &S : sections()) {
457 const coff_section *Section = getCOFFSection(S);
458 uint32_t SectionStart = Section->VirtualAddress;
459 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
460 if (SectionStart <= Addr && Addr < SectionEnd) {
461 uint32_t Offset = Addr - SectionStart;
462 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
463 return object_error::success;
466 return object_error::parse_failed;
469 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
471 error_code COFFObjectFile::
472 getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const {
473 uintptr_t IntPtr = 0;
474 if (error_code EC = getRvaPtr(Rva, IntPtr))
476 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
477 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
478 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
479 return object_error::success;
482 // Find the import table.
483 error_code COFFObjectFile::initImportTablePtr() {
484 // First, we get the RVA of the import table. If the file lacks a pointer to
485 // the import table, do nothing.
486 const data_directory *DataEntry;
487 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
488 return object_error::success;
490 // Do nothing if the pointer to import table is NULL.
491 if (DataEntry->RelativeVirtualAddress == 0)
492 return object_error::success;
494 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
495 NumberOfImportDirectory = DataEntry->Size /
496 sizeof(import_directory_table_entry);
498 // Find the section that contains the RVA. This is needed because the RVA is
499 // the import table's memory address which is different from its file offset.
500 uintptr_t IntPtr = 0;
501 if (error_code EC = getRvaPtr(ImportTableRva, IntPtr))
503 ImportDirectory = reinterpret_cast<
504 const import_directory_table_entry *>(IntPtr);
505 return object_error::success;
508 // Find the export table.
509 error_code COFFObjectFile::initExportTablePtr() {
510 // First, we get the RVA of the export table. If the file lacks a pointer to
511 // the export table, do nothing.
512 const data_directory *DataEntry;
513 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
514 return object_error::success;
516 // Do nothing if the pointer to export table is NULL.
517 if (DataEntry->RelativeVirtualAddress == 0)
518 return object_error::success;
520 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
521 uintptr_t IntPtr = 0;
522 if (error_code EC = getRvaPtr(ExportTableRva, IntPtr))
525 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
526 return object_error::success;
529 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC,
531 : ObjectFile(Binary::ID_COFF, Object, BufferOwned), COFFHeader(0),
532 PE32Header(0), PE32PlusHeader(0), DataDirectory(0), SectionTable(0),
533 SymbolTable(0), StringTable(0), StringTableSize(0), ImportDirectory(0),
534 NumberOfImportDirectory(0), ExportDirectory(0) {
535 // Check that we at least have enough room for a header.
536 if (!checkSize(Data, EC, sizeof(coff_file_header))) return;
538 // The current location in the file where we are looking at.
541 // PE header is optional and is present only in executables. If it exists,
542 // it is placed right after COFF header.
543 bool HasPEHeader = false;
545 // Check if this is a PE/COFF file.
546 if (base()[0] == 0x4d && base()[1] == 0x5a) {
547 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
548 // PE signature to find 'normal' COFF header.
549 if (!checkSize(Data, EC, 0x3c + 8)) return;
550 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
551 // Check the PE magic bytes. ("PE\0\0")
552 if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
553 EC = object_error::parse_failed;
556 CurPtr += 4; // Skip the PE magic bytes.
560 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
562 CurPtr += sizeof(coff_file_header);
565 const pe32_header *Header;
566 if ((EC = getObject(Header, Data, base() + CurPtr)))
569 const uint8_t *DataDirAddr;
570 uint64_t DataDirSize;
571 if (Header->Magic == 0x10b) {
573 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
574 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
575 } else if (Header->Magic == 0x20b) {
576 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
577 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
578 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
580 // It's neither PE32 nor PE32+.
581 EC = object_error::parse_failed;
584 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
586 CurPtr += COFFHeader->SizeOfOptionalHeader;
589 if (COFFHeader->isImportLibrary())
592 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
593 COFFHeader->NumberOfSections * sizeof(coff_section))))
596 // Initialize the pointer to the symbol table.
597 if (COFFHeader->PointerToSymbolTable != 0)
598 if ((EC = initSymbolTablePtr()))
601 // Initialize the pointer to the beginning of the import table.
602 if ((EC = initImportTablePtr()))
605 // Initialize the pointer to the export table.
606 if ((EC = initExportTablePtr()))
609 EC = object_error::success;
612 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
614 Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
615 return basic_symbol_iterator(SymbolRef(Ret, this));
618 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
619 // The symbol table ends where the string table begins.
621 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
622 return basic_symbol_iterator(SymbolRef(Ret, this));
625 library_iterator COFFObjectFile::needed_library_begin() const {
627 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
630 library_iterator COFFObjectFile::needed_library_end() const {
632 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
635 StringRef COFFObjectFile::getLoadName() const {
636 // COFF does not have this field.
640 import_directory_iterator COFFObjectFile::import_directory_begin() const {
641 return import_directory_iterator(
642 ImportDirectoryEntryRef(ImportDirectory, 0, this));
645 import_directory_iterator COFFObjectFile::import_directory_end() const {
646 return import_directory_iterator(
647 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
650 export_directory_iterator COFFObjectFile::export_directory_begin() const {
651 return export_directory_iterator(
652 ExportDirectoryEntryRef(ExportDirectory, 0, this));
655 export_directory_iterator COFFObjectFile::export_directory_end() const {
656 if (ExportDirectory == 0)
657 return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this));
658 ExportDirectoryEntryRef Ref(ExportDirectory,
659 ExportDirectory->AddressTableEntries, this);
660 return export_directory_iterator(Ref);
663 section_iterator COFFObjectFile::section_begin() const {
665 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
666 return section_iterator(SectionRef(Ret, this));
669 section_iterator COFFObjectFile::section_end() const {
671 int NumSections = COFFHeader->isImportLibrary()
672 ? 0 : COFFHeader->NumberOfSections;
673 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
674 return section_iterator(SectionRef(Ret, this));
677 uint8_t COFFObjectFile::getBytesInAddress() const {
678 return getArch() == Triple::x86_64 ? 8 : 4;
681 StringRef COFFObjectFile::getFileFormatName() const {
682 switch(COFFHeader->Machine) {
683 case COFF::IMAGE_FILE_MACHINE_I386:
685 case COFF::IMAGE_FILE_MACHINE_AMD64:
686 return "COFF-x86-64";
687 case COFF::IMAGE_FILE_MACHINE_ARMNT:
690 return "COFF-<unknown arch>";
694 unsigned COFFObjectFile::getArch() const {
695 switch(COFFHeader->Machine) {
696 case COFF::IMAGE_FILE_MACHINE_I386:
698 case COFF::IMAGE_FILE_MACHINE_AMD64:
699 return Triple::x86_64;
700 case COFF::IMAGE_FILE_MACHINE_ARMNT:
701 return Triple::thumb;
703 return Triple::UnknownArch;
707 // This method is kept here because lld uses this. As soon as we make
708 // lld to use getCOFFHeader, this method will be removed.
709 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
710 return getCOFFHeader(Res);
713 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
715 return object_error::success;
718 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
720 return object_error::success;
724 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
725 Res = PE32PlusHeader;
726 return object_error::success;
729 error_code COFFObjectFile::getDataDirectory(uint32_t Index,
730 const data_directory *&Res) const {
731 // Error if if there's no data directory or the index is out of range.
733 return object_error::parse_failed;
734 assert(PE32Header || PE32PlusHeader);
735 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
736 : PE32PlusHeader->NumberOfRvaAndSize;
738 return object_error::parse_failed;
739 Res = &DataDirectory[Index];
740 return object_error::success;
743 error_code COFFObjectFile::getSection(int32_t Index,
744 const coff_section *&Result) const {
745 // Check for special index values.
746 if (COFF::isReservedSectionNumber(Index))
748 else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
749 // We already verified the section table data, so no need to check again.
750 Result = SectionTable + (Index - 1);
752 return object_error::parse_failed;
753 return object_error::success;
756 error_code COFFObjectFile::getString(uint32_t Offset,
757 StringRef &Result) const {
758 if (StringTableSize <= 4)
759 // Tried to get a string from an empty string table.
760 return object_error::parse_failed;
761 if (Offset >= StringTableSize)
762 return object_error::unexpected_eof;
763 Result = StringRef(StringTable + Offset);
764 return object_error::success;
767 error_code COFFObjectFile::getSymbol(uint32_t Index,
768 const coff_symbol *&Result) const {
769 if (Index < COFFHeader->NumberOfSymbols)
770 Result = SymbolTable + Index;
772 return object_error::parse_failed;
773 return object_error::success;
776 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
777 StringRef &Res) const {
778 // Check for string table entry. First 4 bytes are 0.
779 if (Symbol->Name.Offset.Zeroes == 0) {
780 uint32_t Offset = Symbol->Name.Offset.Offset;
781 if (error_code EC = getString(Offset, Res))
783 return object_error::success;
786 if (Symbol->Name.ShortName[7] == 0)
787 // Null terminated, let ::strlen figure out the length.
788 Res = StringRef(Symbol->Name.ShortName);
790 // Not null terminated, use all 8 bytes.
791 Res = StringRef(Symbol->Name.ShortName, 8);
792 return object_error::success;
795 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
796 const coff_symbol *Symbol) const {
797 const uint8_t *Aux = NULL;
799 if (Symbol->NumberOfAuxSymbols > 0) {
800 // AUX data comes immediately after the symbol in COFF
801 Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
803 // Verify that the Aux symbol points to a valid entry in the symbol table.
804 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
805 if (Offset < COFFHeader->PointerToSymbolTable
806 || Offset >= COFFHeader->PointerToSymbolTable
807 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
808 report_fatal_error("Aux Symbol data was outside of symbol table.");
810 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
811 == 0 && "Aux Symbol data did not point to the beginning of a symbol");
814 return ArrayRef<uint8_t>(Aux,
815 Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
818 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
819 StringRef &Res) const {
821 if (Sec->Name[7] == 0)
822 // Null terminated, let ::strlen figure out the length.
825 // Not null terminated, use all 8 bytes.
826 Name = StringRef(Sec->Name, 8);
828 // Check for string table entry. First byte is '/'.
829 if (Name[0] == '/') {
831 if (Name[1] == '/') {
832 if (decodeBase64StringEntry(Name.substr(2), Offset))
833 return object_error::parse_failed;
835 if (Name.substr(1).getAsInteger(10, Offset))
836 return object_error::parse_failed;
838 if (error_code EC = getString(Offset, Name))
843 return object_error::success;
846 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
847 ArrayRef<uint8_t> &Res) const {
848 // The only thing that we need to verify is that the contents is contained
849 // within the file bounds. We don't need to make sure it doesn't cover other
850 // data, as there's nothing that says that is not allowed.
851 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
852 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
853 if (ConEnd > uintptr_t(Data->getBufferEnd()))
854 return object_error::parse_failed;
855 Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
857 return object_error::success;
860 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
861 return reinterpret_cast<const coff_relocation*>(Rel.p);
864 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
865 Rel.p = reinterpret_cast<uintptr_t>(
866 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
869 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
870 uint64_t &Res) const {
871 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
874 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
875 uint64_t &Res) const {
876 Res = toRel(Rel)->VirtualAddress;
877 return object_error::success;
880 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
881 const coff_relocation* R = toRel(Rel);
883 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
884 return symbol_iterator(SymbolRef(Ref, this));
887 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
888 uint64_t &Res) const {
889 const coff_relocation* R = toRel(Rel);
891 return object_error::success;
895 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
896 return toSec(Section.getRawDataRefImpl());
900 COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
901 return toSymb(Symbol.getRawDataRefImpl());
904 const coff_relocation *
905 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
906 return toRel(Reloc.getRawDataRefImpl());
909 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
910 case COFF::reloc_type: \
914 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
915 SmallVectorImpl<char> &Result) const {
916 const coff_relocation *Reloc = toRel(Rel);
918 switch (COFFHeader->Machine) {
919 case COFF::IMAGE_FILE_MACHINE_AMD64:
920 switch (Reloc->Type) {
921 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
922 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
923 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
924 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
925 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
926 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
927 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
928 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
929 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
930 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
931 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
932 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
933 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
934 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
935 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
936 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
937 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
942 case COFF::IMAGE_FILE_MACHINE_I386:
943 switch (Reloc->Type) {
944 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
945 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
946 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
947 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
948 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
949 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
950 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
951 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
952 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
953 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
954 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
962 Result.append(Res.begin(), Res.end());
963 return object_error::success;
966 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
968 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
969 SmallVectorImpl<char> &Result) const {
970 const coff_relocation *Reloc = toRel(Rel);
971 const coff_symbol *Symb = 0;
972 if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
974 Sym.p = reinterpret_cast<uintptr_t>(Symb);
976 if (error_code EC = getSymbolName(Sym, SymName)) return EC;
977 Result.append(SymName.begin(), SymName.end());
978 return object_error::success;
981 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
982 LibraryRef &Result) const {
983 report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
986 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
987 StringRef &Result) const {
988 report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
991 bool ImportDirectoryEntryRef::
992 operator==(const ImportDirectoryEntryRef &Other) const {
993 return ImportTable == Other.ImportTable && Index == Other.Index;
996 void ImportDirectoryEntryRef::moveNext() {
1000 error_code ImportDirectoryEntryRef::
1001 getImportTableEntry(const import_directory_table_entry *&Result) const {
1002 Result = ImportTable;
1003 return object_error::success;
1006 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1007 uintptr_t IntPtr = 0;
1008 if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
1010 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1011 return object_error::success;
1014 error_code ImportDirectoryEntryRef::getImportLookupEntry(
1015 const import_lookup_table_entry32 *&Result) const {
1016 uintptr_t IntPtr = 0;
1018 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
1020 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1021 return object_error::success;
1024 bool ExportDirectoryEntryRef::
1025 operator==(const ExportDirectoryEntryRef &Other) const {
1026 return ExportTable == Other.ExportTable && Index == Other.Index;
1029 void ExportDirectoryEntryRef::moveNext() {
1033 // Returns the name of the current export symbol. If the symbol is exported only
1034 // by ordinal, the empty string is set as a result.
1035 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1036 uintptr_t IntPtr = 0;
1037 if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1039 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1040 return object_error::success;
1043 // Returns the starting ordinal number.
1044 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1045 Result = ExportTable->OrdinalBase;
1046 return object_error::success;
1049 // Returns the export ordinal of the current export symbol.
1050 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1051 Result = ExportTable->OrdinalBase + Index;
1052 return object_error::success;
1055 // Returns the address of the current export symbol.
1056 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1057 uintptr_t IntPtr = 0;
1058 if (error_code EC = OwningObject->getRvaPtr(
1059 ExportTable->ExportAddressTableRVA, IntPtr))
1061 const export_address_table_entry *entry =
1062 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1063 Result = entry[Index].ExportRVA;
1064 return object_error::success;
1067 // Returns the name of the current export symbol. If the symbol is exported only
1068 // by ordinal, the empty string is set as a result.
1069 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1070 uintptr_t IntPtr = 0;
1071 if (error_code EC = OwningObject->getRvaPtr(
1072 ExportTable->OrdinalTableRVA, IntPtr))
1074 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1076 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1078 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1079 I < E; ++I, ++Offset) {
1082 if (error_code EC = OwningObject->getRvaPtr(
1083 ExportTable->NamePointerRVA, IntPtr))
1085 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1086 if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1088 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1089 return object_error::success;
1092 return object_error::success;
1095 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object,
1098 std::unique_ptr<COFFObjectFile> Ret(
1099 new COFFObjectFile(Object, EC, BufferOwned));
1102 return Ret.release();