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"
24 using namespace object;
26 using support::ulittle8_t;
27 using support::ulittle16_t;
28 using support::ulittle32_t;
29 using support::little16_t;
31 // Returns false if size is greater than the buffer size. And sets ec.
32 static bool checkSize(const MemoryBuffer *M, error_code &EC, uint64_t Size) {
33 if (M->getBufferSize() < Size) {
34 EC = object_error::unexpected_eof;
40 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
41 // Returns unexpected_eof if error.
43 static error_code getObject(const T *&Obj, const MemoryBuffer *M,
44 const uint8_t *Ptr, const size_t Size = sizeof(T)) {
45 uintptr_t Addr = uintptr_t(Ptr);
46 if (Addr + Size < Addr ||
48 Addr + Size > uintptr_t(M->getBufferEnd())) {
49 return object_error::unexpected_eof;
51 Obj = reinterpret_cast<const T *>(Addr);
52 return object_error::success;
55 const coff_symbol *COFFObjectFile::toSymb(DataRefImpl Ref) const {
56 const coff_symbol *Addr = reinterpret_cast<const coff_symbol*>(Ref.p);
59 // Verify that the symbol points to a valid entry in the symbol table.
60 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
61 if (Offset < COFFHeader->PointerToSymbolTable
62 || Offset >= COFFHeader->PointerToSymbolTable
63 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
64 report_fatal_error("Symbol was outside of symbol table.");
66 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
67 == 0 && "Symbol did not point to the beginning of a symbol");
73 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
74 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
77 // Verify that the section points to a valid entry in the section table.
78 if (Addr < SectionTable
79 || Addr >= (SectionTable + COFFHeader->NumberOfSections))
80 report_fatal_error("Section was outside of section table.");
82 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
83 assert(Offset % sizeof(coff_section) == 0 &&
84 "Section did not point to the beginning of a section");
90 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
91 const coff_symbol *Symb = toSymb(Ref);
92 Symb += 1 + Symb->NumberOfAuxSymbols;
93 Ref.p = reinterpret_cast<uintptr_t>(Symb);
96 error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
97 StringRef &Result) const {
98 const coff_symbol *Symb = toSymb(Ref);
99 return getSymbolName(Symb, Result);
102 error_code COFFObjectFile::getSymbolFileOffset(DataRefImpl Ref,
103 uint64_t &Result) const {
104 const coff_symbol *Symb = toSymb(Ref);
105 const coff_section *Section = NULL;
106 if (error_code EC = getSection(Symb->SectionNumber, Section))
109 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
110 Result = UnknownAddressOrSize;
112 Result = Section->PointerToRawData + Symb->Value;
114 Result = Symb->Value;
115 return object_error::success;
118 error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
119 uint64_t &Result) const {
120 const coff_symbol *Symb = toSymb(Ref);
121 const coff_section *Section = NULL;
122 if (error_code EC = getSection(Symb->SectionNumber, Section))
125 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
126 Result = UnknownAddressOrSize;
128 Result = Section->VirtualAddress + Symb->Value;
130 Result = Symb->Value;
131 return object_error::success;
134 error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
135 SymbolRef::Type &Result) const {
136 const coff_symbol *Symb = toSymb(Ref);
137 Result = SymbolRef::ST_Other;
138 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
139 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
140 Result = SymbolRef::ST_Unknown;
141 } else if (Symb->getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION) {
142 Result = SymbolRef::ST_Function;
144 uint32_t Characteristics = 0;
145 if (Symb->SectionNumber > 0) {
146 const coff_section *Section = NULL;
147 if (error_code EC = getSection(Symb->SectionNumber, Section))
149 Characteristics = Section->Characteristics;
151 if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
152 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
153 Result = SymbolRef::ST_Data;
155 return object_error::success;
158 error_code COFFObjectFile::getSymbolFlags(DataRefImpl Ref,
159 uint32_t &Result) const {
160 const coff_symbol *Symb = toSymb(Ref);
161 Result = SymbolRef::SF_None;
163 // TODO: Correctly set SF_FormatSpecific, SF_ThreadLocal, SF_Common
165 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
166 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
167 Result |= SymbolRef::SF_Undefined;
169 // TODO: This are certainly too restrictive.
170 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
171 Result |= SymbolRef::SF_Global;
173 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
174 Result |= SymbolRef::SF_Weak;
176 if (Symb->SectionNumber == COFF::IMAGE_SYM_ABSOLUTE)
177 Result |= SymbolRef::SF_Absolute;
179 return object_error::success;
182 error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
183 uint64_t &Result) const {
184 // FIXME: Return the correct size. This requires looking at all the symbols
185 // in the same section as this symbol, and looking for either the next
186 // symbol, or the end of the section.
187 const coff_symbol *Symb = toSymb(Ref);
188 const coff_section *Section = NULL;
189 if (error_code EC = getSection(Symb->SectionNumber, Section))
192 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
193 Result = UnknownAddressOrSize;
195 Result = Section->SizeOfRawData - Symb->Value;
198 return object_error::success;
201 error_code COFFObjectFile::getSymbolSection(DataRefImpl Ref,
202 section_iterator &Result) const {
203 const coff_symbol *Symb = toSymb(Ref);
204 if (Symb->SectionNumber <= COFF::IMAGE_SYM_UNDEFINED)
205 Result = end_sections();
207 const coff_section *Sec = 0;
208 if (error_code EC = getSection(Symb->SectionNumber, Sec)) return EC;
210 Ref.p = reinterpret_cast<uintptr_t>(Sec);
211 Result = section_iterator(SectionRef(Ref, this));
213 return object_error::success;
216 error_code COFFObjectFile::getSymbolValue(DataRefImpl Ref,
217 uint64_t &Val) const {
218 report_fatal_error("getSymbolValue unimplemented in COFFObjectFile");
221 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
222 const coff_section *Sec = toSec(Ref);
224 Ref.p = reinterpret_cast<uintptr_t>(Sec);
227 error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
228 StringRef &Result) const {
229 const coff_section *Sec = toSec(Ref);
230 return getSectionName(Sec, Result);
233 error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
234 uint64_t &Result) const {
235 const coff_section *Sec = toSec(Ref);
236 Result = Sec->VirtualAddress;
237 return object_error::success;
240 error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
241 uint64_t &Result) const {
242 const coff_section *Sec = toSec(Ref);
243 Result = Sec->SizeOfRawData;
244 return object_error::success;
247 error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
248 StringRef &Result) const {
249 const coff_section *Sec = toSec(Ref);
250 ArrayRef<uint8_t> Res;
251 error_code EC = getSectionContents(Sec, Res);
252 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
256 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
257 uint64_t &Res) const {
258 const coff_section *Sec = toSec(Ref);
260 return object_error::parse_failed;
261 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
262 return object_error::success;
265 error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
266 bool &Result) const {
267 const coff_section *Sec = toSec(Ref);
268 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
269 return object_error::success;
272 error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
273 bool &Result) const {
274 const coff_section *Sec = toSec(Ref);
275 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
276 return object_error::success;
279 error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
280 bool &Result) const {
281 const coff_section *Sec = toSec(Ref);
282 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
283 return object_error::success;
286 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
287 bool &Result) const {
288 // FIXME: Unimplemented
290 return object_error::success;
293 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
294 bool &Result) const {
295 const coff_section *Sec = toSec(Ref);
296 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
297 return object_error::success;
300 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
301 bool &Result) const {
302 // FIXME: Unimplemented.
304 return object_error::success;
307 error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
308 bool &Result) const {
309 // FIXME: Unimplemented.
311 return object_error::success;
314 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
316 bool &Result) const {
317 const coff_section *Sec = toSec(SecRef);
318 const coff_symbol *Symb = toSymb(SymbRef);
319 const coff_section *SymbSec = 0;
320 if (error_code EC = getSection(Symb->SectionNumber, SymbSec)) return EC;
325 return object_error::success;
328 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
329 const coff_section *Sec = toSec(Ref);
331 if (Sec->NumberOfRelocations == 0)
334 Ret.p = reinterpret_cast<uintptr_t>(base() + Sec->PointerToRelocations);
336 return relocation_iterator(RelocationRef(Ret, this));
339 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
340 const coff_section *Sec = toSec(Ref);
342 if (Sec->NumberOfRelocations == 0)
345 Ret.p = reinterpret_cast<uintptr_t>(
346 reinterpret_cast<const coff_relocation*>(
347 base() + Sec->PointerToRelocations)
348 + Sec->NumberOfRelocations);
350 return relocation_iterator(RelocationRef(Ret, this));
353 // Initialize the pointer to the symbol table.
354 error_code COFFObjectFile::initSymbolTablePtr() {
355 if (error_code EC = getObject(
356 SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
357 COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
360 // Find string table. The first four byte of the string table contains the
361 // total size of the string table, including the size field itself. If the
362 // string table is empty, the value of the first four byte would be 4.
363 const uint8_t *StringTableAddr =
364 base() + COFFHeader->PointerToSymbolTable +
365 COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
366 const ulittle32_t *StringTableSizePtr;
367 if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
369 StringTableSize = *StringTableSizePtr;
371 getObject(StringTable, Data, StringTableAddr, StringTableSize))
374 // Check that the string table is null terminated if has any in it.
375 if (StringTableSize < 4 ||
376 (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0))
377 return object_error::parse_failed;
378 return object_error::success;
381 // Returns the file offset for the given RVA.
382 error_code COFFObjectFile::getRvaPtr(uint32_t Rva, uintptr_t &Res) const {
383 for (section_iterator I = begin_sections(), E = end_sections(); I != E;
385 const coff_section *Section = getCOFFSection(I);
386 uint32_t SectionStart = Section->VirtualAddress;
387 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
388 if (SectionStart <= Rva && Rva < SectionEnd) {
389 uint32_t Offset = Rva - SectionStart;
390 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
391 return object_error::success;
394 return object_error::parse_failed;
397 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
399 error_code COFFObjectFile::
400 getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const {
401 uintptr_t IntPtr = 0;
402 if (error_code EC = getRvaPtr(Rva, IntPtr))
404 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
405 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
406 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
407 return object_error::success;
410 // Find the import table.
411 error_code COFFObjectFile::initImportTablePtr() {
412 // First, we get the RVA of the import table. If the file lacks a pointer to
413 // the import table, do nothing.
414 const data_directory *DataEntry;
415 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
416 return object_error::success;
418 // Do nothing if the pointer to import table is NULL.
419 if (DataEntry->RelativeVirtualAddress == 0)
420 return object_error::success;
422 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
423 NumberOfImportDirectory = DataEntry->Size /
424 sizeof(import_directory_table_entry);
426 // Find the section that contains the RVA. This is needed because the RVA is
427 // the import table's memory address which is different from its file offset.
428 uintptr_t IntPtr = 0;
429 if (error_code EC = getRvaPtr(ImportTableRva, IntPtr))
431 ImportDirectory = reinterpret_cast<
432 const import_directory_table_entry *>(IntPtr);
433 return object_error::success;
436 // Find the export table.
437 error_code COFFObjectFile::initExportTablePtr() {
438 // First, we get the RVA of the export table. If the file lacks a pointer to
439 // the export table, do nothing.
440 const data_directory *DataEntry;
441 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
442 return object_error::success;
444 // Do nothing if the pointer to export table is NULL.
445 if (DataEntry->RelativeVirtualAddress == 0)
446 return object_error::success;
448 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
449 uintptr_t IntPtr = 0;
450 if (error_code EC = getRvaPtr(ExportTableRva, IntPtr))
453 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
454 return object_error::success;
457 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC,
459 : ObjectFile(Binary::ID_COFF, Object, BufferOwned), COFFHeader(0),
460 PE32Header(0), PE32PlusHeader(0), DataDirectory(0), SectionTable(0),
461 SymbolTable(0), StringTable(0), StringTableSize(0), ImportDirectory(0),
462 NumberOfImportDirectory(0), ExportDirectory(0) {
463 // Check that we at least have enough room for a header.
464 if (!checkSize(Data, EC, sizeof(coff_file_header))) return;
466 // The current location in the file where we are looking at.
469 // PE header is optional and is present only in executables. If it exists,
470 // it is placed right after COFF header.
471 bool HasPEHeader = false;
473 // Check if this is a PE/COFF file.
474 if (base()[0] == 0x4d && base()[1] == 0x5a) {
475 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
476 // PE signature to find 'normal' COFF header.
477 if (!checkSize(Data, EC, 0x3c + 8)) return;
478 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
479 // Check the PE magic bytes. ("PE\0\0")
480 if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
481 EC = object_error::parse_failed;
484 CurPtr += 4; // Skip the PE magic bytes.
488 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
490 CurPtr += sizeof(coff_file_header);
493 const pe32_header *Header;
494 if ((EC = getObject(Header, Data, base() + CurPtr)))
497 const uint8_t *DataDirAddr;
498 uint64_t DataDirSize;
499 if (Header->Magic == 0x10b) {
501 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
502 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
503 } else if (Header->Magic == 0x20b) {
504 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
505 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
506 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
508 // It's neither PE32 nor PE32+.
509 EC = object_error::parse_failed;
512 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
514 CurPtr += COFFHeader->SizeOfOptionalHeader;
517 if (COFFHeader->isImportLibrary())
520 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
521 COFFHeader->NumberOfSections * sizeof(coff_section))))
524 // Initialize the pointer to the symbol table.
525 if (COFFHeader->PointerToSymbolTable != 0)
526 if ((EC = initSymbolTablePtr()))
529 // Initialize the pointer to the beginning of the import table.
530 if ((EC = initImportTablePtr()))
533 // Initialize the pointer to the export table.
534 if ((EC = initExportTablePtr()))
537 EC = object_error::success;
540 symbol_iterator COFFObjectFile::begin_symbols() const {
542 Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
543 return symbol_iterator(SymbolRef(Ret, this));
546 symbol_iterator COFFObjectFile::end_symbols() const {
547 // The symbol table ends where the string table begins.
549 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
550 return symbol_iterator(SymbolRef(Ret, this));
553 library_iterator COFFObjectFile::begin_libraries_needed() const {
555 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
558 library_iterator COFFObjectFile::end_libraries_needed() const {
560 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
563 StringRef COFFObjectFile::getLoadName() const {
564 // COFF does not have this field.
568 import_directory_iterator COFFObjectFile::import_directory_begin() const {
569 return import_directory_iterator(
570 ImportDirectoryEntryRef(ImportDirectory, 0, this));
573 import_directory_iterator COFFObjectFile::import_directory_end() const {
574 return import_directory_iterator(
575 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
578 export_directory_iterator COFFObjectFile::export_directory_begin() const {
579 return export_directory_iterator(
580 ExportDirectoryEntryRef(ExportDirectory, 0, this));
583 export_directory_iterator COFFObjectFile::export_directory_end() const {
584 if (ExportDirectory == 0)
585 return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this));
586 ExportDirectoryEntryRef Ref(ExportDirectory,
587 ExportDirectory->AddressTableEntries, this);
588 return export_directory_iterator(Ref);
591 section_iterator COFFObjectFile::begin_sections() const {
593 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
594 return section_iterator(SectionRef(Ret, this));
597 section_iterator COFFObjectFile::end_sections() const {
599 int NumSections = COFFHeader->isImportLibrary()
600 ? 0 : COFFHeader->NumberOfSections;
601 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
602 return section_iterator(SectionRef(Ret, this));
605 uint8_t COFFObjectFile::getBytesInAddress() const {
606 return getArch() == Triple::x86_64 ? 8 : 4;
609 StringRef COFFObjectFile::getFileFormatName() const {
610 switch(COFFHeader->Machine) {
611 case COFF::IMAGE_FILE_MACHINE_I386:
613 case COFF::IMAGE_FILE_MACHINE_AMD64:
614 return "COFF-x86-64";
616 return "COFF-<unknown arch>";
620 unsigned COFFObjectFile::getArch() const {
621 switch(COFFHeader->Machine) {
622 case COFF::IMAGE_FILE_MACHINE_I386:
624 case COFF::IMAGE_FILE_MACHINE_AMD64:
625 return Triple::x86_64;
627 return Triple::UnknownArch;
631 // This method is kept here because lld uses this. As soon as we make
632 // lld to use getCOFFHeader, this method will be removed.
633 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
634 return getCOFFHeader(Res);
637 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
639 return object_error::success;
642 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
644 return object_error::success;
648 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
649 Res = PE32PlusHeader;
650 return object_error::success;
653 error_code COFFObjectFile::getDataDirectory(uint32_t Index,
654 const data_directory *&Res) const {
655 // Error if if there's no data directory or the index is out of range.
657 return object_error::parse_failed;
658 assert(PE32Header || PE32PlusHeader);
659 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
660 : PE32PlusHeader->NumberOfRvaAndSize;
662 return object_error::parse_failed;
663 Res = &DataDirectory[Index];
664 return object_error::success;
667 error_code COFFObjectFile::getSection(int32_t Index,
668 const coff_section *&Result) const {
669 // Check for special index values.
670 if (Index == COFF::IMAGE_SYM_UNDEFINED ||
671 Index == COFF::IMAGE_SYM_ABSOLUTE ||
672 Index == COFF::IMAGE_SYM_DEBUG)
674 else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
675 // We already verified the section table data, so no need to check again.
676 Result = SectionTable + (Index - 1);
678 return object_error::parse_failed;
679 return object_error::success;
682 error_code COFFObjectFile::getString(uint32_t Offset,
683 StringRef &Result) const {
684 if (StringTableSize <= 4)
685 // Tried to get a string from an empty string table.
686 return object_error::parse_failed;
687 if (Offset >= StringTableSize)
688 return object_error::unexpected_eof;
689 Result = StringRef(StringTable + Offset);
690 return object_error::success;
693 error_code COFFObjectFile::getSymbol(uint32_t Index,
694 const coff_symbol *&Result) const {
695 if (Index < COFFHeader->NumberOfSymbols)
696 Result = SymbolTable + Index;
698 return object_error::parse_failed;
699 return object_error::success;
702 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
703 StringRef &Res) const {
704 // Check for string table entry. First 4 bytes are 0.
705 if (Symbol->Name.Offset.Zeroes == 0) {
706 uint32_t Offset = Symbol->Name.Offset.Offset;
707 if (error_code EC = getString(Offset, Res))
709 return object_error::success;
712 if (Symbol->Name.ShortName[7] == 0)
713 // Null terminated, let ::strlen figure out the length.
714 Res = StringRef(Symbol->Name.ShortName);
716 // Not null terminated, use all 8 bytes.
717 Res = StringRef(Symbol->Name.ShortName, 8);
718 return object_error::success;
721 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
722 const coff_symbol *Symbol) const {
723 const uint8_t *Aux = NULL;
725 if (Symbol->NumberOfAuxSymbols > 0) {
726 // AUX data comes immediately after the symbol in COFF
727 Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
729 // Verify that the Aux symbol points to a valid entry in the symbol table.
730 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
731 if (Offset < COFFHeader->PointerToSymbolTable
732 || Offset >= COFFHeader->PointerToSymbolTable
733 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
734 report_fatal_error("Aux Symbol data was outside of symbol table.");
736 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
737 == 0 && "Aux Symbol data did not point to the beginning of a symbol");
740 return ArrayRef<uint8_t>(Aux,
741 Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
744 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
745 StringRef &Res) const {
747 if (Sec->Name[7] == 0)
748 // Null terminated, let ::strlen figure out the length.
751 // Not null terminated, use all 8 bytes.
752 Name = StringRef(Sec->Name, 8);
754 // Check for string table entry. First byte is '/'.
755 if (Name[0] == '/') {
757 if (Name.substr(1).getAsInteger(10, Offset))
758 return object_error::parse_failed;
759 if (error_code EC = getString(Offset, Name))
764 return object_error::success;
767 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
768 ArrayRef<uint8_t> &Res) const {
769 // The only thing that we need to verify is that the contents is contained
770 // within the file bounds. We don't need to make sure it doesn't cover other
771 // data, as there's nothing that says that is not allowed.
772 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
773 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
774 if (ConEnd > uintptr_t(Data->getBufferEnd()))
775 return object_error::parse_failed;
776 Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
778 return object_error::success;
781 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
782 return reinterpret_cast<const coff_relocation*>(Rel.p);
785 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
786 Rel.p = reinterpret_cast<uintptr_t>(
787 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
790 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
791 uint64_t &Res) const {
792 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
795 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
796 uint64_t &Res) const {
797 Res = toRel(Rel)->VirtualAddress;
798 return object_error::success;
801 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
802 const coff_relocation* R = toRel(Rel);
804 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
805 return symbol_iterator(SymbolRef(Ref, this));
808 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
809 uint64_t &Res) const {
810 const coff_relocation* R = toRel(Rel);
812 return object_error::success;
815 const coff_section *COFFObjectFile::getCOFFSection(section_iterator &It) const {
816 return toSec(It->getRawDataRefImpl());
819 const coff_symbol *COFFObjectFile::getCOFFSymbol(symbol_iterator &It) const {
820 return toSymb(It->getRawDataRefImpl());
823 const coff_relocation *COFFObjectFile::getCOFFRelocation(
824 relocation_iterator &It) const {
825 return toRel(It->getRawDataRefImpl());
828 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(enum) \
829 case COFF::enum: Res = #enum; break;
831 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
832 SmallVectorImpl<char> &Result) const {
833 const coff_relocation *Reloc = toRel(Rel);
835 switch (COFFHeader->Machine) {
836 case COFF::IMAGE_FILE_MACHINE_AMD64:
837 switch (Reloc->Type) {
838 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
839 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
840 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
841 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
842 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
843 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
844 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
845 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
846 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
847 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
848 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
849 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
850 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
851 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
852 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
853 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
854 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
859 case COFF::IMAGE_FILE_MACHINE_I386:
860 switch (Reloc->Type) {
861 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
862 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
863 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
864 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
865 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
866 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
867 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
868 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
869 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
870 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
871 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
879 Result.append(Res.begin(), Res.end());
880 return object_error::success;
883 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
885 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
886 SmallVectorImpl<char> &Result) const {
887 const coff_relocation *Reloc = toRel(Rel);
888 const coff_symbol *Symb = 0;
889 if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
891 Sym.p = reinterpret_cast<uintptr_t>(Symb);
893 if (error_code EC = getSymbolName(Sym, SymName)) return EC;
894 Result.append(SymName.begin(), SymName.end());
895 return object_error::success;
898 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
899 LibraryRef &Result) const {
900 report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
903 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
904 StringRef &Result) const {
905 report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
908 bool ImportDirectoryEntryRef::
909 operator==(const ImportDirectoryEntryRef &Other) const {
910 return ImportTable == Other.ImportTable && Index == Other.Index;
913 void ImportDirectoryEntryRef::moveNext() {
917 error_code ImportDirectoryEntryRef::
918 getImportTableEntry(const import_directory_table_entry *&Result) const {
919 Result = ImportTable;
920 return object_error::success;
923 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
924 uintptr_t IntPtr = 0;
925 if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
927 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
928 return object_error::success;
931 error_code ImportDirectoryEntryRef::getImportLookupEntry(
932 const import_lookup_table_entry32 *&Result) const {
933 uintptr_t IntPtr = 0;
935 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
937 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
938 return object_error::success;
941 bool ExportDirectoryEntryRef::
942 operator==(const ExportDirectoryEntryRef &Other) const {
943 return ExportTable == Other.ExportTable && Index == Other.Index;
946 void ExportDirectoryEntryRef::moveNext() {
950 // Returns the name of the current export symbol. If the symbol is exported only
951 // by ordinal, the empty string is set as a result.
952 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
953 uintptr_t IntPtr = 0;
954 if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
956 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
957 return object_error::success;
960 // Returns the starting ordinal number.
961 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
962 Result = ExportTable->OrdinalBase;
963 return object_error::success;
966 // Returns the export ordinal of the current export symbol.
967 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
968 Result = ExportTable->OrdinalBase + Index;
969 return object_error::success;
972 // Returns the address of the current export symbol.
973 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
974 uintptr_t IntPtr = 0;
975 if (error_code EC = OwningObject->getRvaPtr(
976 ExportTable->ExportAddressTableRVA, IntPtr))
978 const export_address_table_entry *entry =
979 reinterpret_cast<const export_address_table_entry *>(IntPtr);
980 Result = entry[Index].ExportRVA;
981 return object_error::success;
984 // Returns the name of the current export symbol. If the symbol is exported only
985 // by ordinal, the empty string is set as a result.
986 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
987 uintptr_t IntPtr = 0;
988 if (error_code EC = OwningObject->getRvaPtr(
989 ExportTable->OrdinalTableRVA, IntPtr))
991 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
993 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
995 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
996 I < E; ++I, ++Offset) {
999 if (error_code EC = OwningObject->getRvaPtr(
1000 ExportTable->NamePointerRVA, IntPtr))
1002 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1003 if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1005 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1006 return object_error::success;
1009 return object_error::success;
1012 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object,
1015 OwningPtr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC, BufferOwned));