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 &Val) const {
257 report_fatal_error("getSymbolValue unimplemented in COFFObjectFile");
260 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
261 const coff_section *Sec = toSec(Ref);
263 Ref.p = reinterpret_cast<uintptr_t>(Sec);
266 error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
267 StringRef &Result) const {
268 const coff_section *Sec = toSec(Ref);
269 return getSectionName(Sec, Result);
272 error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
273 uint64_t &Result) const {
274 const coff_section *Sec = toSec(Ref);
275 Result = Sec->VirtualAddress;
276 return object_error::success;
279 error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
280 uint64_t &Result) const {
281 const coff_section *Sec = toSec(Ref);
282 Result = Sec->SizeOfRawData;
283 return object_error::success;
286 error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
287 StringRef &Result) const {
288 const coff_section *Sec = toSec(Ref);
289 ArrayRef<uint8_t> Res;
290 error_code EC = getSectionContents(Sec, Res);
291 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
295 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
296 uint64_t &Res) const {
297 const coff_section *Sec = toSec(Ref);
299 return object_error::parse_failed;
300 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
301 return object_error::success;
304 error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
305 bool &Result) const {
306 const coff_section *Sec = toSec(Ref);
307 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
308 return object_error::success;
311 error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
312 bool &Result) const {
313 const coff_section *Sec = toSec(Ref);
314 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
315 return object_error::success;
318 error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
319 bool &Result) const {
320 const coff_section *Sec = toSec(Ref);
321 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
322 return object_error::success;
325 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
326 bool &Result) const {
327 // FIXME: Unimplemented
329 return object_error::success;
332 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
333 bool &Result) const {
334 const coff_section *Sec = toSec(Ref);
335 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
336 return object_error::success;
339 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
340 bool &Result) const {
341 // FIXME: Unimplemented.
343 return object_error::success;
346 error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
347 bool &Result) const {
348 // FIXME: Unimplemented.
350 return object_error::success;
353 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
355 bool &Result) const {
356 const coff_section *Sec = toSec(SecRef);
357 const coff_symbol *Symb = toSymb(SymbRef);
358 const coff_section *SymbSec = 0;
359 if (error_code EC = getSection(Symb->SectionNumber, SymbSec)) return EC;
364 return object_error::success;
367 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
368 const coff_section *Sec = toSec(Ref);
370 if (Sec->NumberOfRelocations == 0) {
373 auto begin = reinterpret_cast<const coff_relocation*>(
374 base() + Sec->PointerToRelocations);
375 if (Sec->hasExtendedRelocations()) {
376 // Skip the first relocation entry repurposed to store the number of
380 Ret.p = reinterpret_cast<uintptr_t>(begin);
382 return relocation_iterator(RelocationRef(Ret, this));
385 static uint32_t getNumberOfRelocations(const coff_section *Sec,
386 const uint8_t *base) {
387 // The field for the number of relocations in COFF section table is only
388 // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
389 // NumberOfRelocations field, and the actual relocation count is stored in the
390 // VirtualAddress field in the first relocation entry.
391 if (Sec->hasExtendedRelocations()) {
392 auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
393 base + Sec->PointerToRelocations);
394 return FirstReloc->VirtualAddress;
396 return Sec->NumberOfRelocations;
399 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
400 const coff_section *Sec = toSec(Ref);
402 if (Sec->NumberOfRelocations == 0) {
405 auto begin = reinterpret_cast<const coff_relocation*>(
406 base() + Sec->PointerToRelocations);
407 uint32_t NumReloc = getNumberOfRelocations(Sec, base());
408 Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
410 return relocation_iterator(RelocationRef(Ret, this));
413 bool COFFObjectFile::section_rel_empty(DataRefImpl Ref) const {
414 const coff_section *Sec = toSec(Ref);
415 return Sec->NumberOfRelocations == 0;
418 // Initialize the pointer to the symbol table.
419 error_code COFFObjectFile::initSymbolTablePtr() {
420 if (error_code EC = getObject(
421 SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
422 COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
425 // Find string table. The first four byte of the string table contains the
426 // total size of the string table, including the size field itself. If the
427 // string table is empty, the value of the first four byte would be 4.
428 const uint8_t *StringTableAddr =
429 base() + COFFHeader->PointerToSymbolTable +
430 COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
431 const ulittle32_t *StringTableSizePtr;
432 if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
434 StringTableSize = *StringTableSizePtr;
436 getObject(StringTable, Data, StringTableAddr, StringTableSize))
439 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
440 // tools like cvtres write a size of 0 for an empty table instead of 4.
441 if (StringTableSize < 4)
444 // Check that the string table is null terminated if has any in it.
445 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
446 return object_error::parse_failed;
447 return object_error::success;
450 // Returns the file offset for the given VA.
451 error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
452 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
453 : (uint64_t)PE32PlusHeader->ImageBase;
454 uint64_t Rva = Addr - ImageBase;
455 assert(Rva <= UINT32_MAX);
456 return getRvaPtr((uint32_t)Rva, Res);
459 // Returns the file offset for the given RVA.
460 error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
461 for (const SectionRef &S : sections()) {
462 const coff_section *Section = getCOFFSection(S);
463 uint32_t SectionStart = Section->VirtualAddress;
464 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
465 if (SectionStart <= Addr && Addr < SectionEnd) {
466 uint32_t Offset = Addr - SectionStart;
467 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
468 return object_error::success;
471 return object_error::parse_failed;
474 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
476 error_code COFFObjectFile::
477 getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const {
478 uintptr_t IntPtr = 0;
479 if (error_code EC = getRvaPtr(Rva, IntPtr))
481 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
482 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
483 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
484 return object_error::success;
487 // Find the import table.
488 error_code COFFObjectFile::initImportTablePtr() {
489 // First, we get the RVA of the import table. If the file lacks a pointer to
490 // the import table, do nothing.
491 const data_directory *DataEntry;
492 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
493 return object_error::success;
495 // Do nothing if the pointer to import table is NULL.
496 if (DataEntry->RelativeVirtualAddress == 0)
497 return object_error::success;
499 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
500 NumberOfImportDirectory = DataEntry->Size /
501 sizeof(import_directory_table_entry);
503 // Find the section that contains the RVA. This is needed because the RVA is
504 // the import table's memory address which is different from its file offset.
505 uintptr_t IntPtr = 0;
506 if (error_code EC = getRvaPtr(ImportTableRva, IntPtr))
508 ImportDirectory = reinterpret_cast<
509 const import_directory_table_entry *>(IntPtr);
510 return object_error::success;
513 // Find the export table.
514 error_code COFFObjectFile::initExportTablePtr() {
515 // First, we get the RVA of the export table. If the file lacks a pointer to
516 // the export table, do nothing.
517 const data_directory *DataEntry;
518 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
519 return object_error::success;
521 // Do nothing if the pointer to export table is NULL.
522 if (DataEntry->RelativeVirtualAddress == 0)
523 return object_error::success;
525 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
526 uintptr_t IntPtr = 0;
527 if (error_code EC = getRvaPtr(ExportTableRva, IntPtr))
530 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
531 return object_error::success;
534 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC,
536 : ObjectFile(Binary::ID_COFF, Object, BufferOwned), COFFHeader(0),
537 PE32Header(0), PE32PlusHeader(0), DataDirectory(0), SectionTable(0),
538 SymbolTable(0), StringTable(0), StringTableSize(0), ImportDirectory(0),
539 NumberOfImportDirectory(0), ExportDirectory(0) {
540 // Check that we at least have enough room for a header.
541 if (!checkSize(Data, EC, sizeof(coff_file_header))) return;
543 // The current location in the file where we are looking at.
546 // PE header is optional and is present only in executables. If it exists,
547 // it is placed right after COFF header.
548 bool HasPEHeader = false;
550 // Check if this is a PE/COFF file.
551 if (base()[0] == 0x4d && base()[1] == 0x5a) {
552 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
553 // PE signature to find 'normal' COFF header.
554 if (!checkSize(Data, EC, 0x3c + 8)) return;
555 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
556 // Check the PE magic bytes. ("PE\0\0")
557 if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
558 EC = object_error::parse_failed;
561 CurPtr += 4; // Skip the PE magic bytes.
565 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
567 CurPtr += sizeof(coff_file_header);
570 const pe32_header *Header;
571 if ((EC = getObject(Header, Data, base() + CurPtr)))
574 const uint8_t *DataDirAddr;
575 uint64_t DataDirSize;
576 if (Header->Magic == 0x10b) {
578 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
579 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
580 } else if (Header->Magic == 0x20b) {
581 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
582 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
583 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
585 // It's neither PE32 nor PE32+.
586 EC = object_error::parse_failed;
589 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
591 CurPtr += COFFHeader->SizeOfOptionalHeader;
594 if (COFFHeader->isImportLibrary())
597 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
598 COFFHeader->NumberOfSections * sizeof(coff_section))))
601 // Initialize the pointer to the symbol table.
602 if (COFFHeader->PointerToSymbolTable != 0)
603 if ((EC = initSymbolTablePtr()))
606 // Initialize the pointer to the beginning of the import table.
607 if ((EC = initImportTablePtr()))
610 // Initialize the pointer to the export table.
611 if ((EC = initExportTablePtr()))
614 EC = object_error::success;
617 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
619 Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
620 return basic_symbol_iterator(SymbolRef(Ret, this));
623 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
624 // The symbol table ends where the string table begins.
626 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
627 return basic_symbol_iterator(SymbolRef(Ret, this));
630 library_iterator COFFObjectFile::needed_library_begin() const {
632 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
635 library_iterator COFFObjectFile::needed_library_end() const {
637 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
640 StringRef COFFObjectFile::getLoadName() const {
641 // COFF does not have this field.
645 import_directory_iterator COFFObjectFile::import_directory_begin() const {
646 return import_directory_iterator(
647 ImportDirectoryEntryRef(ImportDirectory, 0, this));
650 import_directory_iterator COFFObjectFile::import_directory_end() const {
651 return import_directory_iterator(
652 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
655 export_directory_iterator COFFObjectFile::export_directory_begin() const {
656 return export_directory_iterator(
657 ExportDirectoryEntryRef(ExportDirectory, 0, this));
660 export_directory_iterator COFFObjectFile::export_directory_end() const {
661 if (ExportDirectory == 0)
662 return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this));
663 ExportDirectoryEntryRef Ref(ExportDirectory,
664 ExportDirectory->AddressTableEntries, this);
665 return export_directory_iterator(Ref);
668 section_iterator COFFObjectFile::section_begin() const {
670 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
671 return section_iterator(SectionRef(Ret, this));
674 section_iterator COFFObjectFile::section_end() const {
676 int NumSections = COFFHeader->isImportLibrary()
677 ? 0 : COFFHeader->NumberOfSections;
678 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
679 return section_iterator(SectionRef(Ret, this));
682 uint8_t COFFObjectFile::getBytesInAddress() const {
683 return getArch() == Triple::x86_64 ? 8 : 4;
686 StringRef COFFObjectFile::getFileFormatName() const {
687 switch(COFFHeader->Machine) {
688 case COFF::IMAGE_FILE_MACHINE_I386:
690 case COFF::IMAGE_FILE_MACHINE_AMD64:
691 return "COFF-x86-64";
692 case COFF::IMAGE_FILE_MACHINE_ARMNT:
695 return "COFF-<unknown arch>";
699 unsigned COFFObjectFile::getArch() const {
700 switch(COFFHeader->Machine) {
701 case COFF::IMAGE_FILE_MACHINE_I386:
703 case COFF::IMAGE_FILE_MACHINE_AMD64:
704 return Triple::x86_64;
705 case COFF::IMAGE_FILE_MACHINE_ARMNT:
706 return Triple::thumb;
708 return Triple::UnknownArch;
712 // This method is kept here because lld uses this. As soon as we make
713 // lld to use getCOFFHeader, this method will be removed.
714 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
715 return getCOFFHeader(Res);
718 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
720 return object_error::success;
723 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
725 return object_error::success;
729 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
730 Res = PE32PlusHeader;
731 return object_error::success;
734 error_code COFFObjectFile::getDataDirectory(uint32_t Index,
735 const data_directory *&Res) const {
736 // Error if if there's no data directory or the index is out of range.
738 return object_error::parse_failed;
739 assert(PE32Header || PE32PlusHeader);
740 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
741 : PE32PlusHeader->NumberOfRvaAndSize;
743 return object_error::parse_failed;
744 Res = &DataDirectory[Index];
745 return object_error::success;
748 error_code COFFObjectFile::getSection(int32_t Index,
749 const coff_section *&Result) const {
750 // Check for special index values.
751 if (COFF::isReservedSectionNumber(Index))
753 else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
754 // We already verified the section table data, so no need to check again.
755 Result = SectionTable + (Index - 1);
757 return object_error::parse_failed;
758 return object_error::success;
761 error_code COFFObjectFile::getString(uint32_t Offset,
762 StringRef &Result) const {
763 if (StringTableSize <= 4)
764 // Tried to get a string from an empty string table.
765 return object_error::parse_failed;
766 if (Offset >= StringTableSize)
767 return object_error::unexpected_eof;
768 Result = StringRef(StringTable + Offset);
769 return object_error::success;
772 error_code COFFObjectFile::getSymbol(uint32_t Index,
773 const coff_symbol *&Result) const {
774 if (Index < COFFHeader->NumberOfSymbols)
775 Result = SymbolTable + Index;
777 return object_error::parse_failed;
778 return object_error::success;
781 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
782 StringRef &Res) const {
783 // Check for string table entry. First 4 bytes are 0.
784 if (Symbol->Name.Offset.Zeroes == 0) {
785 uint32_t Offset = Symbol->Name.Offset.Offset;
786 if (error_code EC = getString(Offset, Res))
788 return object_error::success;
791 if (Symbol->Name.ShortName[7] == 0)
792 // Null terminated, let ::strlen figure out the length.
793 Res = StringRef(Symbol->Name.ShortName);
795 // Not null terminated, use all 8 bytes.
796 Res = StringRef(Symbol->Name.ShortName, 8);
797 return object_error::success;
800 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
801 const coff_symbol *Symbol) const {
802 const uint8_t *Aux = NULL;
804 if (Symbol->NumberOfAuxSymbols > 0) {
805 // AUX data comes immediately after the symbol in COFF
806 Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
808 // Verify that the Aux symbol points to a valid entry in the symbol table.
809 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
810 if (Offset < COFFHeader->PointerToSymbolTable
811 || Offset >= COFFHeader->PointerToSymbolTable
812 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
813 report_fatal_error("Aux Symbol data was outside of symbol table.");
815 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
816 == 0 && "Aux Symbol data did not point to the beginning of a symbol");
819 return ArrayRef<uint8_t>(Aux,
820 Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
823 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
824 StringRef &Res) const {
826 if (Sec->Name[7] == 0)
827 // Null terminated, let ::strlen figure out the length.
830 // Not null terminated, use all 8 bytes.
831 Name = StringRef(Sec->Name, 8);
833 // Check for string table entry. First byte is '/'.
834 if (Name[0] == '/') {
836 if (Name[1] == '/') {
837 if (decodeBase64StringEntry(Name.substr(2), Offset))
838 return object_error::parse_failed;
840 if (Name.substr(1).getAsInteger(10, Offset))
841 return object_error::parse_failed;
843 if (error_code EC = getString(Offset, Name))
848 return object_error::success;
851 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
852 ArrayRef<uint8_t> &Res) const {
853 // The only thing that we need to verify is that the contents is contained
854 // within the file bounds. We don't need to make sure it doesn't cover other
855 // data, as there's nothing that says that is not allowed.
856 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
857 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
858 if (ConEnd > uintptr_t(Data->getBufferEnd()))
859 return object_error::parse_failed;
860 Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
862 return object_error::success;
865 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
866 return reinterpret_cast<const coff_relocation*>(Rel.p);
869 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
870 Rel.p = reinterpret_cast<uintptr_t>(
871 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
874 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
875 uint64_t &Res) const {
876 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
879 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
880 uint64_t &Res) const {
881 Res = toRel(Rel)->VirtualAddress;
882 return object_error::success;
885 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
886 const coff_relocation* R = toRel(Rel);
888 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
889 return symbol_iterator(SymbolRef(Ref, this));
892 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
893 uint64_t &Res) const {
894 const coff_relocation* R = toRel(Rel);
896 return object_error::success;
900 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
901 return toSec(Section.getRawDataRefImpl());
905 COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
906 return toSymb(Symbol.getRawDataRefImpl());
909 const coff_relocation *
910 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
911 return toRel(Reloc.getRawDataRefImpl());
914 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
915 case COFF::reloc_type: \
919 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
920 SmallVectorImpl<char> &Result) const {
921 const coff_relocation *Reloc = toRel(Rel);
923 switch (COFFHeader->Machine) {
924 case COFF::IMAGE_FILE_MACHINE_AMD64:
925 switch (Reloc->Type) {
926 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
927 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
928 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
929 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
930 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
931 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
932 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
933 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
934 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
935 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
936 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
937 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
938 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
939 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
940 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
941 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
942 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
947 case COFF::IMAGE_FILE_MACHINE_I386:
948 switch (Reloc->Type) {
949 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
950 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
951 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
952 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
953 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
954 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
955 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
956 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
957 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
958 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
959 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
967 Result.append(Res.begin(), Res.end());
968 return object_error::success;
971 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
973 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
974 SmallVectorImpl<char> &Result) const {
975 const coff_relocation *Reloc = toRel(Rel);
976 const coff_symbol *Symb = 0;
977 if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
979 Sym.p = reinterpret_cast<uintptr_t>(Symb);
981 if (error_code EC = getSymbolName(Sym, SymName)) return EC;
982 Result.append(SymName.begin(), SymName.end());
983 return object_error::success;
986 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
987 LibraryRef &Result) const {
988 report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
991 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
992 StringRef &Result) const {
993 report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
996 bool ImportDirectoryEntryRef::
997 operator==(const ImportDirectoryEntryRef &Other) const {
998 return ImportTable == Other.ImportTable && Index == Other.Index;
1001 void ImportDirectoryEntryRef::moveNext() {
1005 error_code ImportDirectoryEntryRef::
1006 getImportTableEntry(const import_directory_table_entry *&Result) const {
1007 Result = ImportTable;
1008 return object_error::success;
1011 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1012 uintptr_t IntPtr = 0;
1013 if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
1015 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1016 return object_error::success;
1019 error_code ImportDirectoryEntryRef::getImportLookupEntry(
1020 const import_lookup_table_entry32 *&Result) const {
1021 uintptr_t IntPtr = 0;
1023 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
1025 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1026 return object_error::success;
1029 bool ExportDirectoryEntryRef::
1030 operator==(const ExportDirectoryEntryRef &Other) const {
1031 return ExportTable == Other.ExportTable && Index == Other.Index;
1034 void ExportDirectoryEntryRef::moveNext() {
1038 // Returns the name of the current export symbol. If the symbol is exported only
1039 // by ordinal, the empty string is set as a result.
1040 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1041 uintptr_t IntPtr = 0;
1042 if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1044 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1045 return object_error::success;
1048 // Returns the starting ordinal number.
1049 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1050 Result = ExportTable->OrdinalBase;
1051 return object_error::success;
1054 // Returns the export ordinal of the current export symbol.
1055 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1056 Result = ExportTable->OrdinalBase + Index;
1057 return object_error::success;
1060 // Returns the address of the current export symbol.
1061 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1062 uintptr_t IntPtr = 0;
1063 if (error_code EC = OwningObject->getRvaPtr(
1064 ExportTable->ExportAddressTableRVA, IntPtr))
1066 const export_address_table_entry *entry =
1067 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1068 Result = entry[Index].ExportRVA;
1069 return object_error::success;
1072 // Returns the name of the current export symbol. If the symbol is exported only
1073 // by ordinal, the empty string is set as a result.
1074 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1075 uintptr_t IntPtr = 0;
1076 if (error_code EC = OwningObject->getRvaPtr(
1077 ExportTable->OrdinalTableRVA, IntPtr))
1079 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1081 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1083 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1084 I < E; ++I, ++Offset) {
1087 if (error_code EC = OwningObject->getRvaPtr(
1088 ExportTable->NamePointerRVA, IntPtr))
1090 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1091 if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1093 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1094 return object_error::success;
1097 return object_error::success;
1100 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object,
1103 std::unique_ptr<COFFObjectFile> Ret(
1104 new COFFObjectFile(Object, EC, BufferOwned));
1107 return Ret.release();