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 error_code COFFObjectFile::getSymbolNext(DataRefImpl Ref,
91 SymbolRef &Result) const {
92 const coff_symbol *Symb = toSymb(Ref);
93 Symb += 1 + Symb->NumberOfAuxSymbols;
94 Ref.p = reinterpret_cast<uintptr_t>(Symb);
95 Result = SymbolRef(Ref, this);
96 return object_error::success;
99 error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
100 StringRef &Result) const {
101 const coff_symbol *Symb = toSymb(Ref);
102 return getSymbolName(Symb, Result);
105 error_code COFFObjectFile::getSymbolFileOffset(DataRefImpl Ref,
106 uint64_t &Result) const {
107 const coff_symbol *Symb = toSymb(Ref);
108 const coff_section *Section = NULL;
109 if (error_code EC = getSection(Symb->SectionNumber, Section))
112 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
113 Result = UnknownAddressOrSize;
115 Result = Section->PointerToRawData + Symb->Value;
117 Result = Symb->Value;
118 return object_error::success;
121 error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
122 uint64_t &Result) const {
123 const coff_symbol *Symb = toSymb(Ref);
124 const coff_section *Section = NULL;
125 if (error_code EC = getSection(Symb->SectionNumber, Section))
128 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
129 Result = UnknownAddressOrSize;
131 Result = Section->VirtualAddress + Symb->Value;
133 Result = Symb->Value;
134 return object_error::success;
137 error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
138 SymbolRef::Type &Result) const {
139 const coff_symbol *Symb = toSymb(Ref);
140 Result = SymbolRef::ST_Other;
141 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
142 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
143 Result = SymbolRef::ST_Unknown;
144 } else if (Symb->getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION) {
145 Result = SymbolRef::ST_Function;
147 uint32_t Characteristics = 0;
148 if (Symb->SectionNumber > 0) {
149 const coff_section *Section = NULL;
150 if (error_code EC = getSection(Symb->SectionNumber, Section))
152 Characteristics = Section->Characteristics;
154 if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
155 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
156 Result = SymbolRef::ST_Data;
158 return object_error::success;
161 error_code COFFObjectFile::getSymbolFlags(DataRefImpl Ref,
162 uint32_t &Result) const {
163 const coff_symbol *Symb = toSymb(Ref);
164 Result = SymbolRef::SF_None;
166 // TODO: Correctly set SF_FormatSpecific, SF_ThreadLocal, SF_Common
168 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
169 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
170 Result |= SymbolRef::SF_Undefined;
172 // TODO: This are certainly too restrictive.
173 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
174 Result |= SymbolRef::SF_Global;
176 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
177 Result |= SymbolRef::SF_Weak;
179 if (Symb->SectionNumber == COFF::IMAGE_SYM_ABSOLUTE)
180 Result |= SymbolRef::SF_Absolute;
182 return object_error::success;
185 error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
186 uint64_t &Result) const {
187 // FIXME: Return the correct size. This requires looking at all the symbols
188 // in the same section as this symbol, and looking for either the next
189 // symbol, or the end of the section.
190 const coff_symbol *Symb = toSymb(Ref);
191 const coff_section *Section = NULL;
192 if (error_code EC = getSection(Symb->SectionNumber, Section))
195 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
196 Result = UnknownAddressOrSize;
198 Result = Section->SizeOfRawData - Symb->Value;
201 return object_error::success;
204 error_code COFFObjectFile::getSymbolSection(DataRefImpl Ref,
205 section_iterator &Result) const {
206 const coff_symbol *Symb = toSymb(Ref);
207 if (Symb->SectionNumber <= COFF::IMAGE_SYM_UNDEFINED)
208 Result = end_sections();
210 const coff_section *Sec = 0;
211 if (error_code EC = getSection(Symb->SectionNumber, Sec)) return EC;
213 Ref.p = reinterpret_cast<uintptr_t>(Sec);
214 Result = section_iterator(SectionRef(Ref, this));
216 return object_error::success;
219 error_code COFFObjectFile::getSymbolValue(DataRefImpl Ref,
220 uint64_t &Val) const {
221 report_fatal_error("getSymbolValue unimplemented in COFFObjectFile");
224 error_code COFFObjectFile::getSectionNext(DataRefImpl Ref,
225 SectionRef &Result) const {
226 const coff_section *Sec = toSec(Ref);
228 Ref.p = reinterpret_cast<uintptr_t>(Sec);
229 Result = SectionRef(Ref, this);
230 return object_error::success;
233 error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
234 StringRef &Result) const {
235 const coff_section *Sec = toSec(Ref);
236 return getSectionName(Sec, Result);
239 error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
240 uint64_t &Result) const {
241 const coff_section *Sec = toSec(Ref);
242 Result = Sec->VirtualAddress;
243 return object_error::success;
246 error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
247 uint64_t &Result) const {
248 const coff_section *Sec = toSec(Ref);
249 Result = Sec->SizeOfRawData;
250 return object_error::success;
253 error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
254 StringRef &Result) const {
255 const coff_section *Sec = toSec(Ref);
256 ArrayRef<uint8_t> Res;
257 error_code EC = getSectionContents(Sec, Res);
258 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
262 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
263 uint64_t &Res) const {
264 const coff_section *Sec = toSec(Ref);
266 return object_error::parse_failed;
267 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
268 return object_error::success;
271 error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
272 bool &Result) const {
273 const coff_section *Sec = toSec(Ref);
274 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
275 return object_error::success;
278 error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
279 bool &Result) const {
280 const coff_section *Sec = toSec(Ref);
281 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
282 return object_error::success;
285 error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
286 bool &Result) const {
287 const coff_section *Sec = toSec(Ref);
288 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
289 return object_error::success;
292 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
293 bool &Result) const {
294 // FIXME: Unimplemented
296 return object_error::success;
299 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
300 bool &Result) const {
301 const coff_section *Sec = toSec(Ref);
302 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
303 return object_error::success;
306 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
307 bool &Result) const {
308 // FIXME: Unimplemented.
310 return object_error::success;
313 error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
314 bool &Result) const {
315 // FIXME: Unimplemented.
317 return object_error::success;
320 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
322 bool &Result) const {
323 const coff_section *Sec = toSec(SecRef);
324 const coff_symbol *Symb = toSymb(SymbRef);
325 const coff_section *SymbSec = 0;
326 if (error_code EC = getSection(Symb->SectionNumber, SymbSec)) return EC;
331 return object_error::success;
334 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
335 const coff_section *Sec = toSec(Ref);
337 if (Sec->NumberOfRelocations == 0)
340 Ret.p = reinterpret_cast<uintptr_t>(base() + Sec->PointerToRelocations);
342 return relocation_iterator(RelocationRef(Ret, this));
345 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
346 const coff_section *Sec = toSec(Ref);
348 if (Sec->NumberOfRelocations == 0)
351 Ret.p = reinterpret_cast<uintptr_t>(
352 reinterpret_cast<const coff_relocation*>(
353 base() + Sec->PointerToRelocations)
354 + Sec->NumberOfRelocations);
356 return relocation_iterator(RelocationRef(Ret, this));
359 // Initialize the pointer to the symbol table.
360 error_code COFFObjectFile::initSymbolTablePtr() {
361 if (error_code EC = getObject(
362 SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
363 COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
366 // Find string table. The first four byte of the string table contains the
367 // total size of the string table, including the size field itself. If the
368 // string table is empty, the value of the first four byte would be 4.
369 const uint8_t *StringTableAddr =
370 base() + COFFHeader->PointerToSymbolTable +
371 COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
372 const ulittle32_t *StringTableSizePtr;
373 if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
375 StringTableSize = *StringTableSizePtr;
377 getObject(StringTable, Data, StringTableAddr, StringTableSize))
380 // Check that the string table is null terminated if has any in it.
381 if (StringTableSize < 4 ||
382 (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0))
383 return object_error::parse_failed;
384 return object_error::success;
387 // Returns the file offset for the given RVA.
388 error_code COFFObjectFile::getRvaPtr(uint32_t Rva, uintptr_t &Res) const {
390 for (section_iterator I = begin_sections(), E = end_sections(); I != E;
394 const coff_section *Section = getCOFFSection(I);
395 uint32_t SectionStart = Section->VirtualAddress;
396 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
397 if (SectionStart <= Rva && Rva < SectionEnd) {
398 uint32_t Offset = Rva - SectionStart;
399 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
400 return object_error::success;
403 return object_error::parse_failed;
406 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
408 error_code COFFObjectFile::
409 getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const {
410 uintptr_t IntPtr = 0;
411 if (error_code EC = getRvaPtr(Rva, IntPtr))
413 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
414 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
415 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
416 return object_error::success;
419 // Find the import table.
420 error_code COFFObjectFile::initImportTablePtr() {
421 // First, we get the RVA of the import table. If the file lacks a pointer to
422 // the import table, do nothing.
423 const data_directory *DataEntry;
424 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
425 return object_error::success;
427 // Do nothing if the pointer to import table is NULL.
428 if (DataEntry->RelativeVirtualAddress == 0)
429 return object_error::success;
431 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
432 NumberOfImportDirectory = DataEntry->Size /
433 sizeof(import_directory_table_entry);
435 // Find the section that contains the RVA. This is needed because the RVA is
436 // the import table's memory address which is different from its file offset.
437 uintptr_t IntPtr = 0;
438 if (error_code EC = getRvaPtr(ImportTableRva, IntPtr))
440 ImportDirectory = reinterpret_cast<
441 const import_directory_table_entry *>(IntPtr);
442 return object_error::success;
445 // Find the export table.
446 error_code COFFObjectFile::initExportTablePtr() {
447 // First, we get the RVA of the export table. If the file lacks a pointer to
448 // the export table, do nothing.
449 const data_directory *DataEntry;
450 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
451 return object_error::success;
453 // Do nothing if the pointer to export table is NULL.
454 if (DataEntry->RelativeVirtualAddress == 0)
455 return object_error::success;
457 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
458 uintptr_t IntPtr = 0;
459 if (error_code EC = getRvaPtr(ExportTableRva, IntPtr))
462 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
463 return object_error::success;
466 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC,
468 : ObjectFile(Binary::ID_COFF, Object, BufferOwned), COFFHeader(0),
469 PE32Header(0), DataDirectory(0), SectionTable(0), SymbolTable(0),
470 StringTable(0), StringTableSize(0), ImportDirectory(0),
471 NumberOfImportDirectory(0), ExportDirectory(0) {
472 // Check that we at least have enough room for a header.
473 if (!checkSize(Data, EC, sizeof(coff_file_header))) return;
475 // The current location in the file where we are looking at.
478 // PE header is optional and is present only in executables. If it exists,
479 // it is placed right after COFF header.
480 bool HasPEHeader = false;
482 // Check if this is a PE/COFF file.
483 if (base()[0] == 0x4d && base()[1] == 0x5a) {
484 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
485 // PE signature to find 'normal' COFF header.
486 if (!checkSize(Data, EC, 0x3c + 8)) return;
487 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
488 // Check the PE magic bytes. ("PE\0\0")
489 if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
490 EC = object_error::parse_failed;
493 CurPtr += 4; // Skip the PE magic bytes.
497 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
499 CurPtr += sizeof(coff_file_header);
502 if ((EC = getObject(PE32Header, Data, base() + CurPtr)))
504 if (PE32Header->Magic != 0x10b) {
505 // We only support PE32. If this is PE32 (not PE32+), the magic byte
506 // should be 0x10b. If this is not PE32, continue as if there's no PE
507 // header in this file.
509 } else if (PE32Header->NumberOfRvaAndSize > 0) {
510 const uint8_t *Addr = base() + CurPtr + sizeof(pe32_header);
511 uint64_t size = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
512 if ((EC = getObject(DataDirectory, Data, Addr, size)))
515 CurPtr += COFFHeader->SizeOfOptionalHeader;
518 if (COFFHeader->isImportLibrary())
521 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
522 COFFHeader->NumberOfSections * sizeof(coff_section))))
525 // Initialize the pointer to the symbol table.
526 if (COFFHeader->PointerToSymbolTable != 0)
527 if ((EC = initSymbolTablePtr()))
530 // Initialize the pointer to the beginning of the import table.
531 if ((EC = initImportTablePtr()))
534 // Initialize the pointer to the export table.
535 if ((EC = initExportTablePtr()))
538 EC = object_error::success;
541 symbol_iterator COFFObjectFile::begin_symbols() const {
543 Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
544 return symbol_iterator(SymbolRef(Ret, this));
547 symbol_iterator COFFObjectFile::end_symbols() const {
548 // The symbol table ends where the string table begins.
550 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
551 return symbol_iterator(SymbolRef(Ret, this));
554 symbol_iterator COFFObjectFile::begin_dynamic_symbols() const {
556 report_fatal_error("Dynamic symbols unimplemented in COFFObjectFile");
559 symbol_iterator COFFObjectFile::end_dynamic_symbols() const {
561 report_fatal_error("Dynamic symbols unimplemented in COFFObjectFile");
564 library_iterator COFFObjectFile::begin_libraries_needed() const {
566 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
569 library_iterator COFFObjectFile::end_libraries_needed() const {
571 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
574 StringRef COFFObjectFile::getLoadName() const {
575 // COFF does not have this field.
579 import_directory_iterator COFFObjectFile::import_directory_begin() const {
580 return import_directory_iterator(
581 ImportDirectoryEntryRef(ImportDirectory, 0, this));
584 import_directory_iterator COFFObjectFile::import_directory_end() const {
585 return import_directory_iterator(
586 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
589 export_directory_iterator COFFObjectFile::export_directory_begin() const {
590 return export_directory_iterator(
591 ExportDirectoryEntryRef(ExportDirectory, 0, this));
594 export_directory_iterator COFFObjectFile::export_directory_end() const {
595 if (ExportDirectory == 0)
596 return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this));
597 ExportDirectoryEntryRef Ref(ExportDirectory,
598 ExportDirectory->AddressTableEntries, this);
599 return export_directory_iterator(Ref);
602 section_iterator COFFObjectFile::begin_sections() const {
604 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
605 return section_iterator(SectionRef(Ret, this));
608 section_iterator COFFObjectFile::end_sections() const {
610 int NumSections = COFFHeader->isImportLibrary()
611 ? 0 : COFFHeader->NumberOfSections;
612 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
613 return section_iterator(SectionRef(Ret, this));
616 uint8_t COFFObjectFile::getBytesInAddress() const {
617 return getArch() == Triple::x86_64 ? 8 : 4;
620 StringRef COFFObjectFile::getFileFormatName() const {
621 switch(COFFHeader->Machine) {
622 case COFF::IMAGE_FILE_MACHINE_I386:
624 case COFF::IMAGE_FILE_MACHINE_AMD64:
625 return "COFF-x86-64";
627 return "COFF-<unknown arch>";
631 unsigned COFFObjectFile::getArch() const {
632 switch(COFFHeader->Machine) {
633 case COFF::IMAGE_FILE_MACHINE_I386:
635 case COFF::IMAGE_FILE_MACHINE_AMD64:
636 return Triple::x86_64;
638 return Triple::UnknownArch;
642 // This method is kept here because lld uses this. As soon as we make
643 // lld to use getCOFFHeader, this method will be removed.
644 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
645 return getCOFFHeader(Res);
648 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
650 return object_error::success;
653 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
655 return object_error::success;
658 error_code COFFObjectFile::getDataDirectory(uint32_t Index,
659 const data_directory *&Res) const {
660 // Error if if there's no data directory or the index is out of range.
661 if (!DataDirectory || Index > PE32Header->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 error_code COFFObjectFile::getRelocationNext(DataRefImpl Rel,
786 RelocationRef &Res) const {
787 Rel.p = reinterpret_cast<uintptr_t>(
788 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
789 Res = RelocationRef(Rel, this);
790 return object_error::success;
793 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
794 uint64_t &Res) const {
795 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
798 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
799 uint64_t &Res) const {
800 Res = toRel(Rel)->VirtualAddress;
801 return object_error::success;
804 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
805 const coff_relocation* R = toRel(Rel);
807 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
808 return symbol_iterator(SymbolRef(Ref, this));
811 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
812 uint64_t &Res) const {
813 const coff_relocation* R = toRel(Rel);
815 return object_error::success;
818 const coff_section *COFFObjectFile::getCOFFSection(section_iterator &It) const {
819 return toSec(It->getRawDataRefImpl());
822 const coff_symbol *COFFObjectFile::getCOFFSymbol(symbol_iterator &It) const {
823 return toSymb(It->getRawDataRefImpl());
826 const coff_relocation *COFFObjectFile::getCOFFRelocation(
827 relocation_iterator &It) const {
828 return toRel(It->getRawDataRefImpl());
831 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(enum) \
832 case COFF::enum: Res = #enum; break;
834 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
835 SmallVectorImpl<char> &Result) const {
836 const coff_relocation *Reloc = toRel(Rel);
838 switch (COFFHeader->Machine) {
839 case COFF::IMAGE_FILE_MACHINE_AMD64:
840 switch (Reloc->Type) {
841 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
842 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
843 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
844 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
845 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
846 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
847 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
848 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
849 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
850 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
851 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
852 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
853 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
854 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
855 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
856 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
857 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
862 case COFF::IMAGE_FILE_MACHINE_I386:
863 switch (Reloc->Type) {
864 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
865 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
866 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
867 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
868 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
869 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
870 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
871 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
872 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
873 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
874 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
882 Result.append(Res.begin(), Res.end());
883 return object_error::success;
886 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
888 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
889 SmallVectorImpl<char> &Result) const {
890 const coff_relocation *Reloc = toRel(Rel);
891 const coff_symbol *Symb = 0;
892 if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
894 Sym.p = reinterpret_cast<uintptr_t>(Symb);
896 if (error_code EC = getSymbolName(Sym, SymName)) return EC;
897 Result.append(SymName.begin(), SymName.end());
898 return object_error::success;
901 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
902 LibraryRef &Result) const {
903 report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
906 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
907 StringRef &Result) const {
908 report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
911 bool ImportDirectoryEntryRef::
912 operator==(const ImportDirectoryEntryRef &Other) const {
913 return ImportTable == Other.ImportTable && Index == Other.Index;
917 ImportDirectoryEntryRef::getNext(ImportDirectoryEntryRef &Result) const {
918 Result = ImportDirectoryEntryRef(ImportTable, Index + 1, OwningObject);
919 return object_error::success;
922 error_code ImportDirectoryEntryRef::
923 getImportTableEntry(const import_directory_table_entry *&Result) const {
924 Result = ImportTable;
925 return object_error::success;
928 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
929 uintptr_t IntPtr = 0;
930 if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
932 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
933 return object_error::success;
936 error_code ImportDirectoryEntryRef::getImportLookupEntry(
937 const import_lookup_table_entry32 *&Result) const {
938 uintptr_t IntPtr = 0;
940 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
942 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
943 return object_error::success;
946 bool ExportDirectoryEntryRef::
947 operator==(const ExportDirectoryEntryRef &Other) const {
948 return ExportTable == Other.ExportTable && Index == Other.Index;
952 ExportDirectoryEntryRef::getNext(ExportDirectoryEntryRef &Result) const {
953 Result = ExportDirectoryEntryRef(ExportTable, Index + 1, OwningObject);
954 return object_error::success;
957 // Returns the name of the current export symbol. If the symbol is exported only
958 // by ordinal, the empty string is set as a result.
959 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
960 uintptr_t IntPtr = 0;
961 if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
963 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
964 return object_error::success;
967 // Returns the starting ordinal number.
968 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
969 Result = ExportTable->OrdinalBase;
970 return object_error::success;
973 // Returns the export ordinal of the current export symbol.
974 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
975 Result = ExportTable->OrdinalBase + Index;
976 return object_error::success;
979 // Returns the address of the current export symbol.
980 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
981 uintptr_t IntPtr = 0;
982 if (error_code EC = OwningObject->getRvaPtr(
983 ExportTable->ExportAddressTableRVA, IntPtr))
985 const export_address_table_entry *entry =
986 reinterpret_cast<const export_address_table_entry *>(IntPtr);
987 Result = entry[Index].ExportRVA;
988 return object_error::success;
991 // Returns the name of the current export symbol. If the symbol is exported only
992 // by ordinal, the empty string is set as a result.
993 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
994 uintptr_t IntPtr = 0;
995 if (error_code EC = OwningObject->getRvaPtr(
996 ExportTable->OrdinalTableRVA, IntPtr))
998 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1000 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1002 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1003 I < E; ++I, ++Offset) {
1006 if (error_code EC = OwningObject->getRvaPtr(
1007 ExportTable->NamePointerRVA, IntPtr))
1009 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1010 if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1012 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1013 return object_error::success;
1016 return object_error::success;
1019 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object,
1022 OwningPtr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC, BufferOwned));