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