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