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/Debug.h"
20 #include "llvm/Support/raw_ostream.h"
25 using namespace object;
27 using support::ulittle8_t;
28 using support::ulittle16_t;
29 using support::ulittle32_t;
30 using support::little16_t;
32 // Returns false if size is greater than the buffer size. And sets ec.
33 static bool checkSize(const MemoryBuffer *M, error_code &EC, uint64_t Size) {
34 if (M->getBufferSize() < Size) {
35 EC = object_error::unexpected_eof;
41 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
42 // Returns unexpected_eof if error.
44 static error_code getObject(const T *&Obj, const MemoryBuffer *M,
45 const uint8_t *Ptr, const size_t Size = sizeof(T)) {
46 uintptr_t Addr = uintptr_t(Ptr);
47 if (Addr + Size < Addr ||
49 Addr + Size > uintptr_t(M->getBufferEnd())) {
50 return object_error::unexpected_eof;
52 Obj = reinterpret_cast<const T *>(Addr);
53 return object_error::success;
56 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
58 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
59 assert(Str.size() <= 6 && "String too long, possible overflow.");
64 while (!Str.empty()) {
66 if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
67 CharVal = Str[0] - 'A';
68 else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
69 CharVal = Str[0] - 'a' + 26;
70 else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
71 CharVal = Str[0] - '0' + 52;
72 else if (Str[0] == '+') // 62
74 else if (Str[0] == '/') // 63
79 Value = (Value * 64) + CharVal;
83 if (Value > std::numeric_limits<uint32_t>::max())
86 Result = static_cast<uint32_t>(Value);
90 const coff_symbol *COFFObjectFile::toSymb(DataRefImpl Ref) const {
91 const coff_symbol *Addr = reinterpret_cast<const coff_symbol*>(Ref.p);
94 // Verify that the symbol points to a valid entry in the symbol table.
95 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
96 if (Offset < COFFHeader->PointerToSymbolTable
97 || Offset >= COFFHeader->PointerToSymbolTable
98 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
99 report_fatal_error("Symbol was outside of symbol table.");
101 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
102 == 0 && "Symbol did not point to the beginning of a symbol");
108 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
109 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
112 // Verify that the section points to a valid entry in the section table.
113 if (Addr < SectionTable
114 || Addr >= (SectionTable + COFFHeader->NumberOfSections))
115 report_fatal_error("Section was outside of section table.");
117 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
118 assert(Offset % sizeof(coff_section) == 0 &&
119 "Section did not point to the beginning of a section");
125 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
126 const coff_symbol *Symb = toSymb(Ref);
127 Symb += 1 + Symb->NumberOfAuxSymbols;
128 Ref.p = reinterpret_cast<uintptr_t>(Symb);
131 error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
132 StringRef &Result) const {
133 const coff_symbol *Symb = toSymb(Ref);
134 return getSymbolName(Symb, Result);
137 error_code COFFObjectFile::getSymbolFileOffset(DataRefImpl Ref,
138 uint64_t &Result) const {
139 const coff_symbol *Symb = toSymb(Ref);
140 const coff_section *Section = NULL;
141 if (error_code EC = getSection(Symb->SectionNumber, Section))
144 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
145 Result = UnknownAddressOrSize;
147 Result = Section->PointerToRawData + Symb->Value;
149 Result = Symb->Value;
150 return object_error::success;
153 error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
154 uint64_t &Result) const {
155 const coff_symbol *Symb = toSymb(Ref);
156 const coff_section *Section = NULL;
157 if (error_code EC = getSection(Symb->SectionNumber, Section))
160 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
161 Result = UnknownAddressOrSize;
163 Result = Section->VirtualAddress + Symb->Value;
165 Result = Symb->Value;
166 return object_error::success;
169 error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
170 SymbolRef::Type &Result) const {
171 const coff_symbol *Symb = toSymb(Ref);
172 Result = SymbolRef::ST_Other;
173 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
174 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
175 Result = SymbolRef::ST_Unknown;
176 } else if (Symb->getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION) {
177 Result = SymbolRef::ST_Function;
179 uint32_t Characteristics = 0;
180 if (Symb->SectionNumber > 0) {
181 const coff_section *Section = NULL;
182 if (error_code EC = getSection(Symb->SectionNumber, Section))
184 Characteristics = Section->Characteristics;
186 if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
187 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
188 Result = SymbolRef::ST_Data;
190 return object_error::success;
193 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
194 const coff_symbol *Symb = toSymb(Ref);
195 uint32_t Result = SymbolRef::SF_None;
197 // TODO: Correctly set SF_FormatSpecific, SF_Common
199 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
200 if (Symb->Value == 0)
201 Result |= SymbolRef::SF_Undefined;
203 Result |= SymbolRef::SF_Common;
207 // TODO: This are certainly too restrictive.
208 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
209 Result |= SymbolRef::SF_Global;
211 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
212 Result |= SymbolRef::SF_Weak;
214 if (Symb->SectionNumber == COFF::IMAGE_SYM_ABSOLUTE)
215 Result |= SymbolRef::SF_Absolute;
220 error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
221 uint64_t &Result) const {
222 // FIXME: Return the correct size. This requires looking at all the symbols
223 // in the same section as this symbol, and looking for either the next
224 // symbol, or the end of the section.
225 const coff_symbol *Symb = toSymb(Ref);
226 const coff_section *Section = NULL;
227 if (error_code EC = getSection(Symb->SectionNumber, Section))
230 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
231 Result = UnknownAddressOrSize;
233 Result = Section->SizeOfRawData - Symb->Value;
236 return object_error::success;
239 error_code COFFObjectFile::getSymbolSection(DataRefImpl Ref,
240 section_iterator &Result) const {
241 const coff_symbol *Symb = toSymb(Ref);
242 if (Symb->SectionNumber <= COFF::IMAGE_SYM_UNDEFINED)
243 Result = section_end();
245 const coff_section *Sec = 0;
246 if (error_code EC = getSection(Symb->SectionNumber, Sec)) return EC;
248 Ref.p = reinterpret_cast<uintptr_t>(Sec);
249 Result = section_iterator(SectionRef(Ref, this));
251 return object_error::success;
254 error_code COFFObjectFile::getSymbolValue(DataRefImpl Ref,
255 uint64_t &Val) const {
256 report_fatal_error("getSymbolValue unimplemented in COFFObjectFile");
259 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
260 const coff_section *Sec = toSec(Ref);
262 Ref.p = reinterpret_cast<uintptr_t>(Sec);
265 error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
266 StringRef &Result) const {
267 const coff_section *Sec = toSec(Ref);
268 return getSectionName(Sec, Result);
271 error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
272 uint64_t &Result) const {
273 const coff_section *Sec = toSec(Ref);
274 Result = Sec->VirtualAddress;
275 return object_error::success;
278 error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
279 uint64_t &Result) const {
280 const coff_section *Sec = toSec(Ref);
281 Result = Sec->SizeOfRawData;
282 return object_error::success;
285 error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
286 StringRef &Result) const {
287 const coff_section *Sec = toSec(Ref);
288 ArrayRef<uint8_t> Res;
289 error_code EC = getSectionContents(Sec, Res);
290 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
294 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
295 uint64_t &Res) const {
296 const coff_section *Sec = toSec(Ref);
298 return object_error::parse_failed;
299 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
300 return object_error::success;
303 error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
304 bool &Result) const {
305 const coff_section *Sec = toSec(Ref);
306 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
307 return object_error::success;
310 error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
311 bool &Result) const {
312 const coff_section *Sec = toSec(Ref);
313 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
314 return object_error::success;
317 error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
318 bool &Result) const {
319 const coff_section *Sec = toSec(Ref);
320 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
321 return object_error::success;
324 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
325 bool &Result) const {
326 // FIXME: Unimplemented
328 return object_error::success;
331 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
332 bool &Result) const {
333 const coff_section *Sec = toSec(Ref);
334 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
335 return object_error::success;
338 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
339 bool &Result) const {
340 // FIXME: Unimplemented.
342 return object_error::success;
345 error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
346 bool &Result) const {
347 // FIXME: Unimplemented.
349 return object_error::success;
352 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
354 bool &Result) const {
355 const coff_section *Sec = toSec(SecRef);
356 const coff_symbol *Symb = toSymb(SymbRef);
357 const coff_section *SymbSec = 0;
358 if (error_code EC = getSection(Symb->SectionNumber, SymbSec)) return EC;
363 return object_error::success;
366 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
367 const coff_section *Sec = toSec(Ref);
369 if (Sec->NumberOfRelocations == 0)
372 Ret.p = reinterpret_cast<uintptr_t>(base() + Sec->PointerToRelocations);
374 return relocation_iterator(RelocationRef(Ret, this));
377 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
378 const coff_section *Sec = toSec(Ref);
380 if (Sec->NumberOfRelocations == 0)
383 Ret.p = reinterpret_cast<uintptr_t>(
384 reinterpret_cast<const coff_relocation*>(
385 base() + Sec->PointerToRelocations)
386 + Sec->NumberOfRelocations);
388 return relocation_iterator(RelocationRef(Ret, this));
391 // Initialize the pointer to the symbol table.
392 error_code COFFObjectFile::initSymbolTablePtr() {
393 if (error_code EC = getObject(
394 SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
395 COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
398 // Find string table. The first four byte of the string table contains the
399 // total size of the string table, including the size field itself. If the
400 // string table is empty, the value of the first four byte would be 4.
401 const uint8_t *StringTableAddr =
402 base() + COFFHeader->PointerToSymbolTable +
403 COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
404 const ulittle32_t *StringTableSizePtr;
405 if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
407 StringTableSize = *StringTableSizePtr;
409 getObject(StringTable, Data, StringTableAddr, StringTableSize))
412 // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
413 // tools like cvtres write a size of 0 for an empty table instead of 4.
414 if (StringTableSize < 4)
417 // Check that the string table is null terminated if has any in it.
418 if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
419 return object_error::parse_failed;
420 return object_error::success;
423 // Returns the file offset for the given VA.
424 error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
425 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
426 : (uint64_t)PE32PlusHeader->ImageBase;
427 uint64_t Rva = Addr - ImageBase;
428 assert(Rva <= UINT32_MAX);
429 return getRvaPtr((uint32_t)Rva, Res);
432 // Returns the file offset for the given RVA.
433 error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
434 for (section_iterator I = section_begin(), E = section_end(); I != E;
436 const coff_section *Section = getCOFFSection(I);
437 uint32_t SectionStart = Section->VirtualAddress;
438 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
439 if (SectionStart <= Addr && Addr < SectionEnd) {
440 uint32_t Offset = Addr - SectionStart;
441 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
442 return object_error::success;
445 return object_error::parse_failed;
448 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
450 error_code COFFObjectFile::
451 getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const {
452 uintptr_t IntPtr = 0;
453 if (error_code EC = getRvaPtr(Rva, IntPtr))
455 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
456 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
457 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
458 return object_error::success;
461 // Find the import table.
462 error_code COFFObjectFile::initImportTablePtr() {
463 // First, we get the RVA of the import table. If the file lacks a pointer to
464 // the import table, do nothing.
465 const data_directory *DataEntry;
466 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
467 return object_error::success;
469 // Do nothing if the pointer to import table is NULL.
470 if (DataEntry->RelativeVirtualAddress == 0)
471 return object_error::success;
473 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
474 NumberOfImportDirectory = DataEntry->Size /
475 sizeof(import_directory_table_entry);
477 // Find the section that contains the RVA. This is needed because the RVA is
478 // the import table's memory address which is different from its file offset.
479 uintptr_t IntPtr = 0;
480 if (error_code EC = getRvaPtr(ImportTableRva, IntPtr))
482 ImportDirectory = reinterpret_cast<
483 const import_directory_table_entry *>(IntPtr);
484 return object_error::success;
487 // Find the export table.
488 error_code COFFObjectFile::initExportTablePtr() {
489 // First, we get the RVA of the export table. If the file lacks a pointer to
490 // the export table, do nothing.
491 const data_directory *DataEntry;
492 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
493 return object_error::success;
495 // Do nothing if the pointer to export table is NULL.
496 if (DataEntry->RelativeVirtualAddress == 0)
497 return object_error::success;
499 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
500 uintptr_t IntPtr = 0;
501 if (error_code EC = getRvaPtr(ExportTableRva, IntPtr))
504 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
505 return object_error::success;
508 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC,
510 : ObjectFile(Binary::ID_COFF, Object, BufferOwned), COFFHeader(0),
511 PE32Header(0), PE32PlusHeader(0), DataDirectory(0), SectionTable(0),
512 SymbolTable(0), StringTable(0), StringTableSize(0), ImportDirectory(0),
513 NumberOfImportDirectory(0), ExportDirectory(0) {
514 // Check that we at least have enough room for a header.
515 if (!checkSize(Data, EC, sizeof(coff_file_header))) return;
517 // The current location in the file where we are looking at.
520 // PE header is optional and is present only in executables. If it exists,
521 // it is placed right after COFF header.
522 bool HasPEHeader = false;
524 // Check if this is a PE/COFF file.
525 if (base()[0] == 0x4d && base()[1] == 0x5a) {
526 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
527 // PE signature to find 'normal' COFF header.
528 if (!checkSize(Data, EC, 0x3c + 8)) return;
529 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
530 // Check the PE magic bytes. ("PE\0\0")
531 if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
532 EC = object_error::parse_failed;
535 CurPtr += 4; // Skip the PE magic bytes.
539 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
541 CurPtr += sizeof(coff_file_header);
544 const pe32_header *Header;
545 if ((EC = getObject(Header, Data, base() + CurPtr)))
548 const uint8_t *DataDirAddr;
549 uint64_t DataDirSize;
550 if (Header->Magic == 0x10b) {
552 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
553 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
554 } else if (Header->Magic == 0x20b) {
555 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
556 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
557 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
559 // It's neither PE32 nor PE32+.
560 EC = object_error::parse_failed;
563 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
565 CurPtr += COFFHeader->SizeOfOptionalHeader;
568 if (COFFHeader->isImportLibrary())
571 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
572 COFFHeader->NumberOfSections * sizeof(coff_section))))
575 // Initialize the pointer to the symbol table.
576 if (COFFHeader->PointerToSymbolTable != 0)
577 if ((EC = initSymbolTablePtr()))
580 // Initialize the pointer to the beginning of the import table.
581 if ((EC = initImportTablePtr()))
584 // Initialize the pointer to the export table.
585 if ((EC = initExportTablePtr()))
588 EC = object_error::success;
591 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
593 Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
594 return basic_symbol_iterator(SymbolRef(Ret, this));
597 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
598 // The symbol table ends where the string table begins.
600 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
601 return basic_symbol_iterator(SymbolRef(Ret, this));
604 library_iterator COFFObjectFile::needed_library_begin() const {
606 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
609 library_iterator COFFObjectFile::needed_library_end() const {
611 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
614 StringRef COFFObjectFile::getLoadName() const {
615 // COFF does not have this field.
619 import_directory_iterator COFFObjectFile::import_directory_begin() const {
620 return import_directory_iterator(
621 ImportDirectoryEntryRef(ImportDirectory, 0, this));
624 import_directory_iterator COFFObjectFile::import_directory_end() const {
625 return import_directory_iterator(
626 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
629 export_directory_iterator COFFObjectFile::export_directory_begin() const {
630 return export_directory_iterator(
631 ExportDirectoryEntryRef(ExportDirectory, 0, this));
634 export_directory_iterator COFFObjectFile::export_directory_end() const {
635 if (ExportDirectory == 0)
636 return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this));
637 ExportDirectoryEntryRef Ref(ExportDirectory,
638 ExportDirectory->AddressTableEntries, this);
639 return export_directory_iterator(Ref);
642 section_iterator COFFObjectFile::section_begin() const {
644 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
645 return section_iterator(SectionRef(Ret, this));
648 section_iterator COFFObjectFile::section_end() const {
650 int NumSections = COFFHeader->isImportLibrary()
651 ? 0 : COFFHeader->NumberOfSections;
652 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
653 return section_iterator(SectionRef(Ret, this));
656 uint8_t COFFObjectFile::getBytesInAddress() const {
657 return getArch() == Triple::x86_64 ? 8 : 4;
660 StringRef COFFObjectFile::getFileFormatName() const {
661 switch(COFFHeader->Machine) {
662 case COFF::IMAGE_FILE_MACHINE_I386:
664 case COFF::IMAGE_FILE_MACHINE_AMD64:
665 return "COFF-x86-64";
667 return "COFF-<unknown arch>";
671 unsigned COFFObjectFile::getArch() const {
672 switch(COFFHeader->Machine) {
673 case COFF::IMAGE_FILE_MACHINE_I386:
675 case COFF::IMAGE_FILE_MACHINE_AMD64:
676 return Triple::x86_64;
678 return Triple::UnknownArch;
682 // This method is kept here because lld uses this. As soon as we make
683 // lld to use getCOFFHeader, this method will be removed.
684 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
685 return getCOFFHeader(Res);
688 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
690 return object_error::success;
693 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
695 return object_error::success;
699 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
700 Res = PE32PlusHeader;
701 return object_error::success;
704 error_code COFFObjectFile::getDataDirectory(uint32_t Index,
705 const data_directory *&Res) const {
706 // Error if if there's no data directory or the index is out of range.
708 return object_error::parse_failed;
709 assert(PE32Header || PE32PlusHeader);
710 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
711 : PE32PlusHeader->NumberOfRvaAndSize;
713 return object_error::parse_failed;
714 Res = &DataDirectory[Index];
715 return object_error::success;
718 error_code COFFObjectFile::getSection(int32_t Index,
719 const coff_section *&Result) const {
720 // Check for special index values.
721 if (Index == COFF::IMAGE_SYM_UNDEFINED ||
722 Index == COFF::IMAGE_SYM_ABSOLUTE ||
723 Index == COFF::IMAGE_SYM_DEBUG)
725 else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
726 // We already verified the section table data, so no need to check again.
727 Result = SectionTable + (Index - 1);
729 return object_error::parse_failed;
730 return object_error::success;
733 error_code COFFObjectFile::getString(uint32_t Offset,
734 StringRef &Result) const {
735 if (StringTableSize <= 4)
736 // Tried to get a string from an empty string table.
737 return object_error::parse_failed;
738 if (Offset >= StringTableSize)
739 return object_error::unexpected_eof;
740 Result = StringRef(StringTable + Offset);
741 return object_error::success;
744 error_code COFFObjectFile::getSymbol(uint32_t Index,
745 const coff_symbol *&Result) const {
746 if (Index < COFFHeader->NumberOfSymbols)
747 Result = SymbolTable + Index;
749 return object_error::parse_failed;
750 return object_error::success;
753 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
754 StringRef &Res) const {
755 // Check for string table entry. First 4 bytes are 0.
756 if (Symbol->Name.Offset.Zeroes == 0) {
757 uint32_t Offset = Symbol->Name.Offset.Offset;
758 if (error_code EC = getString(Offset, Res))
760 return object_error::success;
763 if (Symbol->Name.ShortName[7] == 0)
764 // Null terminated, let ::strlen figure out the length.
765 Res = StringRef(Symbol->Name.ShortName);
767 // Not null terminated, use all 8 bytes.
768 Res = StringRef(Symbol->Name.ShortName, 8);
769 return object_error::success;
772 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
773 const coff_symbol *Symbol) const {
774 const uint8_t *Aux = NULL;
776 if (Symbol->NumberOfAuxSymbols > 0) {
777 // AUX data comes immediately after the symbol in COFF
778 Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
780 // Verify that the Aux symbol points to a valid entry in the symbol table.
781 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
782 if (Offset < COFFHeader->PointerToSymbolTable
783 || Offset >= COFFHeader->PointerToSymbolTable
784 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
785 report_fatal_error("Aux Symbol data was outside of symbol table.");
787 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
788 == 0 && "Aux Symbol data did not point to the beginning of a symbol");
791 return ArrayRef<uint8_t>(Aux,
792 Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
795 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
796 StringRef &Res) const {
798 if (Sec->Name[7] == 0)
799 // Null terminated, let ::strlen figure out the length.
802 // Not null terminated, use all 8 bytes.
803 Name = StringRef(Sec->Name, 8);
805 // Check for string table entry. First byte is '/'.
806 if (Name[0] == '/') {
808 if (Name[1] == '/') {
809 if (decodeBase64StringEntry(Name.substr(2), Offset))
810 return object_error::parse_failed;
812 if (Name.substr(1).getAsInteger(10, Offset))
813 return object_error::parse_failed;
815 if (error_code EC = getString(Offset, Name))
820 return object_error::success;
823 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
824 ArrayRef<uint8_t> &Res) const {
825 // The only thing that we need to verify is that the contents is contained
826 // within the file bounds. We don't need to make sure it doesn't cover other
827 // data, as there's nothing that says that is not allowed.
828 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
829 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
830 if (ConEnd > uintptr_t(Data->getBufferEnd()))
831 return object_error::parse_failed;
832 Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
834 return object_error::success;
837 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
838 return reinterpret_cast<const coff_relocation*>(Rel.p);
841 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
842 Rel.p = reinterpret_cast<uintptr_t>(
843 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
846 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
847 uint64_t &Res) const {
848 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
851 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
852 uint64_t &Res) const {
853 Res = toRel(Rel)->VirtualAddress;
854 return object_error::success;
857 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
858 const coff_relocation* R = toRel(Rel);
860 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
861 return symbol_iterator(SymbolRef(Ref, this));
864 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
865 uint64_t &Res) const {
866 const coff_relocation* R = toRel(Rel);
868 return object_error::success;
871 const coff_section *COFFObjectFile::getCOFFSection(section_iterator &It) const {
872 return toSec(It->getRawDataRefImpl());
875 const coff_symbol *COFFObjectFile::getCOFFSymbol(symbol_iterator &It) const {
876 return toSymb(It->getRawDataRefImpl());
879 const coff_relocation *
880 COFFObjectFile::getCOFFRelocation(relocation_iterator &It) const {
881 return toRel(It->getRawDataRefImpl());
884 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(enum) \
885 case COFF::enum: Res = #enum; break;
887 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
888 SmallVectorImpl<char> &Result) const {
889 const coff_relocation *Reloc = toRel(Rel);
891 switch (COFFHeader->Machine) {
892 case COFF::IMAGE_FILE_MACHINE_AMD64:
893 switch (Reloc->Type) {
894 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
895 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
896 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
897 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
898 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
899 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
900 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
901 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
902 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
903 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
904 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
905 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
906 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
907 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
908 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
909 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
910 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
915 case COFF::IMAGE_FILE_MACHINE_I386:
916 switch (Reloc->Type) {
917 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
918 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
919 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
920 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
921 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
922 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
923 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
924 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
925 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
926 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
927 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
935 Result.append(Res.begin(), Res.end());
936 return object_error::success;
939 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
941 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
942 SmallVectorImpl<char> &Result) const {
943 const coff_relocation *Reloc = toRel(Rel);
944 const coff_symbol *Symb = 0;
945 if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
947 Sym.p = reinterpret_cast<uintptr_t>(Symb);
949 if (error_code EC = getSymbolName(Sym, SymName)) return EC;
950 Result.append(SymName.begin(), SymName.end());
951 return object_error::success;
954 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
955 LibraryRef &Result) const {
956 report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
959 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
960 StringRef &Result) const {
961 report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
964 bool ImportDirectoryEntryRef::
965 operator==(const ImportDirectoryEntryRef &Other) const {
966 return ImportTable == Other.ImportTable && Index == Other.Index;
969 void ImportDirectoryEntryRef::moveNext() {
973 error_code ImportDirectoryEntryRef::
974 getImportTableEntry(const import_directory_table_entry *&Result) const {
975 Result = ImportTable;
976 return object_error::success;
979 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
980 uintptr_t IntPtr = 0;
981 if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
983 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
984 return object_error::success;
987 error_code ImportDirectoryEntryRef::getImportLookupEntry(
988 const import_lookup_table_entry32 *&Result) const {
989 uintptr_t IntPtr = 0;
991 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
993 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
994 return object_error::success;
997 bool ExportDirectoryEntryRef::
998 operator==(const ExportDirectoryEntryRef &Other) const {
999 return ExportTable == Other.ExportTable && Index == Other.Index;
1002 void ExportDirectoryEntryRef::moveNext() {
1006 // Returns the name of the current export symbol. If the symbol is exported only
1007 // by ordinal, the empty string is set as a result.
1008 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1009 uintptr_t IntPtr = 0;
1010 if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1012 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1013 return object_error::success;
1016 // Returns the starting ordinal number.
1017 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1018 Result = ExportTable->OrdinalBase;
1019 return object_error::success;
1022 // Returns the export ordinal of the current export symbol.
1023 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1024 Result = ExportTable->OrdinalBase + Index;
1025 return object_error::success;
1028 // Returns the address of the current export symbol.
1029 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1030 uintptr_t IntPtr = 0;
1031 if (error_code EC = OwningObject->getRvaPtr(
1032 ExportTable->ExportAddressTableRVA, IntPtr))
1034 const export_address_table_entry *entry =
1035 reinterpret_cast<const export_address_table_entry *>(IntPtr);
1036 Result = entry[Index].ExportRVA;
1037 return object_error::success;
1040 // Returns the name of the current export symbol. If the symbol is exported only
1041 // by ordinal, the empty string is set as a result.
1042 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1043 uintptr_t IntPtr = 0;
1044 if (error_code EC = OwningObject->getRvaPtr(
1045 ExportTable->OrdinalTableRVA, IntPtr))
1047 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1049 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1051 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1052 I < E; ++I, ++Offset) {
1055 if (error_code EC = OwningObject->getRvaPtr(
1056 ExportTable->NamePointerRVA, IntPtr))
1058 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1059 if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1061 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1062 return object_error::success;
1065 return object_error::success;
1068 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object,
1071 OwningPtr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC, BufferOwned));
1074 return Ret.release();