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 symbol_iterator COFFObjectFile::begin_dynamic_symbols() const {
555 report_fatal_error("Dynamic symbols unimplemented in COFFObjectFile");
558 symbol_iterator COFFObjectFile::end_dynamic_symbols() const {
560 report_fatal_error("Dynamic symbols unimplemented in COFFObjectFile");
563 library_iterator COFFObjectFile::begin_libraries_needed() const {
565 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
568 library_iterator COFFObjectFile::end_libraries_needed() const {
570 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
573 StringRef COFFObjectFile::getLoadName() const {
574 // COFF does not have this field.
578 import_directory_iterator COFFObjectFile::import_directory_begin() const {
579 return import_directory_iterator(
580 ImportDirectoryEntryRef(ImportDirectory, 0, this));
583 import_directory_iterator COFFObjectFile::import_directory_end() const {
584 return import_directory_iterator(
585 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
588 export_directory_iterator COFFObjectFile::export_directory_begin() const {
589 return export_directory_iterator(
590 ExportDirectoryEntryRef(ExportDirectory, 0, this));
593 export_directory_iterator COFFObjectFile::export_directory_end() const {
594 if (ExportDirectory == 0)
595 return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this));
596 ExportDirectoryEntryRef Ref(ExportDirectory,
597 ExportDirectory->AddressTableEntries, this);
598 return export_directory_iterator(Ref);
601 section_iterator COFFObjectFile::begin_sections() const {
603 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
604 return section_iterator(SectionRef(Ret, this));
607 section_iterator COFFObjectFile::end_sections() const {
609 int NumSections = COFFHeader->isImportLibrary()
610 ? 0 : COFFHeader->NumberOfSections;
611 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
612 return section_iterator(SectionRef(Ret, this));
615 uint8_t COFFObjectFile::getBytesInAddress() const {
616 return getArch() == Triple::x86_64 ? 8 : 4;
619 StringRef COFFObjectFile::getFileFormatName() const {
620 switch(COFFHeader->Machine) {
621 case COFF::IMAGE_FILE_MACHINE_I386:
623 case COFF::IMAGE_FILE_MACHINE_AMD64:
624 return "COFF-x86-64";
626 return "COFF-<unknown arch>";
630 unsigned COFFObjectFile::getArch() const {
631 switch(COFFHeader->Machine) {
632 case COFF::IMAGE_FILE_MACHINE_I386:
634 case COFF::IMAGE_FILE_MACHINE_AMD64:
635 return Triple::x86_64;
637 return Triple::UnknownArch;
641 // This method is kept here because lld uses this. As soon as we make
642 // lld to use getCOFFHeader, this method will be removed.
643 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
644 return getCOFFHeader(Res);
647 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
649 return object_error::success;
652 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
654 return object_error::success;
658 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
659 Res = PE32PlusHeader;
660 return object_error::success;
663 error_code COFFObjectFile::getDataDirectory(uint32_t Index,
664 const data_directory *&Res) const {
665 // Error if if there's no data directory or the index is out of range.
667 return object_error::parse_failed;
668 assert(PE32Header || PE32PlusHeader);
669 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
670 : PE32PlusHeader->NumberOfRvaAndSize;
672 return object_error::parse_failed;
673 Res = &DataDirectory[Index];
674 return object_error::success;
677 error_code COFFObjectFile::getSection(int32_t Index,
678 const coff_section *&Result) const {
679 // Check for special index values.
680 if (Index == COFF::IMAGE_SYM_UNDEFINED ||
681 Index == COFF::IMAGE_SYM_ABSOLUTE ||
682 Index == COFF::IMAGE_SYM_DEBUG)
684 else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
685 // We already verified the section table data, so no need to check again.
686 Result = SectionTable + (Index - 1);
688 return object_error::parse_failed;
689 return object_error::success;
692 error_code COFFObjectFile::getString(uint32_t Offset,
693 StringRef &Result) const {
694 if (StringTableSize <= 4)
695 // Tried to get a string from an empty string table.
696 return object_error::parse_failed;
697 if (Offset >= StringTableSize)
698 return object_error::unexpected_eof;
699 Result = StringRef(StringTable + Offset);
700 return object_error::success;
703 error_code COFFObjectFile::getSymbol(uint32_t Index,
704 const coff_symbol *&Result) const {
705 if (Index < COFFHeader->NumberOfSymbols)
706 Result = SymbolTable + Index;
708 return object_error::parse_failed;
709 return object_error::success;
712 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
713 StringRef &Res) const {
714 // Check for string table entry. First 4 bytes are 0.
715 if (Symbol->Name.Offset.Zeroes == 0) {
716 uint32_t Offset = Symbol->Name.Offset.Offset;
717 if (error_code EC = getString(Offset, Res))
719 return object_error::success;
722 if (Symbol->Name.ShortName[7] == 0)
723 // Null terminated, let ::strlen figure out the length.
724 Res = StringRef(Symbol->Name.ShortName);
726 // Not null terminated, use all 8 bytes.
727 Res = StringRef(Symbol->Name.ShortName, 8);
728 return object_error::success;
731 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
732 const coff_symbol *Symbol) const {
733 const uint8_t *Aux = NULL;
735 if (Symbol->NumberOfAuxSymbols > 0) {
736 // AUX data comes immediately after the symbol in COFF
737 Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
739 // Verify that the Aux symbol points to a valid entry in the symbol table.
740 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
741 if (Offset < COFFHeader->PointerToSymbolTable
742 || Offset >= COFFHeader->PointerToSymbolTable
743 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
744 report_fatal_error("Aux Symbol data was outside of symbol table.");
746 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
747 == 0 && "Aux Symbol data did not point to the beginning of a symbol");
750 return ArrayRef<uint8_t>(Aux,
751 Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
754 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
755 StringRef &Res) const {
757 if (Sec->Name[7] == 0)
758 // Null terminated, let ::strlen figure out the length.
761 // Not null terminated, use all 8 bytes.
762 Name = StringRef(Sec->Name, 8);
764 // Check for string table entry. First byte is '/'.
765 if (Name[0] == '/') {
767 if (Name.substr(1).getAsInteger(10, Offset))
768 return object_error::parse_failed;
769 if (error_code EC = getString(Offset, Name))
774 return object_error::success;
777 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
778 ArrayRef<uint8_t> &Res) const {
779 // The only thing that we need to verify is that the contents is contained
780 // within the file bounds. We don't need to make sure it doesn't cover other
781 // data, as there's nothing that says that is not allowed.
782 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
783 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
784 if (ConEnd > uintptr_t(Data->getBufferEnd()))
785 return object_error::parse_failed;
786 Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
788 return object_error::success;
791 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
792 return reinterpret_cast<const coff_relocation*>(Rel.p);
795 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
796 Rel.p = reinterpret_cast<uintptr_t>(
797 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
800 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
801 uint64_t &Res) const {
802 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
805 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
806 uint64_t &Res) const {
807 Res = toRel(Rel)->VirtualAddress;
808 return object_error::success;
811 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
812 const coff_relocation* R = toRel(Rel);
814 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
815 return symbol_iterator(SymbolRef(Ref, this));
818 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
819 uint64_t &Res) const {
820 const coff_relocation* R = toRel(Rel);
822 return object_error::success;
825 const coff_section *COFFObjectFile::getCOFFSection(section_iterator &It) const {
826 return toSec(It->getRawDataRefImpl());
829 const coff_symbol *COFFObjectFile::getCOFFSymbol(symbol_iterator &It) const {
830 return toSymb(It->getRawDataRefImpl());
833 const coff_relocation *COFFObjectFile::getCOFFRelocation(
834 relocation_iterator &It) const {
835 return toRel(It->getRawDataRefImpl());
838 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(enum) \
839 case COFF::enum: Res = #enum; break;
841 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
842 SmallVectorImpl<char> &Result) const {
843 const coff_relocation *Reloc = toRel(Rel);
845 switch (COFFHeader->Machine) {
846 case COFF::IMAGE_FILE_MACHINE_AMD64:
847 switch (Reloc->Type) {
848 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
849 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
850 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
851 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
852 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
853 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
854 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
855 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
856 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
857 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
858 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
859 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
860 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
861 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
862 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
863 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
864 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
869 case COFF::IMAGE_FILE_MACHINE_I386:
870 switch (Reloc->Type) {
871 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
872 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
873 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
874 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
875 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
876 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
877 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
878 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
879 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
880 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
881 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
889 Result.append(Res.begin(), Res.end());
890 return object_error::success;
893 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
895 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
896 SmallVectorImpl<char> &Result) const {
897 const coff_relocation *Reloc = toRel(Rel);
898 const coff_symbol *Symb = 0;
899 if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
901 Sym.p = reinterpret_cast<uintptr_t>(Symb);
903 if (error_code EC = getSymbolName(Sym, SymName)) return EC;
904 Result.append(SymName.begin(), SymName.end());
905 return object_error::success;
908 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
909 LibraryRef &Result) const {
910 report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
913 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
914 StringRef &Result) const {
915 report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
918 bool ImportDirectoryEntryRef::
919 operator==(const ImportDirectoryEntryRef &Other) const {
920 return ImportTable == Other.ImportTable && Index == Other.Index;
923 void ImportDirectoryEntryRef::moveNext() {
927 error_code ImportDirectoryEntryRef::
928 getImportTableEntry(const import_directory_table_entry *&Result) const {
929 Result = ImportTable;
930 return object_error::success;
933 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
934 uintptr_t IntPtr = 0;
935 if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
937 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
938 return object_error::success;
941 error_code ImportDirectoryEntryRef::getImportLookupEntry(
942 const import_lookup_table_entry32 *&Result) const {
943 uintptr_t IntPtr = 0;
945 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
947 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
948 return object_error::success;
951 bool ExportDirectoryEntryRef::
952 operator==(const ExportDirectoryEntryRef &Other) const {
953 return ExportTable == Other.ExportTable && Index == Other.Index;
956 void ExportDirectoryEntryRef::moveNext() {
960 // Returns the name of the current export symbol. If the symbol is exported only
961 // by ordinal, the empty string is set as a result.
962 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
963 uintptr_t IntPtr = 0;
964 if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
966 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
967 return object_error::success;
970 // Returns the starting ordinal number.
971 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
972 Result = ExportTable->OrdinalBase;
973 return object_error::success;
976 // Returns the export ordinal of the current export symbol.
977 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
978 Result = ExportTable->OrdinalBase + Index;
979 return object_error::success;
982 // Returns the address of the current export symbol.
983 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
984 uintptr_t IntPtr = 0;
985 if (error_code EC = OwningObject->getRvaPtr(
986 ExportTable->ExportAddressTableRVA, IntPtr))
988 const export_address_table_entry *entry =
989 reinterpret_cast<const export_address_table_entry *>(IntPtr);
990 Result = entry[Index].ExportRVA;
991 return object_error::success;
994 // Returns the name of the current export symbol. If the symbol is exported only
995 // by ordinal, the empty string is set as a result.
996 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
997 uintptr_t IntPtr = 0;
998 if (error_code EC = OwningObject->getRvaPtr(
999 ExportTable->OrdinalTableRVA, IntPtr))
1001 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1003 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1005 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1006 I < E; ++I, ++Offset) {
1009 if (error_code EC = OwningObject->getRvaPtr(
1010 ExportTable->NamePointerRVA, IntPtr))
1012 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1013 if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1015 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1016 return object_error::success;
1019 return object_error::success;
1022 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object,
1025 OwningPtr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC, BufferOwned));