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