xref: /llvm-project/llvm/lib/Object/COFFObjectFile.cpp (revision ac8cfab51fe45b1b69931b50a1c91ac408a3ea63)
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 Expected<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 errorCodeToError(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 std::error_code
457 COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
458                                      ArrayRef<uint8_t> &Contents) const {
459   for (const SectionRef &S : sections()) {
460     const coff_section *Section = getCOFFSection(S);
461     uint32_t SectionStart = Section->VirtualAddress;
462     // Check if this RVA is within the section bounds. Be careful about integer
463     // overflow.
464     uint32_t OffsetIntoSection = RVA - SectionStart;
465     if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize &&
466         Size <= Section->VirtualSize - OffsetIntoSection) {
467       uintptr_t Begin =
468           uintptr_t(base()) + Section->PointerToRawData + OffsetIntoSection;
469       Contents =
470           ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size);
471       return std::error_code();
472     }
473   }
474   return object_error::parse_failed;
475 }
476 
477 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
478 // table entry.
479 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
480                                             StringRef &Name) const {
481   uintptr_t IntPtr = 0;
482   if (std::error_code EC = getRvaPtr(Rva, IntPtr))
483     return EC;
484   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
485   Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
486   Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
487   return std::error_code();
488 }
489 
490 std::error_code
491 COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir,
492                                 const codeview::DebugInfo *&PDBInfo,
493                                 StringRef &PDBFileName) const {
494   ArrayRef<uint8_t> InfoBytes;
495   if (std::error_code EC = getRvaAndSizeAsBytes(
496           DebugDir->AddressOfRawData, DebugDir->SizeOfData, InfoBytes))
497     return EC;
498   if (InfoBytes.size() < sizeof(*PDBInfo) + 1)
499     return object_error::parse_failed;
500   PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data());
501   InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo));
502   PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()),
503                           InfoBytes.size());
504   // Truncate the name at the first null byte. Ignore any padding.
505   PDBFileName = PDBFileName.split('\0').first;
506   return std::error_code();
507 }
508 
509 std::error_code
510 COFFObjectFile::getDebugPDBInfo(const codeview::DebugInfo *&PDBInfo,
511                                 StringRef &PDBFileName) const {
512   for (const debug_directory &D : debug_directories())
513     if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW)
514       return getDebugPDBInfo(&D, PDBInfo, PDBFileName);
515   // If we get here, there is no PDB info to return.
516   PDBInfo = nullptr;
517   PDBFileName = StringRef();
518   return std::error_code();
519 }
520 
521 // Find the import table.
522 std::error_code COFFObjectFile::initImportTablePtr() {
523   // First, we get the RVA of the import table. If the file lacks a pointer to
524   // the import table, do nothing.
525   const data_directory *DataEntry;
526   if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
527     return std::error_code();
528 
529   // Do nothing if the pointer to import table is NULL.
530   if (DataEntry->RelativeVirtualAddress == 0)
531     return std::error_code();
532 
533   uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
534 
535   // Find the section that contains the RVA. This is needed because the RVA is
536   // the import table's memory address which is different from its file offset.
537   uintptr_t IntPtr = 0;
538   if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
539     return EC;
540   if (std::error_code EC = checkOffset(Data, IntPtr, DataEntry->Size))
541     return EC;
542   ImportDirectory = reinterpret_cast<
543       const coff_import_directory_table_entry *>(IntPtr);
544   return std::error_code();
545 }
546 
547 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
548 std::error_code COFFObjectFile::initDelayImportTablePtr() {
549   const data_directory *DataEntry;
550   if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
551     return std::error_code();
552   if (DataEntry->RelativeVirtualAddress == 0)
553     return std::error_code();
554 
555   uint32_t RVA = DataEntry->RelativeVirtualAddress;
556   NumberOfDelayImportDirectory = DataEntry->Size /
557       sizeof(delay_import_directory_table_entry) - 1;
558 
559   uintptr_t IntPtr = 0;
560   if (std::error_code EC = getRvaPtr(RVA, IntPtr))
561     return EC;
562   DelayImportDirectory = reinterpret_cast<
563       const delay_import_directory_table_entry *>(IntPtr);
564   return std::error_code();
565 }
566 
567 // Find the export table.
568 std::error_code COFFObjectFile::initExportTablePtr() {
569   // First, we get the RVA of the export table. If the file lacks a pointer to
570   // the export table, do nothing.
571   const data_directory *DataEntry;
572   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
573     return std::error_code();
574 
575   // Do nothing if the pointer to export table is NULL.
576   if (DataEntry->RelativeVirtualAddress == 0)
577     return std::error_code();
578 
579   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
580   uintptr_t IntPtr = 0;
581   if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
582     return EC;
583   ExportDirectory =
584       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
585   return std::error_code();
586 }
587 
588 std::error_code COFFObjectFile::initBaseRelocPtr() {
589   const data_directory *DataEntry;
590   if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
591     return std::error_code();
592   if (DataEntry->RelativeVirtualAddress == 0)
593     return std::error_code();
594 
595   uintptr_t IntPtr = 0;
596   if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
597     return EC;
598   BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
599       IntPtr);
600   BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
601       IntPtr + DataEntry->Size);
602   return std::error_code();
603 }
604 
605 std::error_code COFFObjectFile::initDebugDirectoryPtr() {
606   // Get the RVA of the debug directory. Do nothing if it does not exist.
607   const data_directory *DataEntry;
608   if (getDataDirectory(COFF::DEBUG_DIRECTORY, DataEntry))
609     return std::error_code();
610 
611   // Do nothing if the RVA is NULL.
612   if (DataEntry->RelativeVirtualAddress == 0)
613     return std::error_code();
614 
615   // Check that the size is a multiple of the entry size.
616   if (DataEntry->Size % sizeof(debug_directory) != 0)
617     return object_error::parse_failed;
618 
619   uintptr_t IntPtr = 0;
620   if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
621     return EC;
622   DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
623   if (std::error_code EC = getRvaPtr(
624           DataEntry->RelativeVirtualAddress + DataEntry->Size, IntPtr))
625     return EC;
626   DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(IntPtr);
627   return std::error_code();
628 }
629 
630 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
631     : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
632       COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
633       DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
634       SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
635       ImportDirectory(nullptr),
636       DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
637       ExportDirectory(nullptr), BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
638       DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr) {
639   // Check that we at least have enough room for a header.
640   if (!checkSize(Data, EC, sizeof(coff_file_header)))
641     return;
642 
643   // The current location in the file where we are looking at.
644   uint64_t CurPtr = 0;
645 
646   // PE header is optional and is present only in executables. If it exists,
647   // it is placed right after COFF header.
648   bool HasPEHeader = false;
649 
650   // Check if this is a PE/COFF file.
651   if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
652     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
653     // PE signature to find 'normal' COFF header.
654     const auto *DH = reinterpret_cast<const dos_header *>(base());
655     if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
656       CurPtr = DH->AddressOfNewExeHeader;
657       // Check the PE magic bytes. ("PE\0\0")
658       if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
659         EC = object_error::parse_failed;
660         return;
661       }
662       CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
663       HasPEHeader = true;
664     }
665   }
666 
667   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
668     return;
669 
670   // It might be a bigobj file, let's check.  Note that COFF bigobj and COFF
671   // import libraries share a common prefix but bigobj is more restrictive.
672   if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
673       COFFHeader->NumberOfSections == uint16_t(0xffff) &&
674       checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
675     if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
676       return;
677 
678     // Verify that we are dealing with bigobj.
679     if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
680         std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
681                     sizeof(COFF::BigObjMagic)) == 0) {
682       COFFHeader = nullptr;
683       CurPtr += sizeof(coff_bigobj_file_header);
684     } else {
685       // It's not a bigobj.
686       COFFBigObjHeader = nullptr;
687     }
688   }
689   if (COFFHeader) {
690     // The prior checkSize call may have failed.  This isn't a hard error
691     // because we were just trying to sniff out bigobj.
692     EC = std::error_code();
693     CurPtr += sizeof(coff_file_header);
694 
695     if (COFFHeader->isImportLibrary())
696       return;
697   }
698 
699   if (HasPEHeader) {
700     const pe32_header *Header;
701     if ((EC = getObject(Header, Data, base() + CurPtr)))
702       return;
703 
704     const uint8_t *DataDirAddr;
705     uint64_t DataDirSize;
706     if (Header->Magic == COFF::PE32Header::PE32) {
707       PE32Header = Header;
708       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
709       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
710     } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
711       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
712       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
713       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
714     } else {
715       // It's neither PE32 nor PE32+.
716       EC = object_error::parse_failed;
717       return;
718     }
719     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
720       return;
721   }
722 
723   if (COFFHeader)
724     CurPtr += COFFHeader->SizeOfOptionalHeader;
725 
726   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
727                       (uint64_t)getNumberOfSections() * sizeof(coff_section))))
728     return;
729 
730   // Initialize the pointer to the symbol table.
731   if (getPointerToSymbolTable() != 0) {
732     if ((EC = initSymbolTablePtr())) {
733       SymbolTable16 = nullptr;
734       SymbolTable32 = nullptr;
735       StringTable = nullptr;
736       StringTableSize = 0;
737     }
738   } else {
739     // We had better not have any symbols if we don't have a symbol table.
740     if (getNumberOfSymbols() != 0) {
741       EC = object_error::parse_failed;
742       return;
743     }
744   }
745 
746   // Initialize the pointer to the beginning of the import table.
747   if ((EC = initImportTablePtr()))
748     return;
749   if ((EC = initDelayImportTablePtr()))
750     return;
751 
752   // Initialize the pointer to the export table.
753   if ((EC = initExportTablePtr()))
754     return;
755 
756   // Initialize the pointer to the base relocation table.
757   if ((EC = initBaseRelocPtr()))
758     return;
759 
760   // Initialize the pointer to the export table.
761   if ((EC = initDebugDirectoryPtr()))
762     return;
763 
764   EC = std::error_code();
765 }
766 
767 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
768   DataRefImpl Ret;
769   Ret.p = getSymbolTable();
770   return basic_symbol_iterator(SymbolRef(Ret, this));
771 }
772 
773 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
774   // The symbol table ends where the string table begins.
775   DataRefImpl Ret;
776   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
777   return basic_symbol_iterator(SymbolRef(Ret, this));
778 }
779 
780 import_directory_iterator COFFObjectFile::import_directory_begin() const {
781   if (!ImportDirectory)
782     return import_directory_end();
783   if (ImportDirectory->isNull())
784     return import_directory_end();
785   return import_directory_iterator(
786       ImportDirectoryEntryRef(ImportDirectory, 0, this));
787 }
788 
789 import_directory_iterator COFFObjectFile::import_directory_end() const {
790   return import_directory_iterator(
791       ImportDirectoryEntryRef(nullptr, -1, this));
792 }
793 
794 delay_import_directory_iterator
795 COFFObjectFile::delay_import_directory_begin() const {
796   return delay_import_directory_iterator(
797       DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
798 }
799 
800 delay_import_directory_iterator
801 COFFObjectFile::delay_import_directory_end() const {
802   return delay_import_directory_iterator(
803       DelayImportDirectoryEntryRef(
804           DelayImportDirectory, NumberOfDelayImportDirectory, this));
805 }
806 
807 export_directory_iterator COFFObjectFile::export_directory_begin() const {
808   return export_directory_iterator(
809       ExportDirectoryEntryRef(ExportDirectory, 0, this));
810 }
811 
812 export_directory_iterator COFFObjectFile::export_directory_end() const {
813   if (!ExportDirectory)
814     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
815   ExportDirectoryEntryRef Ref(ExportDirectory,
816                               ExportDirectory->AddressTableEntries, this);
817   return export_directory_iterator(Ref);
818 }
819 
820 section_iterator COFFObjectFile::section_begin() const {
821   DataRefImpl Ret;
822   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
823   return section_iterator(SectionRef(Ret, this));
824 }
825 
826 section_iterator COFFObjectFile::section_end() const {
827   DataRefImpl Ret;
828   int NumSections =
829       COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
830   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
831   return section_iterator(SectionRef(Ret, this));
832 }
833 
834 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
835   return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
836 }
837 
838 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
839   return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
840 }
841 
842 uint8_t COFFObjectFile::getBytesInAddress() const {
843   return getArch() == Triple::x86_64 ? 8 : 4;
844 }
845 
846 StringRef COFFObjectFile::getFileFormatName() const {
847   switch(getMachine()) {
848   case COFF::IMAGE_FILE_MACHINE_I386:
849     return "COFF-i386";
850   case COFF::IMAGE_FILE_MACHINE_AMD64:
851     return "COFF-x86-64";
852   case COFF::IMAGE_FILE_MACHINE_ARMNT:
853     return "COFF-ARM";
854   case COFF::IMAGE_FILE_MACHINE_ARM64:
855     return "COFF-ARM64";
856   default:
857     return "COFF-<unknown arch>";
858   }
859 }
860 
861 unsigned COFFObjectFile::getArch() const {
862   switch (getMachine()) {
863   case COFF::IMAGE_FILE_MACHINE_I386:
864     return Triple::x86;
865   case COFF::IMAGE_FILE_MACHINE_AMD64:
866     return Triple::x86_64;
867   case COFF::IMAGE_FILE_MACHINE_ARMNT:
868     return Triple::thumb;
869   case COFF::IMAGE_FILE_MACHINE_ARM64:
870     return Triple::aarch64;
871   default:
872     return Triple::UnknownArch;
873   }
874 }
875 
876 iterator_range<import_directory_iterator>
877 COFFObjectFile::import_directories() const {
878   return make_range(import_directory_begin(), import_directory_end());
879 }
880 
881 iterator_range<delay_import_directory_iterator>
882 COFFObjectFile::delay_import_directories() const {
883   return make_range(delay_import_directory_begin(),
884                     delay_import_directory_end());
885 }
886 
887 iterator_range<export_directory_iterator>
888 COFFObjectFile::export_directories() const {
889   return make_range(export_directory_begin(), export_directory_end());
890 }
891 
892 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
893   return make_range(base_reloc_begin(), base_reloc_end());
894 }
895 
896 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
897   Res = PE32Header;
898   return std::error_code();
899 }
900 
901 std::error_code
902 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
903   Res = PE32PlusHeader;
904   return std::error_code();
905 }
906 
907 std::error_code
908 COFFObjectFile::getDataDirectory(uint32_t Index,
909                                  const data_directory *&Res) const {
910   // Error if if there's no data directory or the index is out of range.
911   if (!DataDirectory) {
912     Res = nullptr;
913     return object_error::parse_failed;
914   }
915   assert(PE32Header || PE32PlusHeader);
916   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
917                                : PE32PlusHeader->NumberOfRvaAndSize;
918   if (Index >= NumEnt) {
919     Res = nullptr;
920     return object_error::parse_failed;
921   }
922   Res = &DataDirectory[Index];
923   return std::error_code();
924 }
925 
926 std::error_code COFFObjectFile::getSection(int32_t Index,
927                                            const coff_section *&Result) const {
928   Result = nullptr;
929   if (COFF::isReservedSectionNumber(Index))
930     return std::error_code();
931   if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
932     // We already verified the section table data, so no need to check again.
933     Result = SectionTable + (Index - 1);
934     return std::error_code();
935   }
936   return object_error::parse_failed;
937 }
938 
939 std::error_code COFFObjectFile::getString(uint32_t Offset,
940                                           StringRef &Result) const {
941   if (StringTableSize <= 4)
942     // Tried to get a string from an empty string table.
943     return object_error::parse_failed;
944   if (Offset >= StringTableSize)
945     return object_error::unexpected_eof;
946   Result = StringRef(StringTable + Offset);
947   return std::error_code();
948 }
949 
950 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
951                                               StringRef &Res) const {
952   return getSymbolName(Symbol.getGeneric(), Res);
953 }
954 
955 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
956                                               StringRef &Res) const {
957   // Check for string table entry. First 4 bytes are 0.
958   if (Symbol->Name.Offset.Zeroes == 0) {
959     if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
960       return EC;
961     return std::error_code();
962   }
963 
964   if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
965     // Null terminated, let ::strlen figure out the length.
966     Res = StringRef(Symbol->Name.ShortName);
967   else
968     // Not null terminated, use all 8 bytes.
969     Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
970   return std::error_code();
971 }
972 
973 ArrayRef<uint8_t>
974 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
975   const uint8_t *Aux = nullptr;
976 
977   size_t SymbolSize = getSymbolTableEntrySize();
978   if (Symbol.getNumberOfAuxSymbols() > 0) {
979     // AUX data comes immediately after the symbol in COFF
980     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
981 # ifndef NDEBUG
982     // Verify that the Aux symbol points to a valid entry in the symbol table.
983     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
984     if (Offset < getPointerToSymbolTable() ||
985         Offset >=
986             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
987       report_fatal_error("Aux Symbol data was outside of symbol table.");
988 
989     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
990            "Aux Symbol data did not point to the beginning of a symbol");
991 # endif
992   }
993   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
994 }
995 
996 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
997                                                StringRef &Res) const {
998   StringRef Name;
999   if (Sec->Name[COFF::NameSize - 1] == 0)
1000     // Null terminated, let ::strlen figure out the length.
1001     Name = Sec->Name;
1002   else
1003     // Not null terminated, use all 8 bytes.
1004     Name = StringRef(Sec->Name, COFF::NameSize);
1005 
1006   // Check for string table entry. First byte is '/'.
1007   if (Name.startswith("/")) {
1008     uint32_t Offset;
1009     if (Name.startswith("//")) {
1010       if (decodeBase64StringEntry(Name.substr(2), Offset))
1011         return object_error::parse_failed;
1012     } else {
1013       if (Name.substr(1).getAsInteger(10, Offset))
1014         return object_error::parse_failed;
1015     }
1016     if (std::error_code EC = getString(Offset, Name))
1017       return EC;
1018   }
1019 
1020   Res = Name;
1021   return std::error_code();
1022 }
1023 
1024 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
1025   // SizeOfRawData and VirtualSize change what they represent depending on
1026   // whether or not we have an executable image.
1027   //
1028   // For object files, SizeOfRawData contains the size of section's data;
1029   // VirtualSize should be zero but isn't due to buggy COFF writers.
1030   //
1031   // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1032   // actual section size is in VirtualSize.  It is possible for VirtualSize to
1033   // be greater than SizeOfRawData; the contents past that point should be
1034   // considered to be zero.
1035   if (getDOSHeader())
1036     return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1037   return Sec->SizeOfRawData;
1038 }
1039 
1040 std::error_code
1041 COFFObjectFile::getSectionContents(const coff_section *Sec,
1042                                    ArrayRef<uint8_t> &Res) const {
1043   // In COFF, a virtual section won't have any in-file
1044   // content, so the file pointer to the content will be zero.
1045   if (Sec->PointerToRawData == 0)
1046     return object_error::parse_failed;
1047   // The only thing that we need to verify is that the contents is contained
1048   // within the file bounds. We don't need to make sure it doesn't cover other
1049   // data, as there's nothing that says that is not allowed.
1050   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1051   uint32_t SectionSize = getSectionSize(Sec);
1052   if (checkOffset(Data, ConStart, SectionSize))
1053     return object_error::parse_failed;
1054   Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1055   return std::error_code();
1056 }
1057 
1058 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1059   return reinterpret_cast<const coff_relocation*>(Rel.p);
1060 }
1061 
1062 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1063   Rel.p = reinterpret_cast<uintptr_t>(
1064             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1065 }
1066 
1067 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1068   const coff_relocation *R = toRel(Rel);
1069   return R->VirtualAddress;
1070 }
1071 
1072 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1073   const coff_relocation *R = toRel(Rel);
1074   DataRefImpl Ref;
1075   if (R->SymbolTableIndex >= getNumberOfSymbols())
1076     return symbol_end();
1077   if (SymbolTable16)
1078     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1079   else if (SymbolTable32)
1080     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1081   else
1082     llvm_unreachable("no symbol table pointer!");
1083   return symbol_iterator(SymbolRef(Ref, this));
1084 }
1085 
1086 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
1087   const coff_relocation* R = toRel(Rel);
1088   return R->Type;
1089 }
1090 
1091 const coff_section *
1092 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1093   return toSec(Section.getRawDataRefImpl());
1094 }
1095 
1096 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1097   if (SymbolTable16)
1098     return toSymb<coff_symbol16>(Ref);
1099   if (SymbolTable32)
1100     return toSymb<coff_symbol32>(Ref);
1101   llvm_unreachable("no symbol table pointer!");
1102 }
1103 
1104 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1105   return getCOFFSymbol(Symbol.getRawDataRefImpl());
1106 }
1107 
1108 const coff_relocation *
1109 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1110   return toRel(Reloc.getRawDataRefImpl());
1111 }
1112 
1113 iterator_range<const coff_relocation *>
1114 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1115   const coff_relocation *I = getFirstReloc(Sec, Data, base());
1116   const coff_relocation *E = I;
1117   if (I)
1118     E += getNumberOfRelocations(Sec, Data, base());
1119   return make_range(I, E);
1120 }
1121 
1122 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
1123   case COFF::reloc_type:                                                       \
1124     Res = #reloc_type;                                                         \
1125     break;
1126 
1127 void COFFObjectFile::getRelocationTypeName(
1128     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1129   const coff_relocation *Reloc = toRel(Rel);
1130   StringRef Res;
1131   switch (getMachine()) {
1132   case COFF::IMAGE_FILE_MACHINE_AMD64:
1133     switch (Reloc->Type) {
1134     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1135     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1136     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1137     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1138     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1139     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1140     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1141     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1142     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1143     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1144     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1145     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1146     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1147     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1148     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1149     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1150     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1151     default:
1152       Res = "Unknown";
1153     }
1154     break;
1155   case COFF::IMAGE_FILE_MACHINE_ARMNT:
1156     switch (Reloc->Type) {
1157     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1158     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1159     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1160     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1161     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1162     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1163     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1164     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1165     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1166     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1167     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1168     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1169     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1170     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1171     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1172     default:
1173       Res = "Unknown";
1174     }
1175     break;
1176   case COFF::IMAGE_FILE_MACHINE_I386:
1177     switch (Reloc->Type) {
1178     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1179     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1180     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1181     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1182     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1183     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1184     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1185     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1186     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1187     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1188     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1189     default:
1190       Res = "Unknown";
1191     }
1192     break;
1193   default:
1194     Res = "Unknown";
1195   }
1196   Result.append(Res.begin(), Res.end());
1197 }
1198 
1199 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1200 
1201 bool COFFObjectFile::isRelocatableObject() const {
1202   return !DataDirectory;
1203 }
1204 
1205 bool ImportDirectoryEntryRef::
1206 operator==(const ImportDirectoryEntryRef &Other) const {
1207   return ImportTable == Other.ImportTable && Index == Other.Index;
1208 }
1209 
1210 void ImportDirectoryEntryRef::moveNext() {
1211   ++Index;
1212   if (ImportTable[Index].isNull()) {
1213     Index = -1;
1214     ImportTable = nullptr;
1215   }
1216 }
1217 
1218 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1219     const coff_import_directory_table_entry *&Result) const {
1220   return getObject(Result, OwningObject->Data, ImportTable + Index);
1221 }
1222 
1223 static imported_symbol_iterator
1224 makeImportedSymbolIterator(const COFFObjectFile *Object,
1225                            uintptr_t Ptr, int Index) {
1226   if (Object->getBytesInAddress() == 4) {
1227     auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1228     return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1229   }
1230   auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1231   return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1232 }
1233 
1234 static imported_symbol_iterator
1235 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1236   uintptr_t IntPtr = 0;
1237   Object->getRvaPtr(RVA, IntPtr);
1238   return makeImportedSymbolIterator(Object, IntPtr, 0);
1239 }
1240 
1241 static imported_symbol_iterator
1242 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1243   uintptr_t IntPtr = 0;
1244   Object->getRvaPtr(RVA, IntPtr);
1245   // Forward the pointer to the last entry which is null.
1246   int Index = 0;
1247   if (Object->getBytesInAddress() == 4) {
1248     auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1249     while (*Entry++)
1250       ++Index;
1251   } else {
1252     auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1253     while (*Entry++)
1254       ++Index;
1255   }
1256   return makeImportedSymbolIterator(Object, IntPtr, Index);
1257 }
1258 
1259 imported_symbol_iterator
1260 ImportDirectoryEntryRef::imported_symbol_begin() const {
1261   return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
1262                              OwningObject);
1263 }
1264 
1265 imported_symbol_iterator
1266 ImportDirectoryEntryRef::imported_symbol_end() const {
1267   return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
1268                            OwningObject);
1269 }
1270 
1271 iterator_range<imported_symbol_iterator>
1272 ImportDirectoryEntryRef::imported_symbols() const {
1273   return make_range(imported_symbol_begin(), imported_symbol_end());
1274 }
1275 
1276 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
1277   return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1278                              OwningObject);
1279 }
1280 
1281 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
1282   return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1283                            OwningObject);
1284 }
1285 
1286 iterator_range<imported_symbol_iterator>
1287 ImportDirectoryEntryRef::lookup_table_symbols() const {
1288   return make_range(lookup_table_begin(), lookup_table_end());
1289 }
1290 
1291 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1292   uintptr_t IntPtr = 0;
1293   if (std::error_code EC =
1294           OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1295     return EC;
1296   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1297   return std::error_code();
1298 }
1299 
1300 std::error_code
1301 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t  &Result) const {
1302   Result = ImportTable[Index].ImportLookupTableRVA;
1303   return std::error_code();
1304 }
1305 
1306 std::error_code
1307 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1308   Result = ImportTable[Index].ImportAddressTableRVA;
1309   return std::error_code();
1310 }
1311 
1312 bool DelayImportDirectoryEntryRef::
1313 operator==(const DelayImportDirectoryEntryRef &Other) const {
1314   return Table == Other.Table && Index == Other.Index;
1315 }
1316 
1317 void DelayImportDirectoryEntryRef::moveNext() {
1318   ++Index;
1319 }
1320 
1321 imported_symbol_iterator
1322 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1323   return importedSymbolBegin(Table[Index].DelayImportNameTable,
1324                              OwningObject);
1325 }
1326 
1327 imported_symbol_iterator
1328 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1329   return importedSymbolEnd(Table[Index].DelayImportNameTable,
1330                            OwningObject);
1331 }
1332 
1333 iterator_range<imported_symbol_iterator>
1334 DelayImportDirectoryEntryRef::imported_symbols() const {
1335   return make_range(imported_symbol_begin(), imported_symbol_end());
1336 }
1337 
1338 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1339   uintptr_t IntPtr = 0;
1340   if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1341     return EC;
1342   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1343   return std::error_code();
1344 }
1345 
1346 std::error_code DelayImportDirectoryEntryRef::
1347 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1348   Result = Table;
1349   return std::error_code();
1350 }
1351 
1352 std::error_code DelayImportDirectoryEntryRef::
1353 getImportAddress(int AddrIndex, uint64_t &Result) const {
1354   uint32_t RVA = Table[Index].DelayImportAddressTable +
1355       AddrIndex * (OwningObject->is64() ? 8 : 4);
1356   uintptr_t IntPtr = 0;
1357   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1358     return EC;
1359   if (OwningObject->is64())
1360     Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1361   else
1362     Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1363   return std::error_code();
1364 }
1365 
1366 bool ExportDirectoryEntryRef::
1367 operator==(const ExportDirectoryEntryRef &Other) const {
1368   return ExportTable == Other.ExportTable && Index == Other.Index;
1369 }
1370 
1371 void ExportDirectoryEntryRef::moveNext() {
1372   ++Index;
1373 }
1374 
1375 // Returns the name of the current export symbol. If the symbol is exported only
1376 // by ordinal, the empty string is set as a result.
1377 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1378   uintptr_t IntPtr = 0;
1379   if (std::error_code EC =
1380           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1381     return EC;
1382   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1383   return std::error_code();
1384 }
1385 
1386 // Returns the starting ordinal number.
1387 std::error_code
1388 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1389   Result = ExportTable->OrdinalBase;
1390   return std::error_code();
1391 }
1392 
1393 // Returns the export ordinal of the current export symbol.
1394 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1395   Result = ExportTable->OrdinalBase + Index;
1396   return std::error_code();
1397 }
1398 
1399 // Returns the address of the current export symbol.
1400 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1401   uintptr_t IntPtr = 0;
1402   if (std::error_code EC =
1403           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1404     return EC;
1405   const export_address_table_entry *entry =
1406       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1407   Result = entry[Index].ExportRVA;
1408   return std::error_code();
1409 }
1410 
1411 // Returns the name of the current export symbol. If the symbol is exported only
1412 // by ordinal, the empty string is set as a result.
1413 std::error_code
1414 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1415   uintptr_t IntPtr = 0;
1416   if (std::error_code EC =
1417           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1418     return EC;
1419   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1420 
1421   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1422   int Offset = 0;
1423   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1424        I < E; ++I, ++Offset) {
1425     if (*I != Index)
1426       continue;
1427     if (std::error_code EC =
1428             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1429       return EC;
1430     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1431     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1432       return EC;
1433     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1434     return std::error_code();
1435   }
1436   Result = "";
1437   return std::error_code();
1438 }
1439 
1440 std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1441   const data_directory *DataEntry;
1442   if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
1443     return EC;
1444   uint32_t RVA;
1445   if (auto EC = getExportRVA(RVA))
1446     return EC;
1447   uint32_t Begin = DataEntry->RelativeVirtualAddress;
1448   uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1449   Result = (Begin <= RVA && RVA < End);
1450   return std::error_code();
1451 }
1452 
1453 std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1454   uint32_t RVA;
1455   if (auto EC = getExportRVA(RVA))
1456     return EC;
1457   uintptr_t IntPtr = 0;
1458   if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1459     return EC;
1460   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1461   return std::error_code();
1462 }
1463 
1464 bool ImportedSymbolRef::
1465 operator==(const ImportedSymbolRef &Other) const {
1466   return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1467       && Index == Other.Index;
1468 }
1469 
1470 void ImportedSymbolRef::moveNext() {
1471   ++Index;
1472 }
1473 
1474 std::error_code
1475 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1476   uint32_t RVA;
1477   if (Entry32) {
1478     // If a symbol is imported only by ordinal, it has no name.
1479     if (Entry32[Index].isOrdinal())
1480       return std::error_code();
1481     RVA = Entry32[Index].getHintNameRVA();
1482   } else {
1483     if (Entry64[Index].isOrdinal())
1484       return std::error_code();
1485     RVA = Entry64[Index].getHintNameRVA();
1486   }
1487   uintptr_t IntPtr = 0;
1488   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1489     return EC;
1490   // +2 because the first two bytes is hint.
1491   Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1492   return std::error_code();
1493 }
1494 
1495 std::error_code ImportedSymbolRef::isOrdinal(bool &Result) const {
1496   if (Entry32)
1497     Result = Entry32[Index].isOrdinal();
1498   else
1499     Result = Entry64[Index].isOrdinal();
1500   return std::error_code();
1501 }
1502 
1503 std::error_code ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
1504   if (Entry32)
1505     Result = Entry32[Index].getHintNameRVA();
1506   else
1507     Result = Entry64[Index].getHintNameRVA();
1508   return std::error_code();
1509 }
1510 
1511 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1512   uint32_t RVA;
1513   if (Entry32) {
1514     if (Entry32[Index].isOrdinal()) {
1515       Result = Entry32[Index].getOrdinal();
1516       return std::error_code();
1517     }
1518     RVA = Entry32[Index].getHintNameRVA();
1519   } else {
1520     if (Entry64[Index].isOrdinal()) {
1521       Result = Entry64[Index].getOrdinal();
1522       return std::error_code();
1523     }
1524     RVA = Entry64[Index].getHintNameRVA();
1525   }
1526   uintptr_t IntPtr = 0;
1527   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1528     return EC;
1529   Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1530   return std::error_code();
1531 }
1532 
1533 ErrorOr<std::unique_ptr<COFFObjectFile>>
1534 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1535   std::error_code EC;
1536   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1537   if (EC)
1538     return EC;
1539   return std::move(Ret);
1540 }
1541 
1542 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1543   return Header == Other.Header && Index == Other.Index;
1544 }
1545 
1546 void BaseRelocRef::moveNext() {
1547   // Header->BlockSize is the size of the current block, including the
1548   // size of the header itself.
1549   uint32_t Size = sizeof(*Header) +
1550       sizeof(coff_base_reloc_block_entry) * (Index + 1);
1551   if (Size == Header->BlockSize) {
1552     // .reloc contains a list of base relocation blocks. Each block
1553     // consists of the header followed by entries. The header contains
1554     // how many entories will follow. When we reach the end of the
1555     // current block, proceed to the next block.
1556     Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1557         reinterpret_cast<const uint8_t *>(Header) + Size);
1558     Index = 0;
1559   } else {
1560     ++Index;
1561   }
1562 }
1563 
1564 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1565   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1566   Type = Entry[Index].getType();
1567   return std::error_code();
1568 }
1569 
1570 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1571   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1572   Result = Header->PageRVA + Entry[Index].getOffset();
1573   return std::error_code();
1574 }
1575