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