1 //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the COFFObjectFile class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Object/COFF.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/raw_ostream.h"
25 using namespace object;
27 using support::ulittle8_t;
28 using support::ulittle16_t;
29 using support::ulittle32_t;
30 using support::little16_t;
32 // Returns false if size is greater than the buffer size. And sets ec.
33 static bool checkSize(const MemoryBuffer *M, error_code &EC, uint64_t Size) {
34 if (M->getBufferSize() < Size) {
35 EC = object_error::unexpected_eof;
41 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
42 // Returns unexpected_eof if error.
44 static error_code getObject(const T *&Obj, const MemoryBuffer *M,
45 const uint8_t *Ptr, const size_t Size = sizeof(T)) {
46 uintptr_t Addr = uintptr_t(Ptr);
47 if (Addr + Size < Addr ||
49 Addr + Size > uintptr_t(M->getBufferEnd())) {
50 return object_error::unexpected_eof;
52 Obj = reinterpret_cast<const T *>(Addr);
53 return object_error::success;
56 const coff_symbol *COFFObjectFile::toSymb(DataRefImpl Ref) const {
57 const coff_symbol *Addr = reinterpret_cast<const coff_symbol*>(Ref.p);
60 // Verify that the symbol points to a valid entry in the symbol table.
61 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
62 if (Offset < COFFHeader->PointerToSymbolTable
63 || Offset >= COFFHeader->PointerToSymbolTable
64 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
65 report_fatal_error("Symbol was outside of symbol table.");
67 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
68 == 0 && "Symbol did not point to the beginning of a symbol");
74 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
75 const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
78 // Verify that the section points to a valid entry in the section table.
79 if (Addr < SectionTable
80 || Addr >= (SectionTable + COFFHeader->NumberOfSections))
81 report_fatal_error("Section was outside of section table.");
83 uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
84 assert(Offset % sizeof(coff_section) == 0 &&
85 "Section did not point to the beginning of a section");
91 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
92 const coff_symbol *Symb = toSymb(Ref);
93 Symb += 1 + Symb->NumberOfAuxSymbols;
94 Ref.p = reinterpret_cast<uintptr_t>(Symb);
97 error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
98 StringRef &Result) const {
99 const coff_symbol *Symb = toSymb(Ref);
100 return getSymbolName(Symb, Result);
103 error_code COFFObjectFile::getSymbolFileOffset(DataRefImpl Ref,
104 uint64_t &Result) const {
105 const coff_symbol *Symb = toSymb(Ref);
106 const coff_section *Section = NULL;
107 if (error_code EC = getSection(Symb->SectionNumber, Section))
110 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
111 Result = UnknownAddressOrSize;
113 Result = Section->PointerToRawData + Symb->Value;
115 Result = Symb->Value;
116 return object_error::success;
119 error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
120 uint64_t &Result) const {
121 const coff_symbol *Symb = toSymb(Ref);
122 const coff_section *Section = NULL;
123 if (error_code EC = getSection(Symb->SectionNumber, Section))
126 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
127 Result = UnknownAddressOrSize;
129 Result = Section->VirtualAddress + Symb->Value;
131 Result = Symb->Value;
132 return object_error::success;
135 error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
136 SymbolRef::Type &Result) const {
137 const coff_symbol *Symb = toSymb(Ref);
138 Result = SymbolRef::ST_Other;
139 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
140 Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
141 Result = SymbolRef::ST_Unknown;
142 } else if (Symb->getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION) {
143 Result = SymbolRef::ST_Function;
145 uint32_t Characteristics = 0;
146 if (Symb->SectionNumber > 0) {
147 const coff_section *Section = NULL;
148 if (error_code EC = getSection(Symb->SectionNumber, Section))
150 Characteristics = Section->Characteristics;
152 if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
153 ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
154 Result = SymbolRef::ST_Data;
156 return object_error::success;
159 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
160 const coff_symbol *Symb = toSymb(Ref);
161 uint32_t Result = SymbolRef::SF_None;
163 // TODO: Correctly set SF_FormatSpecific, SF_Common
165 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
166 if (Symb->Value == 0)
167 Result |= SymbolRef::SF_Undefined;
169 Result |= SymbolRef::SF_Common;
173 // TODO: This are certainly too restrictive.
174 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
175 Result |= SymbolRef::SF_Global;
177 if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
178 Result |= SymbolRef::SF_Weak;
180 if (Symb->SectionNumber == COFF::IMAGE_SYM_ABSOLUTE)
181 Result |= SymbolRef::SF_Absolute;
186 error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
187 uint64_t &Result) const {
188 // FIXME: Return the correct size. This requires looking at all the symbols
189 // in the same section as this symbol, and looking for either the next
190 // symbol, or the end of the section.
191 const coff_symbol *Symb = toSymb(Ref);
192 const coff_section *Section = NULL;
193 if (error_code EC = getSection(Symb->SectionNumber, Section))
196 if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
197 Result = UnknownAddressOrSize;
199 Result = Section->SizeOfRawData - Symb->Value;
202 return object_error::success;
205 error_code COFFObjectFile::getSymbolSection(DataRefImpl Ref,
206 section_iterator &Result) const {
207 const coff_symbol *Symb = toSymb(Ref);
208 if (Symb->SectionNumber <= COFF::IMAGE_SYM_UNDEFINED)
209 Result = section_end();
211 const coff_section *Sec = 0;
212 if (error_code EC = getSection(Symb->SectionNumber, Sec)) return EC;
214 Ref.p = reinterpret_cast<uintptr_t>(Sec);
215 Result = section_iterator(SectionRef(Ref, this));
217 return object_error::success;
220 error_code COFFObjectFile::getSymbolValue(DataRefImpl Ref,
221 uint64_t &Val) const {
222 report_fatal_error("getSymbolValue unimplemented in COFFObjectFile");
225 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
226 const coff_section *Sec = toSec(Ref);
228 Ref.p = reinterpret_cast<uintptr_t>(Sec);
231 error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
232 StringRef &Result) const {
233 const coff_section *Sec = toSec(Ref);
234 return getSectionName(Sec, Result);
237 error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
238 uint64_t &Result) const {
239 const coff_section *Sec = toSec(Ref);
240 Result = Sec->VirtualAddress;
241 return object_error::success;
244 error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
245 uint64_t &Result) const {
246 const coff_section *Sec = toSec(Ref);
247 Result = Sec->SizeOfRawData;
248 return object_error::success;
251 error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
252 StringRef &Result) const {
253 const coff_section *Sec = toSec(Ref);
254 ArrayRef<uint8_t> Res;
255 error_code EC = getSectionContents(Sec, Res);
256 Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
260 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
261 uint64_t &Res) const {
262 const coff_section *Sec = toSec(Ref);
264 return object_error::parse_failed;
265 Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
266 return object_error::success;
269 error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
270 bool &Result) const {
271 const coff_section *Sec = toSec(Ref);
272 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
273 return object_error::success;
276 error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
277 bool &Result) const {
278 const coff_section *Sec = toSec(Ref);
279 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
280 return object_error::success;
283 error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
284 bool &Result) const {
285 const coff_section *Sec = toSec(Ref);
286 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
287 return object_error::success;
290 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
291 bool &Result) const {
292 // FIXME: Unimplemented
294 return object_error::success;
297 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
298 bool &Result) const {
299 const coff_section *Sec = toSec(Ref);
300 Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
301 return object_error::success;
304 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
305 bool &Result) const {
306 // FIXME: Unimplemented.
308 return object_error::success;
311 error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
312 bool &Result) const {
313 // FIXME: Unimplemented.
315 return object_error::success;
318 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
320 bool &Result) const {
321 const coff_section *Sec = toSec(SecRef);
322 const coff_symbol *Symb = toSymb(SymbRef);
323 const coff_section *SymbSec = 0;
324 if (error_code EC = getSection(Symb->SectionNumber, SymbSec)) return EC;
329 return object_error::success;
332 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
333 const coff_section *Sec = toSec(Ref);
335 if (Sec->NumberOfRelocations == 0)
338 Ret.p = reinterpret_cast<uintptr_t>(base() + Sec->PointerToRelocations);
340 return relocation_iterator(RelocationRef(Ret, this));
343 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
344 const coff_section *Sec = toSec(Ref);
346 if (Sec->NumberOfRelocations == 0)
349 Ret.p = reinterpret_cast<uintptr_t>(
350 reinterpret_cast<const coff_relocation*>(
351 base() + Sec->PointerToRelocations)
352 + Sec->NumberOfRelocations);
354 return relocation_iterator(RelocationRef(Ret, this));
357 // Initialize the pointer to the symbol table.
358 error_code COFFObjectFile::initSymbolTablePtr() {
359 if (error_code EC = getObject(
360 SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
361 COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
364 // Find string table. The first four byte of the string table contains the
365 // total size of the string table, including the size field itself. If the
366 // string table is empty, the value of the first four byte would be 4.
367 const uint8_t *StringTableAddr =
368 base() + COFFHeader->PointerToSymbolTable +
369 COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
370 const ulittle32_t *StringTableSizePtr;
371 if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
373 StringTableSize = *StringTableSizePtr;
375 getObject(StringTable, Data, StringTableAddr, StringTableSize))
378 // Check that the string table is null terminated if has any in it.
379 if (StringTableSize < 4 ||
380 (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0))
381 return object_error::parse_failed;
382 return object_error::success;
385 // Returns the file offset for the given VA.
386 error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
387 uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
388 : (uint64_t)PE32PlusHeader->ImageBase;
389 uint64_t Rva = Addr - ImageBase;
390 assert(Rva <= UINT32_MAX);
391 return getRvaPtr((uint32_t)Rva, Res);
394 // Returns the file offset for the given RVA.
395 error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
396 for (section_iterator I = section_begin(), E = section_end(); 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 <= Addr && Addr < SectionEnd) {
402 uint32_t Offset = Addr - 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))
466 reinterpret_cast<const export_directory_table_entry *>(IntPtr);
467 return object_error::success;
470 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC,
472 : ObjectFile(Binary::ID_COFF, Object, BufferOwned), COFFHeader(0),
473 PE32Header(0), PE32PlusHeader(0), DataDirectory(0), SectionTable(0),
474 SymbolTable(0), StringTable(0), StringTableSize(0), ImportDirectory(0),
475 NumberOfImportDirectory(0), ExportDirectory(0) {
476 // Check that we at least have enough room for a header.
477 if (!checkSize(Data, EC, sizeof(coff_file_header))) return;
479 // The current location in the file where we are looking at.
482 // PE header is optional and is present only in executables. If it exists,
483 // it is placed right after COFF header.
484 bool HasPEHeader = false;
486 // Check if this is a PE/COFF file.
487 if (base()[0] == 0x4d && base()[1] == 0x5a) {
488 // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
489 // PE signature to find 'normal' COFF header.
490 if (!checkSize(Data, EC, 0x3c + 8)) return;
491 CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
492 // Check the PE magic bytes. ("PE\0\0")
493 if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
494 EC = object_error::parse_failed;
497 CurPtr += 4; // Skip the PE magic bytes.
501 if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
503 CurPtr += sizeof(coff_file_header);
506 const pe32_header *Header;
507 if ((EC = getObject(Header, Data, base() + CurPtr)))
510 const uint8_t *DataDirAddr;
511 uint64_t DataDirSize;
512 if (Header->Magic == 0x10b) {
514 DataDirAddr = base() + CurPtr + sizeof(pe32_header);
515 DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
516 } else if (Header->Magic == 0x20b) {
517 PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
518 DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
519 DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
521 // It's neither PE32 nor PE32+.
522 EC = object_error::parse_failed;
525 if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
527 CurPtr += COFFHeader->SizeOfOptionalHeader;
530 if (COFFHeader->isImportLibrary())
533 if ((EC = getObject(SectionTable, Data, base() + CurPtr,
534 COFFHeader->NumberOfSections * sizeof(coff_section))))
537 // Initialize the pointer to the symbol table.
538 if (COFFHeader->PointerToSymbolTable != 0)
539 if ((EC = initSymbolTablePtr()))
542 // Initialize the pointer to the beginning of the import table.
543 if ((EC = initImportTablePtr()))
546 // Initialize the pointer to the export table.
547 if ((EC = initExportTablePtr()))
550 EC = object_error::success;
553 symbol_iterator COFFObjectFile::symbol_begin() const {
555 Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
556 return symbol_iterator(SymbolRef(Ret, this));
559 symbol_iterator COFFObjectFile::symbol_end() const {
560 // The symbol table ends where the string table begins.
562 Ret.p = reinterpret_cast<uintptr_t>(StringTable);
563 return symbol_iterator(SymbolRef(Ret, this));
566 library_iterator COFFObjectFile::needed_library_begin() const {
568 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
571 library_iterator COFFObjectFile::needed_library_end() const {
573 report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
576 StringRef COFFObjectFile::getLoadName() const {
577 // COFF does not have this field.
581 import_directory_iterator COFFObjectFile::import_directory_begin() const {
582 return import_directory_iterator(
583 ImportDirectoryEntryRef(ImportDirectory, 0, this));
586 import_directory_iterator COFFObjectFile::import_directory_end() const {
587 return import_directory_iterator(
588 ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
591 export_directory_iterator COFFObjectFile::export_directory_begin() const {
592 return export_directory_iterator(
593 ExportDirectoryEntryRef(ExportDirectory, 0, this));
596 export_directory_iterator COFFObjectFile::export_directory_end() const {
597 if (ExportDirectory == 0)
598 return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this));
599 ExportDirectoryEntryRef Ref(ExportDirectory,
600 ExportDirectory->AddressTableEntries, this);
601 return export_directory_iterator(Ref);
604 section_iterator COFFObjectFile::section_begin() const {
606 Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
607 return section_iterator(SectionRef(Ret, this));
610 section_iterator COFFObjectFile::section_end() const {
612 int NumSections = COFFHeader->isImportLibrary()
613 ? 0 : COFFHeader->NumberOfSections;
614 Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
615 return section_iterator(SectionRef(Ret, this));
618 uint8_t COFFObjectFile::getBytesInAddress() const {
619 return getArch() == Triple::x86_64 ? 8 : 4;
622 StringRef COFFObjectFile::getFileFormatName() const {
623 switch(COFFHeader->Machine) {
624 case COFF::IMAGE_FILE_MACHINE_I386:
626 case COFF::IMAGE_FILE_MACHINE_AMD64:
627 return "COFF-x86-64";
629 return "COFF-<unknown arch>";
633 unsigned COFFObjectFile::getArch() const {
634 switch(COFFHeader->Machine) {
635 case COFF::IMAGE_FILE_MACHINE_I386:
637 case COFF::IMAGE_FILE_MACHINE_AMD64:
638 return Triple::x86_64;
640 return Triple::UnknownArch;
644 // This method is kept here because lld uses this. As soon as we make
645 // lld to use getCOFFHeader, this method will be removed.
646 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
647 return getCOFFHeader(Res);
650 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
652 return object_error::success;
655 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
657 return object_error::success;
661 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
662 Res = PE32PlusHeader;
663 return object_error::success;
666 error_code COFFObjectFile::getDataDirectory(uint32_t Index,
667 const data_directory *&Res) const {
668 // Error if if there's no data directory or the index is out of range.
670 return object_error::parse_failed;
671 assert(PE32Header || PE32PlusHeader);
672 uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
673 : PE32PlusHeader->NumberOfRvaAndSize;
675 return object_error::parse_failed;
676 Res = &DataDirectory[Index];
677 return object_error::success;
680 error_code COFFObjectFile::getSection(int32_t Index,
681 const coff_section *&Result) const {
682 // Check for special index values.
683 if (Index == COFF::IMAGE_SYM_UNDEFINED ||
684 Index == COFF::IMAGE_SYM_ABSOLUTE ||
685 Index == COFF::IMAGE_SYM_DEBUG)
687 else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
688 // We already verified the section table data, so no need to check again.
689 Result = SectionTable + (Index - 1);
691 return object_error::parse_failed;
692 return object_error::success;
695 error_code COFFObjectFile::getString(uint32_t Offset,
696 StringRef &Result) const {
697 if (StringTableSize <= 4)
698 // Tried to get a string from an empty string table.
699 return object_error::parse_failed;
700 if (Offset >= StringTableSize)
701 return object_error::unexpected_eof;
702 Result = StringRef(StringTable + Offset);
703 return object_error::success;
706 error_code COFFObjectFile::getSymbol(uint32_t Index,
707 const coff_symbol *&Result) const {
708 if (Index < COFFHeader->NumberOfSymbols)
709 Result = SymbolTable + Index;
711 return object_error::parse_failed;
712 return object_error::success;
715 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
716 StringRef &Res) const {
717 // Check for string table entry. First 4 bytes are 0.
718 if (Symbol->Name.Offset.Zeroes == 0) {
719 uint32_t Offset = Symbol->Name.Offset.Offset;
720 if (error_code EC = getString(Offset, Res))
722 return object_error::success;
725 if (Symbol->Name.ShortName[7] == 0)
726 // Null terminated, let ::strlen figure out the length.
727 Res = StringRef(Symbol->Name.ShortName);
729 // Not null terminated, use all 8 bytes.
730 Res = StringRef(Symbol->Name.ShortName, 8);
731 return object_error::success;
734 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
735 const coff_symbol *Symbol) const {
736 const uint8_t *Aux = NULL;
738 if (Symbol->NumberOfAuxSymbols > 0) {
739 // AUX data comes immediately after the symbol in COFF
740 Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
742 // Verify that the Aux symbol points to a valid entry in the symbol table.
743 uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
744 if (Offset < COFFHeader->PointerToSymbolTable
745 || Offset >= COFFHeader->PointerToSymbolTable
746 + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
747 report_fatal_error("Aux Symbol data was outside of symbol table.");
749 assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
750 == 0 && "Aux Symbol data did not point to the beginning of a symbol");
753 return ArrayRef<uint8_t>(Aux,
754 Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
757 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
758 StringRef &Res) const {
760 if (Sec->Name[7] == 0)
761 // Null terminated, let ::strlen figure out the length.
764 // Not null terminated, use all 8 bytes.
765 Name = StringRef(Sec->Name, 8);
767 // Check for string table entry. First byte is '/'.
768 if (Name[0] == '/') {
770 if (Name.substr(1).getAsInteger(10, Offset))
771 return object_error::parse_failed;
772 if (error_code EC = getString(Offset, Name))
777 return object_error::success;
780 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
781 ArrayRef<uint8_t> &Res) const {
782 // The only thing that we need to verify is that the contents is contained
783 // within the file bounds. We don't need to make sure it doesn't cover other
784 // data, as there's nothing that says that is not allowed.
785 uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
786 uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
787 if (ConEnd > uintptr_t(Data->getBufferEnd()))
788 return object_error::parse_failed;
789 Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
791 return object_error::success;
794 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
795 return reinterpret_cast<const coff_relocation*>(Rel.p);
798 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
799 Rel.p = reinterpret_cast<uintptr_t>(
800 reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
803 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
804 uint64_t &Res) const {
805 report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
808 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
809 uint64_t &Res) const {
810 Res = toRel(Rel)->VirtualAddress;
811 return object_error::success;
814 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
815 const coff_relocation* R = toRel(Rel);
817 Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
818 return symbol_iterator(SymbolRef(Ref, this));
821 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
822 uint64_t &Res) const {
823 const coff_relocation* R = toRel(Rel);
825 return object_error::success;
828 const coff_section *COFFObjectFile::getCOFFSection(section_iterator &It) const {
829 return toSec(It->getRawDataRefImpl());
832 const coff_symbol *COFFObjectFile::getCOFFSymbol(symbol_iterator &It) const {
833 return toSymb(It->getRawDataRefImpl());
836 const coff_relocation *COFFObjectFile::getCOFFRelocation(
837 relocation_iterator &It) const {
838 return toRel(It->getRawDataRefImpl());
841 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(enum) \
842 case COFF::enum: Res = #enum; break;
844 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
845 SmallVectorImpl<char> &Result) const {
846 const coff_relocation *Reloc = toRel(Rel);
848 switch (COFFHeader->Machine) {
849 case COFF::IMAGE_FILE_MACHINE_AMD64:
850 switch (Reloc->Type) {
851 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
852 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
853 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
854 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
855 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
856 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
857 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
858 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
859 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
860 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
861 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
862 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
863 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
864 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
865 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
866 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
867 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
872 case COFF::IMAGE_FILE_MACHINE_I386:
873 switch (Reloc->Type) {
874 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
875 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
876 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
877 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
878 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
879 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
880 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
881 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
882 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
883 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
884 LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
892 Result.append(Res.begin(), Res.end());
893 return object_error::success;
896 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
898 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
899 SmallVectorImpl<char> &Result) const {
900 const coff_relocation *Reloc = toRel(Rel);
901 const coff_symbol *Symb = 0;
902 if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
904 Sym.p = reinterpret_cast<uintptr_t>(Symb);
906 if (error_code EC = getSymbolName(Sym, SymName)) return EC;
907 Result.append(SymName.begin(), SymName.end());
908 return object_error::success;
911 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
912 LibraryRef &Result) const {
913 report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
916 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
917 StringRef &Result) const {
918 report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
921 bool ImportDirectoryEntryRef::
922 operator==(const ImportDirectoryEntryRef &Other) const {
923 return ImportTable == Other.ImportTable && Index == Other.Index;
926 void ImportDirectoryEntryRef::moveNext() {
930 error_code ImportDirectoryEntryRef::
931 getImportTableEntry(const import_directory_table_entry *&Result) const {
932 Result = ImportTable;
933 return object_error::success;
936 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
937 uintptr_t IntPtr = 0;
938 if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
940 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
941 return object_error::success;
944 error_code ImportDirectoryEntryRef::getImportLookupEntry(
945 const import_lookup_table_entry32 *&Result) const {
946 uintptr_t IntPtr = 0;
948 OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
950 Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
951 return object_error::success;
954 bool ExportDirectoryEntryRef::
955 operator==(const ExportDirectoryEntryRef &Other) const {
956 return ExportTable == Other.ExportTable && Index == Other.Index;
959 void ExportDirectoryEntryRef::moveNext() {
963 // Returns the name of the current export symbol. If the symbol is exported only
964 // by ordinal, the empty string is set as a result.
965 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
966 uintptr_t IntPtr = 0;
967 if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
969 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
970 return object_error::success;
973 // Returns the starting ordinal number.
974 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
975 Result = ExportTable->OrdinalBase;
976 return object_error::success;
979 // Returns the export ordinal of the current export symbol.
980 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
981 Result = ExportTable->OrdinalBase + Index;
982 return object_error::success;
985 // Returns the address of the current export symbol.
986 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
987 uintptr_t IntPtr = 0;
988 if (error_code EC = OwningObject->getRvaPtr(
989 ExportTable->ExportAddressTableRVA, IntPtr))
991 const export_address_table_entry *entry =
992 reinterpret_cast<const export_address_table_entry *>(IntPtr);
993 Result = entry[Index].ExportRVA;
994 return object_error::success;
997 // Returns the name of the current export symbol. If the symbol is exported only
998 // by ordinal, the empty string is set as a result.
999 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1000 uintptr_t IntPtr = 0;
1001 if (error_code EC = OwningObject->getRvaPtr(
1002 ExportTable->OrdinalTableRVA, IntPtr))
1004 const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1006 uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1008 for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1009 I < E; ++I, ++Offset) {
1012 if (error_code EC = OwningObject->getRvaPtr(
1013 ExportTable->NamePointerRVA, IntPtr))
1015 const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1016 if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1018 Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1019 return object_error::success;
1022 return object_error::success;
1025 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object,
1028 OwningPtr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC, BufferOwned));