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;
27 using support::ulittle8_t;
28 using support::ulittle16_t;
29 using support::ulittle32_t;
30 using support::little16_t;
34 // Returns false if size is greater than the buffer size. And sets ec.
35 bool checkSize(const MemoryBuffer *M, error_code &EC, uint64_t Size) {
36 if (M->getBufferSize() < Size) {
37 EC = object_error::unexpected_eof;
43 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
44 // Returns unexpected_eof if error.
46 error_code getObject(const T *&Obj, const MemoryBuffer *M, const uint8_t *Ptr,
47 const size_t Size = sizeof(T)) {
48 uintptr_t Addr = uintptr_t(Ptr);
49 if (Addr + Size < Addr ||
51 Addr + Size > uintptr_t(M->getBufferEnd())) {
52 return object_error::unexpected_eof;
54 Obj = reinterpret_cast<const T *>(Addr);
55 return object_error::success;
59 const coff_symbol *COFFObjectFile::toSymb(DataRefImpl Ref) const {
60 const coff_symbol *Addr = reinterpret_cast<const coff_symbol*>(Ref.p);
63 // Verify that the symbol points to a valid entry in the symbol table.
64 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
65 if (Offset < COFFHeader->PointerToSymbolTable
66 || Offset >= COFFHeader->PointerToSymbolTable
67 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
68 report_fatal_error("Symbol was outside of symbol table.");
70 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
71 == 0 && "Symbol did not point to the beginning of a symbol");
77 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
78 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
81 // Verify that the section points to a valid entry in the section table.
82 if (Addr < SectionTable
83 || Addr >= (SectionTable + COFFHeader->NumberOfSections))
84 report_fatal_error("Section was outside of section table.");
86 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
87 assert(Offset % sizeof(coff_section) == 0 &&
88 "Section did not point to the beginning of a section");
94 error_code COFFObjectFile::getSymbolNext(DataRefImpl Ref,
95 SymbolRef &Result) const {
96 const coff_symbol *Symb = toSymb(Ref);
97 Symb += 1 + Symb->NumberOfAuxSymbols;
98 Ref.p = reinterpret_cast<uintptr_t>(Symb);
99 Result = SymbolRef(Ref, this);
100 return object_error::success;
103 error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
104 StringRef &Result) const {
105 const coff_symbol *Symb = toSymb(Ref);
106 return getSymbolName(Symb, Result);
109 error_code COFFObjectFile::getSymbolFileOffset(DataRefImpl Ref,
110 uint64_t &Result) const {
111 const coff_symbol *Symb = toSymb(Ref);
112 const coff_section *Section = NULL;
113 if (error_code EC = getSection(Symb->SectionNumber, Section))
116 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
117 Result = UnknownAddressOrSize;
119 Result = Section->PointerToRawData + Symb->Value;
121 Result = Symb->Value;
122 return object_error::success;
125 error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
126 uint64_t &Result) const {
127 const coff_symbol *Symb = toSymb(Ref);
128 const coff_section *Section = NULL;
129 if (error_code EC = getSection(Symb->SectionNumber, Section))
132 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
133 Result = UnknownAddressOrSize;
135 Result = Section->VirtualAddress + Symb->Value;
137 Result = Symb->Value;
138 return object_error::success;
141 error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
142 SymbolRef::Type &Result) const {
143 const coff_symbol *Symb = toSymb(Ref);
144 Result = SymbolRef::ST_Other;
145 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
146 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
147 Result = SymbolRef::ST_Unknown;
148 } else if (Symb->getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION) {
149 Result = SymbolRef::ST_Function;
151 uint32_t Characteristics = 0;
152 if (Symb->SectionNumber > 0) {
153 const coff_section *Section = NULL;
154 if (error_code EC = getSection(Symb->SectionNumber, Section))
156 Characteristics = Section->Characteristics;
158 if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
159 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
160 Result = SymbolRef::ST_Data;
162 return object_error::success;
165 error_code COFFObjectFile::getSymbolFlags(DataRefImpl Ref,
166 uint32_t &Result) const {
167 const coff_symbol *Symb = toSymb(Ref);
168 Result = SymbolRef::SF_None;
170 // TODO: Correctly set SF_FormatSpecific, SF_ThreadLocal, SF_Common
172 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
173 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
174 Result |= SymbolRef::SF_Undefined;
176 // TODO: This are certainly too restrictive.
177 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
178 Result |= SymbolRef::SF_Global;
180 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
181 Result |= SymbolRef::SF_Weak;
183 if (Symb->SectionNumber == COFF::IMAGE_SYM_ABSOLUTE)
184 Result |= SymbolRef::SF_Absolute;
186 return object_error::success;
189 error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
190 uint64_t &Result) const {
191 // FIXME: Return the correct size. This requires looking at all the symbols
192 // in the same section as this symbol, and looking for either the next
193 // symbol, or the end of the section.
194 const coff_symbol *Symb = toSymb(Ref);
195 const coff_section *Section = NULL;
196 if (error_code EC = getSection(Symb->SectionNumber, Section))
199 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
200 Result = UnknownAddressOrSize;
202 Result = Section->SizeOfRawData - Symb->Value;
205 return object_error::success;
208 error_code COFFObjectFile::getSymbolSection(DataRefImpl Ref,
209 section_iterator &Result) const {
210 const coff_symbol *Symb = toSymb(Ref);
211 if (Symb->SectionNumber <= COFF::IMAGE_SYM_UNDEFINED)
212 Result = end_sections();
214 const coff_section *Sec = 0;
215 if (error_code EC = getSection(Symb->SectionNumber, Sec)) return EC;
217 Ref.p = reinterpret_cast<uintptr_t>(Sec);
218 Result = section_iterator(SectionRef(Ref, this));
220 return object_error::success;
223 error_code COFFObjectFile::getSymbolValue(DataRefImpl Ref,
224 uint64_t &Val) const {
225 report_fatal_error("getSymbolValue unimplemented in COFFObjectFile");
228 error_code COFFObjectFile::getSectionNext(DataRefImpl Ref,
229 SectionRef &Result) const {
230 const coff_section *Sec = toSec(Ref);
232 Ref.p = reinterpret_cast<uintptr_t>(Sec);
233 Result = SectionRef(Ref, this);
234 return object_error::success;
237 error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
238 StringRef &Result) const {
239 const coff_section *Sec = toSec(Ref);
240 return getSectionName(Sec, Result);
243 error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
244 uint64_t &Result) const {
245 const coff_section *Sec = toSec(Ref);
246 Result = Sec->VirtualAddress;
247 return object_error::success;
250 error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
251 uint64_t &Result) const {
252 const coff_section *Sec = toSec(Ref);
253 Result = Sec->SizeOfRawData;
254 return object_error::success;
257 error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
258 StringRef &Result) const {
259 const coff_section *Sec = toSec(Ref);
260 ArrayRef<uint8_t> Res;
261 error_code EC = getSectionContents(Sec, Res);
262 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
266 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
267 uint64_t &Res) const {
268 const coff_section *Sec = toSec(Ref);
270 return object_error::parse_failed;
271 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
272 return object_error::success;
275 error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
276 bool &Result) const {
277 const coff_section *Sec = toSec(Ref);
278 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
279 return object_error::success;
282 error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
283 bool &Result) const {
284 const coff_section *Sec = toSec(Ref);
285 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
286 return object_error::success;
289 error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
290 bool &Result) const {
291 const coff_section *Sec = toSec(Ref);
292 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
293 return object_error::success;
296 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
297 bool &Result) const {
298 // FIXME: Unimplemented
300 return object_error::success;
303 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
304 bool &Result) const {
305 const coff_section *Sec = toSec(Ref);
306 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
307 return object_error::success;
310 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
311 bool &Result) const {
312 // FIXME: Unimplemented.
314 return object_error::success;
317 error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
318 bool &Result) const {
319 // FIXME: Unimplemented.
321 return object_error::success;
324 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
326 bool &Result) const {
327 const coff_section *Sec = toSec(SecRef);
328 const coff_symbol *Symb = toSymb(SymbRef);
329 const coff_section *SymbSec = 0;
330 if (error_code EC = getSection(Symb->SectionNumber, SymbSec)) return EC;
335 return object_error::success;
338 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
339 const coff_section *Sec = toSec(Ref);
341 if (Sec->NumberOfRelocations == 0)
344 Ret.p = reinterpret_cast<uintptr_t>(base() + Sec->PointerToRelocations);
346 return relocation_iterator(RelocationRef(Ret, this));
349 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
350 const coff_section *Sec = toSec(Ref);
352 if (Sec->NumberOfRelocations == 0)
355 Ret.p = reinterpret_cast<uintptr_t>(
356 reinterpret_cast<const coff_relocation*>(
357 base() + Sec->PointerToRelocations)
358 + Sec->NumberOfRelocations);
360 return relocation_iterator(RelocationRef(Ret, this));
363 // Initialize the pointer to the symbol table.
364 error_code COFFObjectFile::initSymbolTablePtr() {
365 if (error_code EC = getObject(
366 SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
367 COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
370 // Find string table. The first four byte of the string table contains the
371 // total size of the string table, including the size field itself. If the
372 // string table is empty, the value of the first four byte would be 4.
373 const uint8_t *StringTableAddr =
374 base() + COFFHeader->PointerToSymbolTable +
375 COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
376 const ulittle32_t *StringTableSizePtr;
377 if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
379 StringTableSize = *StringTableSizePtr;
381 getObject(StringTable, Data, StringTableAddr, StringTableSize))
384 // Check that the string table is null terminated if has any in it.
385 if (StringTableSize < 4 ||
386 (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0))
387 return object_error::parse_failed;
388 return object_error::success;
391 // Returns the file offset for the given RVA.
392 error_code COFFObjectFile::getRvaPtr(uint32_t Rva, uintptr_t &Res) const {
394 for (section_iterator I = begin_sections(), E = end_sections(); I != E;
398 const coff_section *Section = getCOFFSection(I);
399 uint32_t SectionStart = Section->VirtualAddress;
400 uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
401 if (SectionStart <= Rva && Rva < SectionEnd) {
402 uint32_t Offset = Rva - SectionStart;
403 Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
404 return object_error::success;
407 return object_error::parse_failed;
410 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
412 error_code COFFObjectFile::
413 getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const {
414 uintptr_t IntPtr = 0;
415 if (error_code EC = getRvaPtr(Rva, IntPtr))
417 const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
418 Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
419 Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
420 return object_error::success;
423 // Find the import table.
424 error_code COFFObjectFile::initImportTablePtr() {
425 // First, we get the RVA of the import table. If the file lacks a pointer to
426 // the import table, do nothing.
427 const data_directory *DataEntry;
428 if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
429 return object_error::success;
431 // Do nothing if the pointer to import table is NULL.
432 if (DataEntry->RelativeVirtualAddress == 0)
433 return object_error::success;
435 uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
436 NumberOfImportDirectory = DataEntry->Size /
437 sizeof(import_directory_table_entry);
439 // Find the section that contains the RVA. This is needed because the RVA is
440 // the import table's memory address which is different from its file offset.
441 uintptr_t IntPtr = 0;
442 if (error_code EC = getRvaPtr(ImportTableRva, IntPtr))
444 ImportDirectory = reinterpret_cast<
445 const import_directory_table_entry *>(IntPtr);
446 return object_error::success;
449 // Find the export table.
450 error_code COFFObjectFile::initExportTablePtr() {
451 // First, we get the RVA of the export table. If the file lacks a pointer to
452 // the export table, do nothing.
453 const data_directory *DataEntry;
454 if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
455 return object_error::success;
457 // Do nothing if the pointer to export table is NULL.
458 if (DataEntry->RelativeVirtualAddress == 0)
459 return object_error::success;
461 uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
462 uintptr_t IntPtr = 0;
463 if (error_code EC = getRvaPtr(ExportTableRva, IntPtr))
465 ExportDirectory = reinterpret_cast<const export_directory_table_entry *>(IntPtr);
466 return object_error::success;
469 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC)
470 : ObjectFile(Binary::ID_COFF, Object), COFFHeader(0), PE32Header(0),
471 DataDirectory(0), SectionTable(0), SymbolTable(0), StringTable(0),
472 StringTableSize(0), ImportDirectory(0), NumberOfImportDirectory(0),
474 // Check that we at least have enough room for a header.
475 if (!checkSize(Data, EC, sizeof(coff_file_header))) return;
477 // The current location in the file where we are looking at.
480 // PE header is optional and is present only in executables. If it exists,
481 // it is placed right after COFF header.
482 bool HasPEHeader = false;
484 // Check if this is a PE/COFF file.
485 if (base()[0] == 0x4d && base()[1] == 0x5a) {
486 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
487 // PE signature to find 'normal' COFF header.
488 if (!checkSize(Data, EC, 0x3c + 8)) return;
489 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
490 // Check the PE magic bytes. ("PE\0\0")
491 if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
492 EC = object_error::parse_failed;
495 CurPtr += 4; // Skip the PE magic bytes.
499 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
501 CurPtr += sizeof(coff_file_header);
504 if ((EC = getObject(PE32Header, Data, base() + CurPtr)))
506 if (PE32Header->Magic != 0x10b) {
507 // We only support PE32. If this is PE32 (not PE32+), the magic byte
508 // should be 0x10b. If this is not PE32, continue as if there's no PE
509 // header in this file.
511 } else if (PE32Header->NumberOfRvaAndSize > 0) {
512 const uint8_t *Addr = base() + CurPtr + sizeof(pe32_header);
513 uint64_t size = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
514 if ((EC = getObject(DataDirectory, Data, Addr, size)))
517 CurPtr += COFFHeader->SizeOfOptionalHeader;
520 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, Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
743 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
744 StringRef &Res) const {
746 if (Sec->Name[7] == 0)
747 // Null terminated, let ::strlen figure out the length.
750 // Not null terminated, use all 8 bytes.
751 Name = StringRef(Sec->Name, 8);
753 // Check for string table entry. First byte is '/'.
754 if (Name[0] == '/') {
756 if (Name.substr(1).getAsInteger(10, Offset))
757 return object_error::parse_failed;
758 if (error_code EC = getString(Offset, Name))
763 return object_error::success;
766 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
767 ArrayRef<uint8_t> &Res) const {
768 // The only thing that we need to verify is that the contents is contained
769 // within the file bounds. We don't need to make sure it doesn't cover other
770 // data, as there's nothing that says that is not allowed.
771 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
772 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
773 if (ConEnd > uintptr_t(Data->getBufferEnd()))
774 return object_error::parse_failed;
775 Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
777 return object_error::success;
780 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
781 return reinterpret_cast<const coff_relocation*>(Rel.p);
784 error_code COFFObjectFile::getRelocationNext(DataRefImpl Rel,
785 RelocationRef &Res) const {
786 Rel.p = reinterpret_cast<uintptr_t>(
787 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
788 Res = RelocationRef(Rel, this);
789 return object_error::success;
792 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
793 uint64_t &Res) const {
794 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
797 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
798 uint64_t &Res) const {
799 Res = toRel(Rel)->VirtualAddress;
800 return object_error::success;
803 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
804 const coff_relocation* R = toRel(Rel);
806 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
807 return symbol_iterator(SymbolRef(Ref, this));
810 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
811 uint64_t &Res) const {
812 const coff_relocation* R = toRel(Rel);
814 return object_error::success;
817 const coff_section *COFFObjectFile::getCOFFSection(section_iterator &It) const {
818 return toSec(It->getRawDataRefImpl());
821 const coff_symbol *COFFObjectFile::getCOFFSymbol(symbol_iterator &It) const {
822 return toSymb(It->getRawDataRefImpl());
825 const coff_relocation *COFFObjectFile::getCOFFRelocation(
826 relocation_iterator &It) const {
827 return toRel(It->getRawDataRefImpl());
830 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(enum) \
831 case COFF::enum: Res = #enum; break;
833 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
834 SmallVectorImpl<char> &Result) const {
835 const coff_relocation *Reloc = toRel(Rel);
837 switch (COFFHeader->Machine) {
838 case COFF::IMAGE_FILE_MACHINE_AMD64:
839 switch (Reloc->Type) {
840 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
841 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
842 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
843 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
844 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
845 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
846 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
847 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
848 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
849 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
850 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
851 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
852 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
853 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
854 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
855 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
856 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
861 case COFF::IMAGE_FILE_MACHINE_I386:
862 switch (Reloc->Type) {
863 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
864 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
865 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
866 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
867 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
868 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
869 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
870 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
871 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
872 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
873 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
881 Result.append(Res.begin(), Res.end());
882 return object_error::success;
885 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
887 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
888 SmallVectorImpl<char> &Result) const {
889 const coff_relocation *Reloc = toRel(Rel);
890 const coff_symbol *Symb = 0;
891 if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
893 Sym.p = reinterpret_cast<uintptr_t>(Symb);
895 if (error_code EC = getSymbolName(Sym, SymName)) return EC;
896 Result.append(SymName.begin(), SymName.end());
897 return object_error::success;
900 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
901 LibraryRef &Result) const {
902 report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
905 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
906 StringRef &Result) const {
907 report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
910 bool ImportDirectoryEntryRef::
911 operator==(const ImportDirectoryEntryRef &Other) const {
912 return ImportTable == Other.ImportTable && Index == Other.Index;
916 ImportDirectoryEntryRef::getNext(ImportDirectoryEntryRef &Result) const {
917 Result = ImportDirectoryEntryRef(ImportTable, Index + 1, OwningObject);
918 return object_error::success;
921 error_code ImportDirectoryEntryRef::
922 getImportTableEntry(const import_directory_table_entry *&Result) const {
923 Result = ImportTable;
924 return object_error::success;
927 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
928 uintptr_t IntPtr = 0;
929 if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
931 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
932 return object_error::success;
935 error_code ImportDirectoryEntryRef::getImportLookupEntry(
936 const import_lookup_table_entry32 *&Result) const {
937 uintptr_t IntPtr = 0;
939 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
941 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
942 return object_error::success;
945 bool ExportDirectoryEntryRef::
946 operator==(const ExportDirectoryEntryRef &Other) const {
947 return ExportTable == Other.ExportTable && Index == Other.Index;
951 ExportDirectoryEntryRef::getNext(ExportDirectoryEntryRef &Result) const {
952 Result = ExportDirectoryEntryRef(ExportTable, Index + 1, OwningObject);
953 return object_error::success;
956 // Returns the export ordinal of the current export symbol.
957 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
958 Result = ExportTable->OrdinalBase + Index;
959 return object_error::success;
962 // Returns the address of the current export symbol.
963 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
964 uintptr_t IntPtr = 0;
965 if (error_code EC = OwningObject->getRvaPtr(
966 ExportTable->ExportAddressTableRVA, IntPtr))
968 const export_address_table_entry *entry = reinterpret_cast<const export_address_table_entry *>(IntPtr);
969 Result = entry[Index].ExportRVA;
970 return object_error::success;
973 // Returns the name of the current export symbol. If the symbol is exported only
974 // by ordinal, the empty string is set as a result.
975 error_code ExportDirectoryEntryRef::getName(StringRef &Result) const {
976 uintptr_t IntPtr = 0;
977 if (error_code EC = OwningObject->getRvaPtr(
978 ExportTable->OrdinalTableRVA, IntPtr))
980 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
982 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
984 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
985 I < E; ++I, ++Offset) {
988 if (error_code EC = OwningObject->getRvaPtr(
989 ExportTable->NamePointerRVA, IntPtr))
991 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
992 if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
994 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
995 return object_error::success;
998 return object_error::success;
1002 ObjectFile *ObjectFile::createCOFFObjectFile(MemoryBuffer *Object) {
1004 return new COFFObjectFile(Object, EC);
1006 } // end namespace llvm