507d690f0964232120e9baa42a7b9f52adbde662
[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/ADT/iterator_range.h"
20 #include "llvm/Support/COFF.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <cctype>
24 #include <limits>
25
26 using namespace llvm;
27 using namespace object;
28
29 using support::ulittle16_t;
30 using support::ulittle32_t;
31 using support::ulittle64_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(MemoryBufferRef M, std::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 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
44                                    const uint64_t Size) {
45   if (Addr + Size < Addr || Addr + Size < Size ||
46       Addr + Size > uintptr_t(M.getBufferEnd()) ||
47       Addr < uintptr_t(M.getBufferStart())) {
48     return object_error::unexpected_eof;
49   }
50   return std::error_code();
51 }
52
53 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
54 // Returns unexpected_eof if error.
55 template <typename T>
56 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
57                                  const void *Ptr,
58                                  const uint64_t Size = sizeof(T)) {
59   uintptr_t Addr = uintptr_t(Ptr);
60   if (std::error_code EC = checkOffset(M, Addr, Size))
61     return EC;
62   Obj = reinterpret_cast<const T *>(Addr);
63   return std::error_code();
64 }
65
66 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
67 // prefixed slashes.
68 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
69   assert(Str.size() <= 6 && "String too long, possible overflow.");
70   if (Str.size() > 6)
71     return true;
72
73   uint64_t Value = 0;
74   while (!Str.empty()) {
75     unsigned CharVal;
76     if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
77       CharVal = Str[0] - 'A';
78     else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
79       CharVal = Str[0] - 'a' + 26;
80     else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
81       CharVal = Str[0] - '0' + 52;
82     else if (Str[0] == '+') // 62
83       CharVal = 62;
84     else if (Str[0] == '/') // 63
85       CharVal = 63;
86     else
87       return true;
88
89     Value = (Value * 64) + CharVal;
90     Str = Str.substr(1);
91   }
92
93   if (Value > std::numeric_limits<uint32_t>::max())
94     return true;
95
96   Result = static_cast<uint32_t>(Value);
97   return false;
98 }
99
100 template <typename coff_symbol_type>
101 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
102   const coff_symbol_type *Addr =
103       reinterpret_cast<const coff_symbol_type *>(Ref.p);
104
105   assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
106 #ifndef NDEBUG
107   // Verify that the symbol points to a valid entry in the symbol table.
108   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
109
110   assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
111          "Symbol did not point to the beginning of a symbol");
112 #endif
113
114   return Addr;
115 }
116
117 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
118   const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
119
120 # ifndef NDEBUG
121   // Verify that the section points to a valid entry in the section table.
122   if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
123     report_fatal_error("Section was outside of section table.");
124
125   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
126   assert(Offset % sizeof(coff_section) == 0 &&
127          "Section did not point to the beginning of a section");
128 # endif
129
130   return Addr;
131 }
132
133 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
134   auto End = reinterpret_cast<uintptr_t>(StringTable);
135   if (SymbolTable16) {
136     const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
137     Symb += 1 + Symb->NumberOfAuxSymbols;
138     Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
139   } else if (SymbolTable32) {
140     const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
141     Symb += 1 + Symb->NumberOfAuxSymbols;
142     Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
143   } else {
144     llvm_unreachable("no symbol table pointer!");
145   }
146 }
147
148 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
149                                               StringRef &Result) const {
150   COFFSymbolRef Symb = getCOFFSymbol(Ref);
151   return getSymbolName(Symb, Result);
152 }
153
154 uint64_t COFFObjectFile::getSymbolValue(DataRefImpl Ref) const {
155   COFFSymbolRef Sym = getCOFFSymbol(Ref);
156
157   if (Sym.isAnyUndefined() || Sym.isCommon())
158     return UnknownAddress;
159
160   return Sym.getValue();
161 }
162
163 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
164                                                  uint64_t &Result) const {
165   Result = getSymbolValue(Ref);
166   COFFSymbolRef Symb = getCOFFSymbol(Ref);
167   int32_t SectionNumber = Symb.getSectionNumber();
168
169   if (Symb.isAnyUndefined() || Symb.isCommon() ||
170       COFF::isReservedSectionNumber(SectionNumber))
171     return std::error_code();
172
173   const coff_section *Section = nullptr;
174   if (std::error_code EC = getSection(SectionNumber, Section))
175     return EC;
176   Result += Section->VirtualAddress;
177   return std::error_code();
178 }
179
180 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
181                                               SymbolRef::Type &Result) const {
182   COFFSymbolRef Symb = getCOFFSymbol(Ref);
183   int32_t SectionNumber = Symb.getSectionNumber();
184   Result = SymbolRef::ST_Other;
185
186   if (Symb.isAnyUndefined()) {
187     Result = SymbolRef::ST_Unknown;
188   } else if (Symb.isFunctionDefinition()) {
189     Result = SymbolRef::ST_Function;
190   } else if (Symb.isCommon()) {
191     Result = SymbolRef::ST_Data;
192   } else if (Symb.isFileRecord()) {
193     Result = SymbolRef::ST_File;
194   } else if (SectionNumber == COFF::IMAGE_SYM_DEBUG ||
195              Symb.isSectionDefinition()) {
196     // TODO: perhaps we need a new symbol type ST_Section.
197     Result = SymbolRef::ST_Debug;
198   } else if (!COFF::isReservedSectionNumber(SectionNumber)) {
199     const coff_section *Section = nullptr;
200     if (std::error_code EC = getSection(SectionNumber, Section))
201       return EC;
202     uint32_t Characteristics = Section->Characteristics;
203     if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
204       Result = SymbolRef::ST_Function;
205     else if (Characteristics & (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
206                                 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA))
207       Result = SymbolRef::ST_Data;
208   }
209   return std::error_code();
210 }
211
212 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
213   COFFSymbolRef Symb = getCOFFSymbol(Ref);
214   uint32_t Result = SymbolRef::SF_None;
215
216   if (Symb.isExternal() || Symb.isWeakExternal())
217     Result |= SymbolRef::SF_Global;
218
219   if (Symb.isWeakExternal())
220     Result |= SymbolRef::SF_Weak;
221
222   if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
223     Result |= SymbolRef::SF_Absolute;
224
225   if (Symb.isFileRecord())
226     Result |= SymbolRef::SF_FormatSpecific;
227
228   if (Symb.isSectionDefinition())
229     Result |= SymbolRef::SF_FormatSpecific;
230
231   if (Symb.isCommon())
232     Result |= SymbolRef::SF_Common;
233
234   if (Symb.isAnyUndefined())
235     Result |= SymbolRef::SF_Undefined;
236
237   return Result;
238 }
239
240 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
241   COFFSymbolRef Symb = getCOFFSymbol(Ref);
242   return Symb.getValue();
243 }
244
245 std::error_code
246 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
247                                  section_iterator &Result) const {
248   COFFSymbolRef Symb = getCOFFSymbol(Ref);
249   if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
250     Result = section_end();
251   } else {
252     const coff_section *Sec = nullptr;
253     if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
254       return EC;
255     DataRefImpl Ref;
256     Ref.p = reinterpret_cast<uintptr_t>(Sec);
257     Result = section_iterator(SectionRef(Ref, this));
258   }
259   return std::error_code();
260 }
261
262 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
263   COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
264   return Symb.getSectionNumber();
265 }
266
267 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
268   const coff_section *Sec = toSec(Ref);
269   Sec += 1;
270   Ref.p = reinterpret_cast<uintptr_t>(Sec);
271 }
272
273 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
274                                                StringRef &Result) const {
275   const coff_section *Sec = toSec(Ref);
276   return getSectionName(Sec, Result);
277 }
278
279 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
280   const coff_section *Sec = toSec(Ref);
281   return Sec->VirtualAddress;
282 }
283
284 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
285   return getSectionSize(toSec(Ref));
286 }
287
288 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
289                                                    StringRef &Result) const {
290   const coff_section *Sec = toSec(Ref);
291   ArrayRef<uint8_t> Res;
292   std::error_code EC = getSectionContents(Sec, Res);
293   Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
294   return EC;
295 }
296
297 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
298   const coff_section *Sec = toSec(Ref);
299   return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
300 }
301
302 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
303   const coff_section *Sec = toSec(Ref);
304   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
305 }
306
307 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
308   const coff_section *Sec = toSec(Ref);
309   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
310 }
311
312 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
313   const coff_section *Sec = toSec(Ref);
314   const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
315                             COFF::IMAGE_SCN_MEM_READ |
316                             COFF::IMAGE_SCN_MEM_WRITE;
317   return (Sec->Characteristics & BssFlags) == BssFlags;
318 }
319
320 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
321   uintptr_t Offset =
322       uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
323   assert((Offset % sizeof(coff_section)) == 0);
324   return (Offset / sizeof(coff_section)) + 1;
325 }
326
327 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
328   const coff_section *Sec = toSec(Ref);
329   // In COFF, a virtual section won't have any in-file 
330   // content, so the file pointer to the content will be zero.
331   return Sec->PointerToRawData == 0;
332 }
333
334 bool COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
335                                            DataRefImpl SymbRef) const {
336   const coff_section *Sec = toSec(SecRef);
337   COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
338   int32_t SecNumber = (Sec - SectionTable) + 1;
339   return SecNumber == Symb.getSectionNumber();
340 }
341
342 static uint32_t getNumberOfRelocations(const coff_section *Sec,
343                                        MemoryBufferRef M, const uint8_t *base) {
344   // The field for the number of relocations in COFF section table is only
345   // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
346   // NumberOfRelocations field, and the actual relocation count is stored in the
347   // VirtualAddress field in the first relocation entry.
348   if (Sec->hasExtendedRelocations()) {
349     const coff_relocation *FirstReloc;
350     if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
351         base + Sec->PointerToRelocations)))
352       return 0;
353     // -1 to exclude this first relocation entry.
354     return FirstReloc->VirtualAddress - 1;
355   }
356   return Sec->NumberOfRelocations;
357 }
358
359 static const coff_relocation *
360 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
361   uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
362   if (!NumRelocs)
363     return nullptr;
364   auto begin = reinterpret_cast<const coff_relocation *>(
365       Base + Sec->PointerToRelocations);
366   if (Sec->hasExtendedRelocations()) {
367     // Skip the first relocation entry repurposed to store the number of
368     // relocations.
369     begin++;
370   }
371   if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
372     return nullptr;
373   return begin;
374 }
375
376 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
377   const coff_section *Sec = toSec(Ref);
378   const coff_relocation *begin = getFirstReloc(Sec, Data, base());
379   DataRefImpl Ret;
380   Ret.p = reinterpret_cast<uintptr_t>(begin);
381   return relocation_iterator(RelocationRef(Ret, this));
382 }
383
384 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
385   const coff_section *Sec = toSec(Ref);
386   const coff_relocation *I = getFirstReloc(Sec, Data, base());
387   if (I)
388     I += getNumberOfRelocations(Sec, Data, base());
389   DataRefImpl Ret;
390   Ret.p = reinterpret_cast<uintptr_t>(I);
391   return relocation_iterator(RelocationRef(Ret, this));
392 }
393
394 // Initialize the pointer to the symbol table.
395 std::error_code COFFObjectFile::initSymbolTablePtr() {
396   if (COFFHeader)
397     if (std::error_code EC = getObject(
398             SymbolTable16, Data, base() + getPointerToSymbolTable(),
399             (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
400       return EC;
401
402   if (COFFBigObjHeader)
403     if (std::error_code EC = getObject(
404             SymbolTable32, Data, base() + getPointerToSymbolTable(),
405             (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
406       return EC;
407
408   // Find string table. The first four byte of the string table contains the
409   // total size of the string table, including the size field itself. If the
410   // string table is empty, the value of the first four byte would be 4.
411   uint32_t StringTableOffset = getPointerToSymbolTable() +
412                                getNumberOfSymbols() * getSymbolTableEntrySize();
413   const uint8_t *StringTableAddr = base() + StringTableOffset;
414   const ulittle32_t *StringTableSizePtr;
415   if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
416     return EC;
417   StringTableSize = *StringTableSizePtr;
418   if (std::error_code EC =
419           getObject(StringTable, Data, StringTableAddr, StringTableSize))
420     return EC;
421
422   // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
423   // tools like cvtres write a size of 0 for an empty table instead of 4.
424   if (StringTableSize < 4)
425       StringTableSize = 4;
426
427   // Check that the string table is null terminated if has any in it.
428   if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
429     return  object_error::parse_failed;
430   return std::error_code();
431 }
432
433 // Returns the file offset for the given VA.
434 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
435   uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
436                                   : (uint64_t)PE32PlusHeader->ImageBase;
437   uint64_t Rva = Addr - ImageBase;
438   assert(Rva <= UINT32_MAX);
439   return getRvaPtr((uint32_t)Rva, Res);
440 }
441
442 // Returns the file offset for the given RVA.
443 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
444   for (const SectionRef &S : sections()) {
445     const coff_section *Section = getCOFFSection(S);
446     uint32_t SectionStart = Section->VirtualAddress;
447     uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
448     if (SectionStart <= Addr && Addr < SectionEnd) {
449       uint32_t Offset = Addr - SectionStart;
450       Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
451       return std::error_code();
452     }
453   }
454   return object_error::parse_failed;
455 }
456
457 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
458 // table entry.
459 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
460                                             StringRef &Name) const {
461   uintptr_t IntPtr = 0;
462   if (std::error_code EC = getRvaPtr(Rva, IntPtr))
463     return EC;
464   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
465   Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
466   Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
467   return std::error_code();
468 }
469
470 // Find the import table.
471 std::error_code COFFObjectFile::initImportTablePtr() {
472   // First, we get the RVA of the import table. If the file lacks a pointer to
473   // the import table, do nothing.
474   const data_directory *DataEntry;
475   if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
476     return std::error_code();
477
478   // Do nothing if the pointer to import table is NULL.
479   if (DataEntry->RelativeVirtualAddress == 0)
480     return std::error_code();
481
482   uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
483   // -1 because the last entry is the null entry.
484   NumberOfImportDirectory = DataEntry->Size /
485       sizeof(import_directory_table_entry) - 1;
486
487   // Find the section that contains the RVA. This is needed because the RVA is
488   // the import table's memory address which is different from its file offset.
489   uintptr_t IntPtr = 0;
490   if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
491     return EC;
492   ImportDirectory = reinterpret_cast<
493       const import_directory_table_entry *>(IntPtr);
494   return std::error_code();
495 }
496
497 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
498 std::error_code COFFObjectFile::initDelayImportTablePtr() {
499   const data_directory *DataEntry;
500   if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
501     return std::error_code();
502   if (DataEntry->RelativeVirtualAddress == 0)
503     return std::error_code();
504
505   uint32_t RVA = DataEntry->RelativeVirtualAddress;
506   NumberOfDelayImportDirectory = DataEntry->Size /
507       sizeof(delay_import_directory_table_entry) - 1;
508
509   uintptr_t IntPtr = 0;
510   if (std::error_code EC = getRvaPtr(RVA, IntPtr))
511     return EC;
512   DelayImportDirectory = reinterpret_cast<
513       const delay_import_directory_table_entry *>(IntPtr);
514   return std::error_code();
515 }
516
517 // Find the export table.
518 std::error_code COFFObjectFile::initExportTablePtr() {
519   // First, we get the RVA of the export table. If the file lacks a pointer to
520   // the export table, do nothing.
521   const data_directory *DataEntry;
522   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
523     return std::error_code();
524
525   // Do nothing if the pointer to export table is NULL.
526   if (DataEntry->RelativeVirtualAddress == 0)
527     return std::error_code();
528
529   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
530   uintptr_t IntPtr = 0;
531   if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
532     return EC;
533   ExportDirectory =
534       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
535   return std::error_code();
536 }
537
538 std::error_code COFFObjectFile::initBaseRelocPtr() {
539   const data_directory *DataEntry;
540   if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
541     return std::error_code();
542   if (DataEntry->RelativeVirtualAddress == 0)
543     return std::error_code();
544
545   uintptr_t IntPtr = 0;
546   if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
547     return EC;
548   BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
549       IntPtr);
550   BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
551       IntPtr + DataEntry->Size);
552   return std::error_code();
553 }
554
555 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
556     : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
557       COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
558       DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
559       SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
560       ImportDirectory(nullptr), NumberOfImportDirectory(0),
561       DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
562       ExportDirectory(nullptr), BaseRelocHeader(nullptr),
563       BaseRelocEnd(nullptr) {
564   // Check that we at least have enough room for a header.
565   if (!checkSize(Data, EC, sizeof(coff_file_header)))
566     return;
567
568   // The current location in the file where we are looking at.
569   uint64_t CurPtr = 0;
570
571   // PE header is optional and is present only in executables. If it exists,
572   // it is placed right after COFF header.
573   bool HasPEHeader = false;
574
575   // Check if this is a PE/COFF file.
576   if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
577     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
578     // PE signature to find 'normal' COFF header.
579     const auto *DH = reinterpret_cast<const dos_header *>(base());
580     if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
581       CurPtr = DH->AddressOfNewExeHeader;
582       // Check the PE magic bytes. ("PE\0\0")
583       if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
584         EC = object_error::parse_failed;
585         return;
586       }
587       CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
588       HasPEHeader = true;
589     }
590   }
591
592   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
593     return;
594
595   // It might be a bigobj file, let's check.  Note that COFF bigobj and COFF
596   // import libraries share a common prefix but bigobj is more restrictive.
597   if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
598       COFFHeader->NumberOfSections == uint16_t(0xffff) &&
599       checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
600     if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
601       return;
602
603     // Verify that we are dealing with bigobj.
604     if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
605         std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
606                     sizeof(COFF::BigObjMagic)) == 0) {
607       COFFHeader = nullptr;
608       CurPtr += sizeof(coff_bigobj_file_header);
609     } else {
610       // It's not a bigobj.
611       COFFBigObjHeader = nullptr;
612     }
613   }
614   if (COFFHeader) {
615     // The prior checkSize call may have failed.  This isn't a hard error
616     // because we were just trying to sniff out bigobj.
617     EC = std::error_code();
618     CurPtr += sizeof(coff_file_header);
619
620     if (COFFHeader->isImportLibrary())
621       return;
622   }
623
624   if (HasPEHeader) {
625     const pe32_header *Header;
626     if ((EC = getObject(Header, Data, base() + CurPtr)))
627       return;
628
629     const uint8_t *DataDirAddr;
630     uint64_t DataDirSize;
631     if (Header->Magic == COFF::PE32Header::PE32) {
632       PE32Header = Header;
633       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
634       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
635     } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
636       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
637       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
638       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
639     } else {
640       // It's neither PE32 nor PE32+.
641       EC = object_error::parse_failed;
642       return;
643     }
644     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
645       return;
646     CurPtr += COFFHeader->SizeOfOptionalHeader;
647   }
648
649   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
650                       (uint64_t)getNumberOfSections() * sizeof(coff_section))))
651     return;
652
653   // Initialize the pointer to the symbol table.
654   if (getPointerToSymbolTable() != 0) {
655     if ((EC = initSymbolTablePtr()))
656       return;
657   } else {
658     // We had better not have any symbols if we don't have a symbol table.
659     if (getNumberOfSymbols() != 0) {
660       EC = object_error::parse_failed;
661       return;
662     }
663   }
664
665   // Initialize the pointer to the beginning of the import table.
666   if ((EC = initImportTablePtr()))
667     return;
668   if ((EC = initDelayImportTablePtr()))
669     return;
670
671   // Initialize the pointer to the export table.
672   if ((EC = initExportTablePtr()))
673     return;
674
675   // Initialize the pointer to the base relocation table.
676   if ((EC = initBaseRelocPtr()))
677     return;
678
679   EC = std::error_code();
680 }
681
682 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
683   DataRefImpl Ret;
684   Ret.p = getSymbolTable();
685   return basic_symbol_iterator(SymbolRef(Ret, this));
686 }
687
688 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
689   // The symbol table ends where the string table begins.
690   DataRefImpl Ret;
691   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
692   return basic_symbol_iterator(SymbolRef(Ret, this));
693 }
694
695 import_directory_iterator COFFObjectFile::import_directory_begin() const {
696   return import_directory_iterator(
697       ImportDirectoryEntryRef(ImportDirectory, 0, this));
698 }
699
700 import_directory_iterator COFFObjectFile::import_directory_end() const {
701   return import_directory_iterator(
702       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
703 }
704
705 delay_import_directory_iterator
706 COFFObjectFile::delay_import_directory_begin() const {
707   return delay_import_directory_iterator(
708       DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
709 }
710
711 delay_import_directory_iterator
712 COFFObjectFile::delay_import_directory_end() const {
713   return delay_import_directory_iterator(
714       DelayImportDirectoryEntryRef(
715           DelayImportDirectory, NumberOfDelayImportDirectory, this));
716 }
717
718 export_directory_iterator COFFObjectFile::export_directory_begin() const {
719   return export_directory_iterator(
720       ExportDirectoryEntryRef(ExportDirectory, 0, this));
721 }
722
723 export_directory_iterator COFFObjectFile::export_directory_end() const {
724   if (!ExportDirectory)
725     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
726   ExportDirectoryEntryRef Ref(ExportDirectory,
727                               ExportDirectory->AddressTableEntries, this);
728   return export_directory_iterator(Ref);
729 }
730
731 section_iterator COFFObjectFile::section_begin() const {
732   DataRefImpl Ret;
733   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
734   return section_iterator(SectionRef(Ret, this));
735 }
736
737 section_iterator COFFObjectFile::section_end() const {
738   DataRefImpl Ret;
739   int NumSections =
740       COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
741   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
742   return section_iterator(SectionRef(Ret, this));
743 }
744
745 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
746   return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
747 }
748
749 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
750   return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
751 }
752
753 uint8_t COFFObjectFile::getBytesInAddress() const {
754   return getArch() == Triple::x86_64 ? 8 : 4;
755 }
756
757 StringRef COFFObjectFile::getFileFormatName() const {
758   switch(getMachine()) {
759   case COFF::IMAGE_FILE_MACHINE_I386:
760     return "COFF-i386";
761   case COFF::IMAGE_FILE_MACHINE_AMD64:
762     return "COFF-x86-64";
763   case COFF::IMAGE_FILE_MACHINE_ARMNT:
764     return "COFF-ARM";
765   default:
766     return "COFF-<unknown arch>";
767   }
768 }
769
770 unsigned COFFObjectFile::getArch() const {
771   switch (getMachine()) {
772   case COFF::IMAGE_FILE_MACHINE_I386:
773     return Triple::x86;
774   case COFF::IMAGE_FILE_MACHINE_AMD64:
775     return Triple::x86_64;
776   case COFF::IMAGE_FILE_MACHINE_ARMNT:
777     return Triple::thumb;
778   default:
779     return Triple::UnknownArch;
780   }
781 }
782
783 iterator_range<import_directory_iterator>
784 COFFObjectFile::import_directories() const {
785   return make_range(import_directory_begin(), import_directory_end());
786 }
787
788 iterator_range<delay_import_directory_iterator>
789 COFFObjectFile::delay_import_directories() const {
790   return make_range(delay_import_directory_begin(),
791                     delay_import_directory_end());
792 }
793
794 iterator_range<export_directory_iterator>
795 COFFObjectFile::export_directories() const {
796   return make_range(export_directory_begin(), export_directory_end());
797 }
798
799 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
800   return make_range(base_reloc_begin(), base_reloc_end());
801 }
802
803 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
804   Res = PE32Header;
805   return std::error_code();
806 }
807
808 std::error_code
809 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
810   Res = PE32PlusHeader;
811   return std::error_code();
812 }
813
814 std::error_code
815 COFFObjectFile::getDataDirectory(uint32_t Index,
816                                  const data_directory *&Res) const {
817   // Error if if there's no data directory or the index is out of range.
818   if (!DataDirectory) {
819     Res = nullptr;
820     return object_error::parse_failed;
821   }
822   assert(PE32Header || PE32PlusHeader);
823   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
824                                : PE32PlusHeader->NumberOfRvaAndSize;
825   if (Index >= NumEnt) {
826     Res = nullptr;
827     return object_error::parse_failed;
828   }
829   Res = &DataDirectory[Index];
830   return std::error_code();
831 }
832
833 std::error_code COFFObjectFile::getSection(int32_t Index,
834                                            const coff_section *&Result) const {
835   Result = nullptr;
836   if (COFF::isReservedSectionNumber(Index))
837     return std::error_code();
838   if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
839     // We already verified the section table data, so no need to check again.
840     Result = SectionTable + (Index - 1);
841     return std::error_code();
842   }
843   return object_error::parse_failed;
844 }
845
846 std::error_code COFFObjectFile::getString(uint32_t Offset,
847                                           StringRef &Result) const {
848   if (StringTableSize <= 4)
849     // Tried to get a string from an empty string table.
850     return object_error::parse_failed;
851   if (Offset >= StringTableSize)
852     return object_error::unexpected_eof;
853   Result = StringRef(StringTable + Offset);
854   return std::error_code();
855 }
856
857 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
858                                               StringRef &Res) const {
859   // Check for string table entry. First 4 bytes are 0.
860   if (Symbol.getStringTableOffset().Zeroes == 0) {
861     uint32_t Offset = Symbol.getStringTableOffset().Offset;
862     if (std::error_code EC = getString(Offset, Res))
863       return EC;
864     return std::error_code();
865   }
866
867   if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
868     // Null terminated, let ::strlen figure out the length.
869     Res = StringRef(Symbol.getShortName());
870   else
871     // Not null terminated, use all 8 bytes.
872     Res = StringRef(Symbol.getShortName(), COFF::NameSize);
873   return std::error_code();
874 }
875
876 ArrayRef<uint8_t>
877 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
878   const uint8_t *Aux = nullptr;
879
880   size_t SymbolSize = getSymbolTableEntrySize();
881   if (Symbol.getNumberOfAuxSymbols() > 0) {
882     // AUX data comes immediately after the symbol in COFF
883     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
884 # ifndef NDEBUG
885     // Verify that the Aux symbol points to a valid entry in the symbol table.
886     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
887     if (Offset < getPointerToSymbolTable() ||
888         Offset >=
889             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
890       report_fatal_error("Aux Symbol data was outside of symbol table.");
891
892     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
893            "Aux Symbol data did not point to the beginning of a symbol");
894 # endif
895   }
896   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
897 }
898
899 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
900                                                StringRef &Res) const {
901   StringRef Name;
902   if (Sec->Name[COFF::NameSize - 1] == 0)
903     // Null terminated, let ::strlen figure out the length.
904     Name = Sec->Name;
905   else
906     // Not null terminated, use all 8 bytes.
907     Name = StringRef(Sec->Name, COFF::NameSize);
908
909   // Check for string table entry. First byte is '/'.
910   if (Name.startswith("/")) {
911     uint32_t Offset;
912     if (Name.startswith("//")) {
913       if (decodeBase64StringEntry(Name.substr(2), Offset))
914         return object_error::parse_failed;
915     } else {
916       if (Name.substr(1).getAsInteger(10, Offset))
917         return object_error::parse_failed;
918     }
919     if (std::error_code EC = getString(Offset, Name))
920       return EC;
921   }
922
923   Res = Name;
924   return std::error_code();
925 }
926
927 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
928   // SizeOfRawData and VirtualSize change what they represent depending on
929   // whether or not we have an executable image.
930   //
931   // For object files, SizeOfRawData contains the size of section's data;
932   // VirtualSize is always zero.
933   //
934   // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
935   // actual section size is in VirtualSize.  It is possible for VirtualSize to
936   // be greater than SizeOfRawData; the contents past that point should be
937   // considered to be zero.
938   uint32_t SectionSize;
939   if (Sec->VirtualSize)
940     SectionSize = std::min(Sec->VirtualSize, Sec->SizeOfRawData);
941   else
942     SectionSize = Sec->SizeOfRawData;
943
944   return SectionSize;
945 }
946
947 std::error_code
948 COFFObjectFile::getSectionContents(const coff_section *Sec,
949                                    ArrayRef<uint8_t> &Res) const {
950   // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
951   // don't do anything interesting for them.
952   assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
953          "BSS sections don't have contents!");
954   // The only thing that we need to verify is that the contents is contained
955   // within the file bounds. We don't need to make sure it doesn't cover other
956   // data, as there's nothing that says that is not allowed.
957   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
958   uint32_t SectionSize = getSectionSize(Sec);
959   if (checkOffset(Data, ConStart, SectionSize))
960     return object_error::parse_failed;
961   Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
962   return std::error_code();
963 }
964
965 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
966   return reinterpret_cast<const coff_relocation*>(Rel.p);
967 }
968
969 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
970   Rel.p = reinterpret_cast<uintptr_t>(
971             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
972 }
973
974 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
975                                                      uint64_t &Res) const {
976   report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
977 }
978
979 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
980                                                     uint64_t &Res) const {
981   const coff_relocation *R = toRel(Rel);
982   const support::ulittle32_t *VirtualAddressPtr;
983   if (std::error_code EC =
984           getObject(VirtualAddressPtr, Data, &R->VirtualAddress))
985     return EC;
986   Res = *VirtualAddressPtr;
987   return std::error_code();
988 }
989
990 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
991   const coff_relocation *R = toRel(Rel);
992   DataRefImpl Ref;
993   if (R->SymbolTableIndex >= getNumberOfSymbols())
994     return symbol_end();
995   if (SymbolTable16)
996     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
997   else if (SymbolTable32)
998     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
999   else
1000     llvm_unreachable("no symbol table pointer!");
1001   return symbol_iterator(SymbolRef(Ref, this));
1002 }
1003
1004 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
1005                                                   uint64_t &Res) const {
1006   const coff_relocation* R = toRel(Rel);
1007   Res = R->Type;
1008   return std::error_code();
1009 }
1010
1011 const coff_section *
1012 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1013   return toSec(Section.getRawDataRefImpl());
1014 }
1015
1016 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1017   if (SymbolTable16)
1018     return toSymb<coff_symbol16>(Ref);
1019   if (SymbolTable32)
1020     return toSymb<coff_symbol32>(Ref);
1021   llvm_unreachable("no symbol table pointer!");
1022 }
1023
1024 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1025   return getCOFFSymbol(Symbol.getRawDataRefImpl());
1026 }
1027
1028 const coff_relocation *
1029 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1030   return toRel(Reloc.getRawDataRefImpl());
1031 }
1032
1033 iterator_range<const coff_relocation *>
1034 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1035   const coff_relocation *I = getFirstReloc(Sec, Data, base());
1036   const coff_relocation *E = I;
1037   if (I)
1038     E += getNumberOfRelocations(Sec, Data, base());
1039   return make_range(I, E);
1040 }
1041
1042 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
1043   case COFF::reloc_type:                                                       \
1044     Res = #reloc_type;                                                         \
1045     break;
1046
1047 std::error_code
1048 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
1049                                       SmallVectorImpl<char> &Result) const {
1050   const coff_relocation *Reloc = toRel(Rel);
1051   StringRef Res;
1052   switch (getMachine()) {
1053   case COFF::IMAGE_FILE_MACHINE_AMD64:
1054     switch (Reloc->Type) {
1055     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1056     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1057     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1058     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1059     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1060     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1061     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1062     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1063     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1064     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1065     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1066     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1067     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1068     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1069     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1070     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1071     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1072     default:
1073       Res = "Unknown";
1074     }
1075     break;
1076   case COFF::IMAGE_FILE_MACHINE_ARMNT:
1077     switch (Reloc->Type) {
1078     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1079     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1080     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1081     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1082     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1083     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1084     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1085     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1086     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1087     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1088     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1089     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1090     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1091     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1092     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1093     default:
1094       Res = "Unknown";
1095     }
1096     break;
1097   case COFF::IMAGE_FILE_MACHINE_I386:
1098     switch (Reloc->Type) {
1099     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1100     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1101     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1102     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1103     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1104     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1105     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1106     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1107     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1108     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1109     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1110     default:
1111       Res = "Unknown";
1112     }
1113     break;
1114   default:
1115     Res = "Unknown";
1116   }
1117   Result.append(Res.begin(), Res.end());
1118   return std::error_code();
1119 }
1120
1121 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1122
1123 bool COFFObjectFile::isRelocatableObject() const {
1124   return !DataDirectory;
1125 }
1126
1127 bool ImportDirectoryEntryRef::
1128 operator==(const ImportDirectoryEntryRef &Other) const {
1129   return ImportTable == Other.ImportTable && Index == Other.Index;
1130 }
1131
1132 void ImportDirectoryEntryRef::moveNext() {
1133   ++Index;
1134 }
1135
1136 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1137     const import_directory_table_entry *&Result) const {
1138   Result = ImportTable + Index;
1139   return std::error_code();
1140 }
1141
1142 static imported_symbol_iterator
1143 makeImportedSymbolIterator(const COFFObjectFile *Object,
1144                            uintptr_t Ptr, int Index) {
1145   if (Object->getBytesInAddress() == 4) {
1146     auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1147     return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1148   }
1149   auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1150   return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1151 }
1152
1153 static imported_symbol_iterator
1154 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1155   uintptr_t IntPtr = 0;
1156   Object->getRvaPtr(RVA, IntPtr);
1157   return makeImportedSymbolIterator(Object, IntPtr, 0);
1158 }
1159
1160 static imported_symbol_iterator
1161 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1162   uintptr_t IntPtr = 0;
1163   Object->getRvaPtr(RVA, IntPtr);
1164   // Forward the pointer to the last entry which is null.
1165   int Index = 0;
1166   if (Object->getBytesInAddress() == 4) {
1167     auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1168     while (*Entry++)
1169       ++Index;
1170   } else {
1171     auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1172     while (*Entry++)
1173       ++Index;
1174   }
1175   return makeImportedSymbolIterator(Object, IntPtr, Index);
1176 }
1177
1178 imported_symbol_iterator
1179 ImportDirectoryEntryRef::imported_symbol_begin() const {
1180   return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1181                              OwningObject);
1182 }
1183
1184 imported_symbol_iterator
1185 ImportDirectoryEntryRef::imported_symbol_end() const {
1186   return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1187                            OwningObject);
1188 }
1189
1190 iterator_range<imported_symbol_iterator>
1191 ImportDirectoryEntryRef::imported_symbols() const {
1192   return make_range(imported_symbol_begin(), imported_symbol_end());
1193 }
1194
1195 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1196   uintptr_t IntPtr = 0;
1197   if (std::error_code EC =
1198           OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1199     return EC;
1200   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1201   return std::error_code();
1202 }
1203
1204 std::error_code
1205 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t  &Result) const {
1206   Result = ImportTable[Index].ImportLookupTableRVA;
1207   return std::error_code();
1208 }
1209
1210 std::error_code
1211 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1212   Result = ImportTable[Index].ImportAddressTableRVA;
1213   return std::error_code();
1214 }
1215
1216 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1217     const import_lookup_table_entry32 *&Result) const {
1218   uintptr_t IntPtr = 0;
1219   uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1220   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1221     return EC;
1222   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1223   return std::error_code();
1224 }
1225
1226 bool DelayImportDirectoryEntryRef::
1227 operator==(const DelayImportDirectoryEntryRef &Other) const {
1228   return Table == Other.Table && Index == Other.Index;
1229 }
1230
1231 void DelayImportDirectoryEntryRef::moveNext() {
1232   ++Index;
1233 }
1234
1235 imported_symbol_iterator
1236 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1237   return importedSymbolBegin(Table[Index].DelayImportNameTable,
1238                              OwningObject);
1239 }
1240
1241 imported_symbol_iterator
1242 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1243   return importedSymbolEnd(Table[Index].DelayImportNameTable,
1244                            OwningObject);
1245 }
1246
1247 iterator_range<imported_symbol_iterator>
1248 DelayImportDirectoryEntryRef::imported_symbols() const {
1249   return make_range(imported_symbol_begin(), imported_symbol_end());
1250 }
1251
1252 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1253   uintptr_t IntPtr = 0;
1254   if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1255     return EC;
1256   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1257   return std::error_code();
1258 }
1259
1260 std::error_code DelayImportDirectoryEntryRef::
1261 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1262   Result = Table;
1263   return std::error_code();
1264 }
1265
1266 std::error_code DelayImportDirectoryEntryRef::
1267 getImportAddress(int AddrIndex, uint64_t &Result) const {
1268   uint32_t RVA = Table[Index].DelayImportAddressTable +
1269       AddrIndex * (OwningObject->is64() ? 8 : 4);
1270   uintptr_t IntPtr = 0;
1271   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1272     return EC;
1273   if (OwningObject->is64())
1274     Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1275   else
1276     Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1277   return std::error_code();
1278 }
1279
1280 bool ExportDirectoryEntryRef::
1281 operator==(const ExportDirectoryEntryRef &Other) const {
1282   return ExportTable == Other.ExportTable && Index == Other.Index;
1283 }
1284
1285 void ExportDirectoryEntryRef::moveNext() {
1286   ++Index;
1287 }
1288
1289 // Returns the name of the current export symbol. If the symbol is exported only
1290 // by ordinal, the empty string is set as a result.
1291 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1292   uintptr_t IntPtr = 0;
1293   if (std::error_code EC =
1294           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1295     return EC;
1296   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1297   return std::error_code();
1298 }
1299
1300 // Returns the starting ordinal number.
1301 std::error_code
1302 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1303   Result = ExportTable->OrdinalBase;
1304   return std::error_code();
1305 }
1306
1307 // Returns the export ordinal of the current export symbol.
1308 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1309   Result = ExportTable->OrdinalBase + Index;
1310   return std::error_code();
1311 }
1312
1313 // Returns the address of the current export symbol.
1314 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1315   uintptr_t IntPtr = 0;
1316   if (std::error_code EC =
1317           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1318     return EC;
1319   const export_address_table_entry *entry =
1320       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1321   Result = entry[Index].ExportRVA;
1322   return std::error_code();
1323 }
1324
1325 // Returns the name of the current export symbol. If the symbol is exported only
1326 // by ordinal, the empty string is set as a result.
1327 std::error_code
1328 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1329   uintptr_t IntPtr = 0;
1330   if (std::error_code EC =
1331           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1332     return EC;
1333   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1334
1335   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1336   int Offset = 0;
1337   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1338        I < E; ++I, ++Offset) {
1339     if (*I != Index)
1340       continue;
1341     if (std::error_code EC =
1342             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1343       return EC;
1344     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1345     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1346       return EC;
1347     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1348     return std::error_code();
1349   }
1350   Result = "";
1351   return std::error_code();
1352 }
1353
1354 bool ImportedSymbolRef::
1355 operator==(const ImportedSymbolRef &Other) const {
1356   return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1357       && Index == Other.Index;
1358 }
1359
1360 void ImportedSymbolRef::moveNext() {
1361   ++Index;
1362 }
1363
1364 std::error_code
1365 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1366   uint32_t RVA;
1367   if (Entry32) {
1368     // If a symbol is imported only by ordinal, it has no name.
1369     if (Entry32[Index].isOrdinal())
1370       return std::error_code();
1371     RVA = Entry32[Index].getHintNameRVA();
1372   } else {
1373     if (Entry64[Index].isOrdinal())
1374       return std::error_code();
1375     RVA = Entry64[Index].getHintNameRVA();
1376   }
1377   uintptr_t IntPtr = 0;
1378   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1379     return EC;
1380   // +2 because the first two bytes is hint.
1381   Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1382   return std::error_code();
1383 }
1384
1385 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1386   uint32_t RVA;
1387   if (Entry32) {
1388     if (Entry32[Index].isOrdinal()) {
1389       Result = Entry32[Index].getOrdinal();
1390       return std::error_code();
1391     }
1392     RVA = Entry32[Index].getHintNameRVA();
1393   } else {
1394     if (Entry64[Index].isOrdinal()) {
1395       Result = Entry64[Index].getOrdinal();
1396       return std::error_code();
1397     }
1398     RVA = Entry64[Index].getHintNameRVA();
1399   }
1400   uintptr_t IntPtr = 0;
1401   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1402     return EC;
1403   Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1404   return std::error_code();
1405 }
1406
1407 ErrorOr<std::unique_ptr<COFFObjectFile>>
1408 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1409   std::error_code EC;
1410   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1411   if (EC)
1412     return EC;
1413   return std::move(Ret);
1414 }
1415
1416 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1417   return Header == Other.Header && Index == Other.Index;
1418 }
1419
1420 void BaseRelocRef::moveNext() {
1421   // Header->BlockSize is the size of the current block, including the
1422   // size of the header itself.
1423   uint32_t Size = sizeof(*Header) +
1424       sizeof(coff_base_reloc_block_entry) * (Index + 1);
1425   if (Size == Header->BlockSize) {
1426     // .reloc contains a list of base relocation blocks. Each block
1427     // consists of the header followed by entries. The header contains
1428     // how many entories will follow. When we reach the end of the
1429     // current block, proceed to the next block.
1430     Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1431         reinterpret_cast<const uint8_t *>(Header) + Size);
1432     Index = 0;
1433   } else {
1434     ++Index;
1435   }
1436 }
1437
1438 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1439   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1440   Type = Entry[Index].getType();
1441   return std::error_code();
1442 }
1443
1444 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1445   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1446   Result = Header->PageRVA + Entry[Index].getOffset();
1447   return std::error_code();
1448 }