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