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