llvm-objdump/COFF: Print SEH table addresses.
[oota-llvm.git] / lib / Object / COFFObjectFile.cpp
1 //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the COFFObjectFile class.
11 //
12 //===----------------------------------------------------------------------===//
13
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"
21 #include <cctype>
22
23 using namespace llvm;
24 using namespace object;
25
26 using support::ulittle8_t;
27 using support::ulittle16_t;
28 using support::ulittle32_t;
29 using support::little16_t;
30
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;
35     return false;
36   }
37   return true;
38 }
39
40 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
41 // Returns unexpected_eof if error.
42 template<typename T>
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 ||
47       Addr + Size < Size ||
48       Addr + Size > uintptr_t(M->getBufferEnd())) {
49     return object_error::unexpected_eof;
50   }
51   Obj = reinterpret_cast<const T *>(Addr);
52   return object_error::success;
53 }
54
55 const coff_symbol *COFFObjectFile::toSymb(DataRefImpl Ref) const {
56   const coff_symbol *Addr = reinterpret_cast<const coff_symbol*>(Ref.p);
57
58 # ifndef NDEBUG
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.");
65
66   assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
67          == 0 && "Symbol did not point to the beginning of a symbol");
68 # endif
69
70   return Addr;
71 }
72
73 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
74   const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
75
76 # ifndef NDEBUG
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.");
81
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");
85 # endif
86
87   return Addr;
88 }
89
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);
94 }
95
96 error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
97                                          StringRef &Result) const {
98   const coff_symbol *Symb = toSymb(Ref);
99   return getSymbolName(Symb, Result);
100 }
101
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))
107     return EC;
108
109   if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
110     Result = UnknownAddressOrSize;
111   else if (Section)
112     Result = Section->PointerToRawData + Symb->Value;
113   else
114     Result = Symb->Value;
115   return object_error::success;
116 }
117
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))
123     return EC;
124
125   if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
126     Result = UnknownAddressOrSize;
127   else if (Section)
128     Result = Section->VirtualAddress + Symb->Value;
129   else
130     Result = Symb->Value;
131   return object_error::success;
132 }
133
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;
143   } else {
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))
148         return EC;
149       Characteristics = Section->Characteristics;
150     }
151     if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
152         ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
153       Result = SymbolRef::ST_Data;
154   }
155   return object_error::success;
156 }
157
158 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
159   const coff_symbol *Symb = toSymb(Ref);
160   uint32_t Result = SymbolRef::SF_None;
161
162   // TODO: Correctly set SF_FormatSpecific, SF_Common
163
164   if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
165     if (Symb->Value == 0)
166       Result |= SymbolRef::SF_Undefined;
167     else
168       Result |= SymbolRef::SF_Common;
169   }
170
171
172   // TODO: This are certainly too restrictive.
173   if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
174     Result |= SymbolRef::SF_Global;
175
176   if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
177     Result |= SymbolRef::SF_Weak;
178
179   if (Symb->SectionNumber == COFF::IMAGE_SYM_ABSOLUTE)
180     Result |= SymbolRef::SF_Absolute;
181
182   return Result;
183 }
184
185 error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
186                                          uint64_t &Result) const {
187   // FIXME: Return the correct size. This requires looking at all the symbols
188   //        in the same section as this symbol, and looking for either the next
189   //        symbol, or the end of the section.
190   const coff_symbol *Symb = toSymb(Ref);
191   const coff_section *Section = NULL;
192   if (error_code EC = getSection(Symb->SectionNumber, Section))
193     return EC;
194
195   if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
196     Result = UnknownAddressOrSize;
197   else if (Section)
198     Result = Section->SizeOfRawData - Symb->Value;
199   else
200     Result = 0;
201   return object_error::success;
202 }
203
204 error_code COFFObjectFile::getSymbolSection(DataRefImpl Ref,
205                                             section_iterator &Result) const {
206   const coff_symbol *Symb = toSymb(Ref);
207   if (Symb->SectionNumber <= COFF::IMAGE_SYM_UNDEFINED)
208     Result = section_end();
209   else {
210     const coff_section *Sec = 0;
211     if (error_code EC = getSection(Symb->SectionNumber, Sec)) return EC;
212     DataRefImpl Ref;
213     Ref.p = reinterpret_cast<uintptr_t>(Sec);
214     Result = section_iterator(SectionRef(Ref, this));
215   }
216   return object_error::success;
217 }
218
219 error_code COFFObjectFile::getSymbolValue(DataRefImpl Ref,
220                                           uint64_t &Val) const {
221   report_fatal_error("getSymbolValue unimplemented in COFFObjectFile");
222 }
223
224 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
225   const coff_section *Sec = toSec(Ref);
226   Sec += 1;
227   Ref.p = reinterpret_cast<uintptr_t>(Sec);
228 }
229
230 error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
231                                           StringRef &Result) const {
232   const coff_section *Sec = toSec(Ref);
233   return getSectionName(Sec, Result);
234 }
235
236 error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
237                                              uint64_t &Result) const {
238   const coff_section *Sec = toSec(Ref);
239   Result = Sec->VirtualAddress;
240   return object_error::success;
241 }
242
243 error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
244                                           uint64_t &Result) const {
245   const coff_section *Sec = toSec(Ref);
246   Result = Sec->SizeOfRawData;
247   return object_error::success;
248 }
249
250 error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
251                                               StringRef &Result) const {
252   const coff_section *Sec = toSec(Ref);
253   ArrayRef<uint8_t> Res;
254   error_code EC = getSectionContents(Sec, Res);
255   Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
256   return EC;
257 }
258
259 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
260                                                uint64_t &Res) const {
261   const coff_section *Sec = toSec(Ref);
262   if (!Sec)
263     return object_error::parse_failed;
264   Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
265   return object_error::success;
266 }
267
268 error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
269                                          bool &Result) const {
270   const coff_section *Sec = toSec(Ref);
271   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
272   return object_error::success;
273 }
274
275 error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
276                                          bool &Result) const {
277   const coff_section *Sec = toSec(Ref);
278   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
279   return object_error::success;
280 }
281
282 error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
283                                         bool &Result) const {
284   const coff_section *Sec = toSec(Ref);
285   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
286   return object_error::success;
287 }
288
289 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
290                                                          bool &Result) const {
291   // FIXME: Unimplemented
292   Result = true;
293   return object_error::success;
294 }
295
296 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
297                                            bool &Result) const {
298   const coff_section *Sec = toSec(Ref);
299   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
300   return object_error::success;
301 }
302
303 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
304                                              bool &Result) const {
305   // FIXME: Unimplemented.
306   Result = false;
307   return object_error::success;
308 }
309
310 error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
311                                                 bool &Result) const {
312   // FIXME: Unimplemented.
313   Result = false;
314   return object_error::success;
315 }
316
317 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
318                                                  DataRefImpl SymbRef,
319                                                  bool &Result) const {
320   const coff_section *Sec = toSec(SecRef);
321   const coff_symbol *Symb = toSymb(SymbRef);
322   const coff_section *SymbSec = 0;
323   if (error_code EC = getSection(Symb->SectionNumber, SymbSec)) return EC;
324   if (SymbSec == Sec)
325     Result = true;
326   else
327     Result = false;
328   return object_error::success;
329 }
330
331 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
332   const coff_section *Sec = toSec(Ref);
333   DataRefImpl Ret;
334   if (Sec->NumberOfRelocations == 0)
335     Ret.p = 0;
336   else
337     Ret.p = reinterpret_cast<uintptr_t>(base() + Sec->PointerToRelocations);
338
339   return relocation_iterator(RelocationRef(Ret, this));
340 }
341
342 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
343   const coff_section *Sec = toSec(Ref);
344   DataRefImpl Ret;
345   if (Sec->NumberOfRelocations == 0)
346     Ret.p = 0;
347   else
348     Ret.p = reinterpret_cast<uintptr_t>(
349               reinterpret_cast<const coff_relocation*>(
350                 base() + Sec->PointerToRelocations)
351               + Sec->NumberOfRelocations);
352
353   return relocation_iterator(RelocationRef(Ret, this));
354 }
355
356 // Initialize the pointer to the symbol table.
357 error_code COFFObjectFile::initSymbolTablePtr() {
358   if (error_code EC = getObject(
359           SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
360           COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
361     return EC;
362
363   // Find string table. The first four byte of the string table contains the
364   // total size of the string table, including the size field itself. If the
365   // string table is empty, the value of the first four byte would be 4.
366   const uint8_t *StringTableAddr =
367       base() + COFFHeader->PointerToSymbolTable +
368       COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
369   const ulittle32_t *StringTableSizePtr;
370   if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
371     return EC;
372   StringTableSize = *StringTableSizePtr;
373   if (error_code EC =
374       getObject(StringTable, Data, StringTableAddr, StringTableSize))
375     return EC;
376
377   // Check that the string table is null terminated if has any in it.
378   if (StringTableSize < 4 ||
379       (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0))
380     return  object_error::parse_failed;
381   return object_error::success;
382 }
383
384 // Returns the file offset for the given VA.
385 error_code COFFObjectFile::getVaPtr(uint32_t Addr, uintptr_t &Res) const {
386   uint32_t ImageBase = PE32Header ? PE32Header->ImageBase : PE32PlusHeader->ImageBase;
387   return getRvaPtr(Addr - ImageBase, Res);
388 }
389
390 // Returns the file offset for the given RVA.
391 error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
392   for (section_iterator I = section_begin(), E = section_end(); I != E;
393        ++I) {
394     const coff_section *Section = getCOFFSection(I);
395     uint32_t SectionStart = Section->VirtualAddress;
396     uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
397     if (SectionStart <= Addr && Addr < SectionEnd) {
398       uint32_t Offset = Addr - SectionStart;
399       Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
400       return object_error::success;
401     }
402   }
403   return object_error::parse_failed;
404 }
405
406 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
407 // table entry.
408 error_code COFFObjectFile::
409 getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const {
410   uintptr_t IntPtr = 0;
411   if (error_code EC = getRvaPtr(Rva, IntPtr))
412     return EC;
413   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
414   Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
415   Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
416   return object_error::success;
417 }
418
419 // Find the import table.
420 error_code COFFObjectFile::initImportTablePtr() {
421   // First, we get the RVA of the import table. If the file lacks a pointer to
422   // the import table, do nothing.
423   const data_directory *DataEntry;
424   if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
425     return object_error::success;
426
427   // Do nothing if the pointer to import table is NULL.
428   if (DataEntry->RelativeVirtualAddress == 0)
429     return object_error::success;
430
431   uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
432   NumberOfImportDirectory = DataEntry->Size /
433       sizeof(import_directory_table_entry);
434
435   // Find the section that contains the RVA. This is needed because the RVA is
436   // the import table's memory address which is different from its file offset.
437   uintptr_t IntPtr = 0;
438   if (error_code EC = getRvaPtr(ImportTableRva, IntPtr))
439     return EC;
440   ImportDirectory = reinterpret_cast<
441       const import_directory_table_entry *>(IntPtr);
442   return object_error::success;
443 }
444
445 // Find the export table.
446 error_code COFFObjectFile::initExportTablePtr() {
447   // First, we get the RVA of the export table. If the file lacks a pointer to
448   // the export table, do nothing.
449   const data_directory *DataEntry;
450   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
451     return object_error::success;
452
453   // Do nothing if the pointer to export table is NULL.
454   if (DataEntry->RelativeVirtualAddress == 0)
455     return object_error::success;
456
457   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
458   uintptr_t IntPtr = 0;
459   if (error_code EC = getRvaPtr(ExportTableRva, IntPtr))
460     return EC;
461   ExportDirectory =
462       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
463   return object_error::success;
464 }
465
466 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC,
467                                bool BufferOwned)
468     : ObjectFile(Binary::ID_COFF, Object, BufferOwned), COFFHeader(0),
469       PE32Header(0), PE32PlusHeader(0), DataDirectory(0), SectionTable(0),
470       SymbolTable(0), StringTable(0), StringTableSize(0), ImportDirectory(0),
471       NumberOfImportDirectory(0), ExportDirectory(0) {
472   // Check that we at least have enough room for a header.
473   if (!checkSize(Data, EC, sizeof(coff_file_header))) return;
474
475   // The current location in the file where we are looking at.
476   uint64_t CurPtr = 0;
477
478   // PE header is optional and is present only in executables. If it exists,
479   // it is placed right after COFF header.
480   bool HasPEHeader = false;
481
482   // Check if this is a PE/COFF file.
483   if (base()[0] == 0x4d && base()[1] == 0x5a) {
484     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
485     // PE signature to find 'normal' COFF header.
486     if (!checkSize(Data, EC, 0x3c + 8)) return;
487     CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
488     // Check the PE magic bytes. ("PE\0\0")
489     if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
490       EC = object_error::parse_failed;
491       return;
492     }
493     CurPtr += 4; // Skip the PE magic bytes.
494     HasPEHeader = true;
495   }
496
497   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
498     return;
499   CurPtr += sizeof(coff_file_header);
500
501   if (HasPEHeader) {
502     const pe32_header *Header;
503     if ((EC = getObject(Header, Data, base() + CurPtr)))
504       return;
505
506     const uint8_t *DataDirAddr;
507     uint64_t DataDirSize;
508     if (Header->Magic == 0x10b) {
509       PE32Header = Header;
510       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
511       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
512     } else if (Header->Magic == 0x20b) {
513       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
514       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
515       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
516     } else {
517       // It's neither PE32 nor PE32+.
518       EC = object_error::parse_failed;
519       return;
520     }
521     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
522       return;
523     CurPtr += COFFHeader->SizeOfOptionalHeader;
524   }
525
526   if (COFFHeader->isImportLibrary())
527     return;
528
529   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
530                       COFFHeader->NumberOfSections * sizeof(coff_section))))
531     return;
532
533   // Initialize the pointer to the symbol table.
534   if (COFFHeader->PointerToSymbolTable != 0)
535     if ((EC = initSymbolTablePtr()))
536       return;
537
538   // Initialize the pointer to the beginning of the import table.
539   if ((EC = initImportTablePtr()))
540     return;
541
542   // Initialize the pointer to the export table.
543   if ((EC = initExportTablePtr()))
544     return;
545
546   EC = object_error::success;
547 }
548
549 symbol_iterator COFFObjectFile::symbol_begin() const {
550   DataRefImpl Ret;
551   Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
552   return symbol_iterator(SymbolRef(Ret, this));
553 }
554
555 symbol_iterator COFFObjectFile::symbol_end() const {
556   // The symbol table ends where the string table begins.
557   DataRefImpl Ret;
558   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
559   return symbol_iterator(SymbolRef(Ret, this));
560 }
561
562 library_iterator COFFObjectFile::needed_library_begin() const {
563   // TODO: implement
564   report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
565 }
566
567 library_iterator COFFObjectFile::needed_library_end() const {
568   // TODO: implement
569   report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
570 }
571
572 StringRef COFFObjectFile::getLoadName() const {
573   // COFF does not have this field.
574   return "";
575 }
576
577 import_directory_iterator COFFObjectFile::import_directory_begin() const {
578   return import_directory_iterator(
579       ImportDirectoryEntryRef(ImportDirectory, 0, this));
580 }
581
582 import_directory_iterator COFFObjectFile::import_directory_end() const {
583   return import_directory_iterator(
584       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
585 }
586
587 export_directory_iterator COFFObjectFile::export_directory_begin() const {
588   return export_directory_iterator(
589       ExportDirectoryEntryRef(ExportDirectory, 0, this));
590 }
591
592 export_directory_iterator COFFObjectFile::export_directory_end() const {
593   if (ExportDirectory == 0)
594     return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this));
595   ExportDirectoryEntryRef Ref(ExportDirectory,
596                               ExportDirectory->AddressTableEntries, this);
597   return export_directory_iterator(Ref);
598 }
599
600 section_iterator COFFObjectFile::section_begin() const {
601   DataRefImpl Ret;
602   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
603   return section_iterator(SectionRef(Ret, this));
604 }
605
606 section_iterator COFFObjectFile::section_end() const {
607   DataRefImpl Ret;
608   int NumSections = COFFHeader->isImportLibrary()
609       ? 0 : COFFHeader->NumberOfSections;
610   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
611   return section_iterator(SectionRef(Ret, this));
612 }
613
614 uint8_t COFFObjectFile::getBytesInAddress() const {
615   return getArch() == Triple::x86_64 ? 8 : 4;
616 }
617
618 StringRef COFFObjectFile::getFileFormatName() const {
619   switch(COFFHeader->Machine) {
620   case COFF::IMAGE_FILE_MACHINE_I386:
621     return "COFF-i386";
622   case COFF::IMAGE_FILE_MACHINE_AMD64:
623     return "COFF-x86-64";
624   default:
625     return "COFF-<unknown arch>";
626   }
627 }
628
629 unsigned COFFObjectFile::getArch() const {
630   switch(COFFHeader->Machine) {
631   case COFF::IMAGE_FILE_MACHINE_I386:
632     return Triple::x86;
633   case COFF::IMAGE_FILE_MACHINE_AMD64:
634     return Triple::x86_64;
635   default:
636     return Triple::UnknownArch;
637   }
638 }
639
640 // This method is kept here because lld uses this. As soon as we make
641 // lld to use getCOFFHeader, this method will be removed.
642 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
643   return getCOFFHeader(Res);
644 }
645
646 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
647   Res = COFFHeader;
648   return object_error::success;
649 }
650
651 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
652   Res = PE32Header;
653   return object_error::success;
654 }
655
656 error_code
657 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
658   Res = PE32PlusHeader;
659   return object_error::success;
660 }
661
662 error_code COFFObjectFile::getDataDirectory(uint32_t Index,
663                                             const data_directory *&Res) const {
664   // Error if if there's no data directory or the index is out of range.
665   if (!DataDirectory)
666     return object_error::parse_failed;
667   assert(PE32Header || PE32PlusHeader);
668   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
669                                : PE32PlusHeader->NumberOfRvaAndSize;
670   if (Index > NumEnt)
671     return object_error::parse_failed;
672   Res = &DataDirectory[Index];
673   return object_error::success;
674 }
675
676 error_code COFFObjectFile::getSection(int32_t Index,
677                                       const coff_section *&Result) const {
678   // Check for special index values.
679   if (Index == COFF::IMAGE_SYM_UNDEFINED ||
680       Index == COFF::IMAGE_SYM_ABSOLUTE ||
681       Index == COFF::IMAGE_SYM_DEBUG)
682     Result = NULL;
683   else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
684     // We already verified the section table data, so no need to check again.
685     Result = SectionTable + (Index - 1);
686   else
687     return object_error::parse_failed;
688   return object_error::success;
689 }
690
691 error_code COFFObjectFile::getString(uint32_t Offset,
692                                      StringRef &Result) const {
693   if (StringTableSize <= 4)
694     // Tried to get a string from an empty string table.
695     return object_error::parse_failed;
696   if (Offset >= StringTableSize)
697     return object_error::unexpected_eof;
698   Result = StringRef(StringTable + Offset);
699   return object_error::success;
700 }
701
702 error_code COFFObjectFile::getSymbol(uint32_t Index,
703                                      const coff_symbol *&Result) const {
704   if (Index < COFFHeader->NumberOfSymbols)
705     Result = SymbolTable + Index;
706   else
707     return object_error::parse_failed;
708   return object_error::success;
709 }
710
711 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
712                                          StringRef &Res) const {
713   // Check for string table entry. First 4 bytes are 0.
714   if (Symbol->Name.Offset.Zeroes == 0) {
715     uint32_t Offset = Symbol->Name.Offset.Offset;
716     if (error_code EC = getString(Offset, Res))
717       return EC;
718     return object_error::success;
719   }
720
721   if (Symbol->Name.ShortName[7] == 0)
722     // Null terminated, let ::strlen figure out the length.
723     Res = StringRef(Symbol->Name.ShortName);
724   else
725     // Not null terminated, use all 8 bytes.
726     Res = StringRef(Symbol->Name.ShortName, 8);
727   return object_error::success;
728 }
729
730 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
731                                   const coff_symbol *Symbol) const {
732   const uint8_t *Aux = NULL;
733
734   if (Symbol->NumberOfAuxSymbols > 0) {
735   // AUX data comes immediately after the symbol in COFF
736     Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
737 # ifndef NDEBUG
738     // Verify that the Aux symbol points to a valid entry in the symbol table.
739     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
740     if (Offset < COFFHeader->PointerToSymbolTable
741         || Offset >= COFFHeader->PointerToSymbolTable
742            + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
743       report_fatal_error("Aux Symbol data was outside of symbol table.");
744
745     assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
746          == 0 && "Aux Symbol data did not point to the beginning of a symbol");
747 # endif
748   }
749   return ArrayRef<uint8_t>(Aux,
750                            Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
751 }
752
753 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
754                                           StringRef &Res) const {
755   StringRef Name;
756   if (Sec->Name[7] == 0)
757     // Null terminated, let ::strlen figure out the length.
758     Name = Sec->Name;
759   else
760     // Not null terminated, use all 8 bytes.
761     Name = StringRef(Sec->Name, 8);
762
763   // Check for string table entry. First byte is '/'.
764   if (Name[0] == '/') {
765     uint32_t Offset;
766     if (Name.substr(1).getAsInteger(10, Offset))
767       return object_error::parse_failed;
768     if (error_code EC = getString(Offset, Name))
769       return EC;
770   }
771
772   Res = Name;
773   return object_error::success;
774 }
775
776 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
777                                               ArrayRef<uint8_t> &Res) const {
778   // The only thing that we need to verify is that the contents is contained
779   // within the file bounds. We don't need to make sure it doesn't cover other
780   // data, as there's nothing that says that is not allowed.
781   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
782   uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
783   if (ConEnd > uintptr_t(Data->getBufferEnd()))
784     return object_error::parse_failed;
785   Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
786                           Sec->SizeOfRawData);
787   return object_error::success;
788 }
789
790 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
791   return reinterpret_cast<const coff_relocation*>(Rel.p);
792 }
793
794 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
795   Rel.p = reinterpret_cast<uintptr_t>(
796             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
797 }
798
799 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
800                                                 uint64_t &Res) const {
801   report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
802 }
803
804 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
805                                                uint64_t &Res) const {
806   Res = toRel(Rel)->VirtualAddress;
807   return object_error::success;
808 }
809
810 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
811   const coff_relocation* R = toRel(Rel);
812   DataRefImpl Ref;
813   Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
814   return symbol_iterator(SymbolRef(Ref, this));
815 }
816
817 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
818                                              uint64_t &Res) const {
819   const coff_relocation* R = toRel(Rel);
820   Res = R->Type;
821   return object_error::success;
822 }
823
824 const coff_section *COFFObjectFile::getCOFFSection(section_iterator &It) const {
825   return toSec(It->getRawDataRefImpl());
826 }
827
828 const coff_symbol *COFFObjectFile::getCOFFSymbol(symbol_iterator &It) const {
829   return toSymb(It->getRawDataRefImpl());
830 }
831
832 const coff_relocation *COFFObjectFile::getCOFFRelocation(
833                                              relocation_iterator &It) const {
834   return toRel(It->getRawDataRefImpl());
835 }
836
837 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(enum) \
838   case COFF::enum: Res = #enum; break;
839
840 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
841                                           SmallVectorImpl<char> &Result) const {
842   const coff_relocation *Reloc = toRel(Rel);
843   StringRef Res;
844   switch (COFFHeader->Machine) {
845   case COFF::IMAGE_FILE_MACHINE_AMD64:
846     switch (Reloc->Type) {
847     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
848     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
849     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
850     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
851     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
852     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
853     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
854     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
855     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
856     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
857     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
858     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
859     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
860     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
861     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
862     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
863     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
864     default:
865       Res = "Unknown";
866     }
867     break;
868   case COFF::IMAGE_FILE_MACHINE_I386:
869     switch (Reloc->Type) {
870     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
871     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
872     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
873     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
874     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
875     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
876     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
877     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
878     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
879     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
880     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
881     default:
882       Res = "Unknown";
883     }
884     break;
885   default:
886     Res = "Unknown";
887   }
888   Result.append(Res.begin(), Res.end());
889   return object_error::success;
890 }
891
892 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
893
894 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
895                                           SmallVectorImpl<char> &Result) const {
896   const coff_relocation *Reloc = toRel(Rel);
897   const coff_symbol *Symb = 0;
898   if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
899   DataRefImpl Sym;
900   Sym.p = reinterpret_cast<uintptr_t>(Symb);
901   StringRef SymName;
902   if (error_code EC = getSymbolName(Sym, SymName)) return EC;
903   Result.append(SymName.begin(), SymName.end());
904   return object_error::success;
905 }
906
907 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
908                                           LibraryRef &Result) const {
909   report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
910 }
911
912 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
913                                           StringRef &Result) const {
914   report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
915 }
916
917 bool ImportDirectoryEntryRef::
918 operator==(const ImportDirectoryEntryRef &Other) const {
919   return ImportTable == Other.ImportTable && Index == Other.Index;
920 }
921
922 void ImportDirectoryEntryRef::moveNext() {
923   ++Index;
924 }
925
926 error_code ImportDirectoryEntryRef::
927 getImportTableEntry(const import_directory_table_entry *&Result) const {
928   Result = ImportTable;
929   return object_error::success;
930 }
931
932 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
933   uintptr_t IntPtr = 0;
934   if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
935     return EC;
936   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
937   return object_error::success;
938 }
939
940 error_code ImportDirectoryEntryRef::getImportLookupEntry(
941     const import_lookup_table_entry32 *&Result) const {
942   uintptr_t IntPtr = 0;
943   if (error_code EC =
944           OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
945     return EC;
946   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
947   return object_error::success;
948 }
949
950 bool ExportDirectoryEntryRef::
951 operator==(const ExportDirectoryEntryRef &Other) const {
952   return ExportTable == Other.ExportTable && Index == Other.Index;
953 }
954
955 void ExportDirectoryEntryRef::moveNext() {
956   ++Index;
957 }
958
959 // Returns the name of the current export symbol. If the symbol is exported only
960 // by ordinal, the empty string is set as a result.
961 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
962   uintptr_t IntPtr = 0;
963   if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
964     return EC;
965   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
966   return object_error::success;
967 }
968
969 // Returns the starting ordinal number.
970 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
971   Result = ExportTable->OrdinalBase;
972   return object_error::success;
973 }
974
975 // Returns the export ordinal of the current export symbol.
976 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
977   Result = ExportTable->OrdinalBase + Index;
978   return object_error::success;
979 }
980
981 // Returns the address of the current export symbol.
982 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
983   uintptr_t IntPtr = 0;
984   if (error_code EC = OwningObject->getRvaPtr(
985           ExportTable->ExportAddressTableRVA, IntPtr))
986     return EC;
987   const export_address_table_entry *entry =
988       reinterpret_cast<const export_address_table_entry *>(IntPtr);
989   Result = entry[Index].ExportRVA;
990   return object_error::success;
991 }
992
993 // Returns the name of the current export symbol. If the symbol is exported only
994 // by ordinal, the empty string is set as a result.
995 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
996   uintptr_t IntPtr = 0;
997   if (error_code EC = OwningObject->getRvaPtr(
998           ExportTable->OrdinalTableRVA, IntPtr))
999     return EC;
1000   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1001
1002   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1003   int Offset = 0;
1004   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1005        I < E; ++I, ++Offset) {
1006     if (*I != Index)
1007       continue;
1008     if (error_code EC = OwningObject->getRvaPtr(
1009             ExportTable->NamePointerRVA, IntPtr))
1010       return EC;
1011     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1012     if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1013       return EC;
1014     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1015     return object_error::success;
1016   }
1017   Result = "";
1018   return object_error::success;
1019 }
1020
1021 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object,
1022                                                        bool BufferOwned) {
1023   error_code EC;
1024   OwningPtr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC, BufferOwned));
1025   if (EC)
1026     return EC;
1027   return Ret.take();
1028 }