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