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