xref: /llvm-project/llvm/lib/Object/COFFObjectFile.cpp (revision 015280211b091946b5ae33f2e5a056346068fe55)
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     CurPtr += COFFHeader->SizeOfOptionalHeader;
722   }
723 
724   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
725                       (uint64_t)getNumberOfSections() * sizeof(coff_section))))
726     return;
727 
728   // Initialize the pointer to the symbol table.
729   if (getPointerToSymbolTable() != 0) {
730     if ((EC = initSymbolTablePtr()))
731       return;
732   } else {
733     // We had better not have any symbols if we don't have a symbol table.
734     if (getNumberOfSymbols() != 0) {
735       EC = object_error::parse_failed;
736       return;
737     }
738   }
739 
740   // Initialize the pointer to the beginning of the import table.
741   if ((EC = initImportTablePtr()))
742     return;
743   if ((EC = initDelayImportTablePtr()))
744     return;
745 
746   // Initialize the pointer to the export table.
747   if ((EC = initExportTablePtr()))
748     return;
749 
750   // Initialize the pointer to the base relocation table.
751   if ((EC = initBaseRelocPtr()))
752     return;
753 
754   // Initialize the pointer to the export table.
755   if ((EC = initDebugDirectoryPtr()))
756     return;
757 
758   EC = std::error_code();
759 }
760 
761 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
762   DataRefImpl Ret;
763   Ret.p = getSymbolTable();
764   return basic_symbol_iterator(SymbolRef(Ret, this));
765 }
766 
767 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
768   // The symbol table ends where the string table begins.
769   DataRefImpl Ret;
770   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
771   return basic_symbol_iterator(SymbolRef(Ret, this));
772 }
773 
774 import_directory_iterator COFFObjectFile::import_directory_begin() const {
775   if (!ImportDirectory)
776     return import_directory_end();
777   if (ImportDirectory->isNull())
778     return import_directory_end();
779   return import_directory_iterator(
780       ImportDirectoryEntryRef(ImportDirectory, 0, this));
781 }
782 
783 import_directory_iterator COFFObjectFile::import_directory_end() const {
784   return import_directory_iterator(
785       ImportDirectoryEntryRef(nullptr, -1, this));
786 }
787 
788 delay_import_directory_iterator
789 COFFObjectFile::delay_import_directory_begin() const {
790   return delay_import_directory_iterator(
791       DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
792 }
793 
794 delay_import_directory_iterator
795 COFFObjectFile::delay_import_directory_end() const {
796   return delay_import_directory_iterator(
797       DelayImportDirectoryEntryRef(
798           DelayImportDirectory, NumberOfDelayImportDirectory, this));
799 }
800 
801 export_directory_iterator COFFObjectFile::export_directory_begin() const {
802   return export_directory_iterator(
803       ExportDirectoryEntryRef(ExportDirectory, 0, this));
804 }
805 
806 export_directory_iterator COFFObjectFile::export_directory_end() const {
807   if (!ExportDirectory)
808     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
809   ExportDirectoryEntryRef Ref(ExportDirectory,
810                               ExportDirectory->AddressTableEntries, this);
811   return export_directory_iterator(Ref);
812 }
813 
814 section_iterator COFFObjectFile::section_begin() const {
815   DataRefImpl Ret;
816   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
817   return section_iterator(SectionRef(Ret, this));
818 }
819 
820 section_iterator COFFObjectFile::section_end() const {
821   DataRefImpl Ret;
822   int NumSections =
823       COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
824   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
825   return section_iterator(SectionRef(Ret, this));
826 }
827 
828 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
829   return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
830 }
831 
832 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
833   return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
834 }
835 
836 uint8_t COFFObjectFile::getBytesInAddress() const {
837   return getArch() == Triple::x86_64 ? 8 : 4;
838 }
839 
840 StringRef COFFObjectFile::getFileFormatName() const {
841   switch(getMachine()) {
842   case COFF::IMAGE_FILE_MACHINE_I386:
843     return "COFF-i386";
844   case COFF::IMAGE_FILE_MACHINE_AMD64:
845     return "COFF-x86-64";
846   case COFF::IMAGE_FILE_MACHINE_ARMNT:
847     return "COFF-ARM";
848   case COFF::IMAGE_FILE_MACHINE_ARM64:
849     return "COFF-ARM64";
850   default:
851     return "COFF-<unknown arch>";
852   }
853 }
854 
855 unsigned COFFObjectFile::getArch() const {
856   switch (getMachine()) {
857   case COFF::IMAGE_FILE_MACHINE_I386:
858     return Triple::x86;
859   case COFF::IMAGE_FILE_MACHINE_AMD64:
860     return Triple::x86_64;
861   case COFF::IMAGE_FILE_MACHINE_ARMNT:
862     return Triple::thumb;
863   case COFF::IMAGE_FILE_MACHINE_ARM64:
864     return Triple::aarch64;
865   default:
866     return Triple::UnknownArch;
867   }
868 }
869 
870 iterator_range<import_directory_iterator>
871 COFFObjectFile::import_directories() const {
872   return make_range(import_directory_begin(), import_directory_end());
873 }
874 
875 iterator_range<delay_import_directory_iterator>
876 COFFObjectFile::delay_import_directories() const {
877   return make_range(delay_import_directory_begin(),
878                     delay_import_directory_end());
879 }
880 
881 iterator_range<export_directory_iterator>
882 COFFObjectFile::export_directories() const {
883   return make_range(export_directory_begin(), export_directory_end());
884 }
885 
886 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
887   return make_range(base_reloc_begin(), base_reloc_end());
888 }
889 
890 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
891   Res = PE32Header;
892   return std::error_code();
893 }
894 
895 std::error_code
896 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
897   Res = PE32PlusHeader;
898   return std::error_code();
899 }
900 
901 std::error_code
902 COFFObjectFile::getDataDirectory(uint32_t Index,
903                                  const data_directory *&Res) const {
904   // Error if if there's no data directory or the index is out of range.
905   if (!DataDirectory) {
906     Res = nullptr;
907     return object_error::parse_failed;
908   }
909   assert(PE32Header || PE32PlusHeader);
910   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
911                                : PE32PlusHeader->NumberOfRvaAndSize;
912   if (Index >= NumEnt) {
913     Res = nullptr;
914     return object_error::parse_failed;
915   }
916   Res = &DataDirectory[Index];
917   return std::error_code();
918 }
919 
920 std::error_code COFFObjectFile::getSection(int32_t Index,
921                                            const coff_section *&Result) const {
922   Result = nullptr;
923   if (COFF::isReservedSectionNumber(Index))
924     return std::error_code();
925   if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
926     // We already verified the section table data, so no need to check again.
927     Result = SectionTable + (Index - 1);
928     return std::error_code();
929   }
930   return object_error::parse_failed;
931 }
932 
933 std::error_code COFFObjectFile::getString(uint32_t Offset,
934                                           StringRef &Result) const {
935   if (StringTableSize <= 4)
936     // Tried to get a string from an empty string table.
937     return object_error::parse_failed;
938   if (Offset >= StringTableSize)
939     return object_error::unexpected_eof;
940   Result = StringRef(StringTable + Offset);
941   return std::error_code();
942 }
943 
944 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
945                                               StringRef &Res) const {
946   return getSymbolName(Symbol.getGeneric(), Res);
947 }
948 
949 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
950                                               StringRef &Res) const {
951   // Check for string table entry. First 4 bytes are 0.
952   if (Symbol->Name.Offset.Zeroes == 0) {
953     if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
954       return EC;
955     return std::error_code();
956   }
957 
958   if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
959     // Null terminated, let ::strlen figure out the length.
960     Res = StringRef(Symbol->Name.ShortName);
961   else
962     // Not null terminated, use all 8 bytes.
963     Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
964   return std::error_code();
965 }
966 
967 ArrayRef<uint8_t>
968 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
969   const uint8_t *Aux = nullptr;
970 
971   size_t SymbolSize = getSymbolTableEntrySize();
972   if (Symbol.getNumberOfAuxSymbols() > 0) {
973     // AUX data comes immediately after the symbol in COFF
974     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
975 # ifndef NDEBUG
976     // Verify that the Aux symbol points to a valid entry in the symbol table.
977     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
978     if (Offset < getPointerToSymbolTable() ||
979         Offset >=
980             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
981       report_fatal_error("Aux Symbol data was outside of symbol table.");
982 
983     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
984            "Aux Symbol data did not point to the beginning of a symbol");
985 # endif
986   }
987   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
988 }
989 
990 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
991                                                StringRef &Res) const {
992   StringRef Name;
993   if (Sec->Name[COFF::NameSize - 1] == 0)
994     // Null terminated, let ::strlen figure out the length.
995     Name = Sec->Name;
996   else
997     // Not null terminated, use all 8 bytes.
998     Name = StringRef(Sec->Name, COFF::NameSize);
999 
1000   // Check for string table entry. First byte is '/'.
1001   if (Name.startswith("/")) {
1002     uint32_t Offset;
1003     if (Name.startswith("//")) {
1004       if (decodeBase64StringEntry(Name.substr(2), Offset))
1005         return object_error::parse_failed;
1006     } else {
1007       if (Name.substr(1).getAsInteger(10, Offset))
1008         return object_error::parse_failed;
1009     }
1010     if (std::error_code EC = getString(Offset, Name))
1011       return EC;
1012   }
1013 
1014   Res = Name;
1015   return std::error_code();
1016 }
1017 
1018 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
1019   // SizeOfRawData and VirtualSize change what they represent depending on
1020   // whether or not we have an executable image.
1021   //
1022   // For object files, SizeOfRawData contains the size of section's data;
1023   // VirtualSize should be zero but isn't due to buggy COFF writers.
1024   //
1025   // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1026   // actual section size is in VirtualSize.  It is possible for VirtualSize to
1027   // be greater than SizeOfRawData; the contents past that point should be
1028   // considered to be zero.
1029   if (getDOSHeader())
1030     return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1031   return Sec->SizeOfRawData;
1032 }
1033 
1034 std::error_code
1035 COFFObjectFile::getSectionContents(const coff_section *Sec,
1036                                    ArrayRef<uint8_t> &Res) const {
1037   // In COFF, a virtual section won't have any in-file
1038   // content, so the file pointer to the content will be zero.
1039   if (Sec->PointerToRawData == 0)
1040     return object_error::parse_failed;
1041   // The only thing that we need to verify is that the contents is contained
1042   // within the file bounds. We don't need to make sure it doesn't cover other
1043   // data, as there's nothing that says that is not allowed.
1044   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1045   uint32_t SectionSize = getSectionSize(Sec);
1046   if (checkOffset(Data, ConStart, SectionSize))
1047     return object_error::parse_failed;
1048   Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1049   return std::error_code();
1050 }
1051 
1052 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1053   return reinterpret_cast<const coff_relocation*>(Rel.p);
1054 }
1055 
1056 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1057   Rel.p = reinterpret_cast<uintptr_t>(
1058             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1059 }
1060 
1061 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1062   const coff_relocation *R = toRel(Rel);
1063   return R->VirtualAddress;
1064 }
1065 
1066 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1067   const coff_relocation *R = toRel(Rel);
1068   DataRefImpl Ref;
1069   if (R->SymbolTableIndex >= getNumberOfSymbols())
1070     return symbol_end();
1071   if (SymbolTable16)
1072     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1073   else if (SymbolTable32)
1074     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1075   else
1076     llvm_unreachable("no symbol table pointer!");
1077   return symbol_iterator(SymbolRef(Ref, this));
1078 }
1079 
1080 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
1081   const coff_relocation* R = toRel(Rel);
1082   return R->Type;
1083 }
1084 
1085 const coff_section *
1086 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1087   return toSec(Section.getRawDataRefImpl());
1088 }
1089 
1090 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1091   if (SymbolTable16)
1092     return toSymb<coff_symbol16>(Ref);
1093   if (SymbolTable32)
1094     return toSymb<coff_symbol32>(Ref);
1095   llvm_unreachable("no symbol table pointer!");
1096 }
1097 
1098 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1099   return getCOFFSymbol(Symbol.getRawDataRefImpl());
1100 }
1101 
1102 const coff_relocation *
1103 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1104   return toRel(Reloc.getRawDataRefImpl());
1105 }
1106 
1107 iterator_range<const coff_relocation *>
1108 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1109   const coff_relocation *I = getFirstReloc(Sec, Data, base());
1110   const coff_relocation *E = I;
1111   if (I)
1112     E += getNumberOfRelocations(Sec, Data, base());
1113   return make_range(I, E);
1114 }
1115 
1116 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
1117   case COFF::reloc_type:                                                       \
1118     Res = #reloc_type;                                                         \
1119     break;
1120 
1121 void COFFObjectFile::getRelocationTypeName(
1122     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1123   const coff_relocation *Reloc = toRel(Rel);
1124   StringRef Res;
1125   switch (getMachine()) {
1126   case COFF::IMAGE_FILE_MACHINE_AMD64:
1127     switch (Reloc->Type) {
1128     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1129     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1130     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1131     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1132     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1133     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1134     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1135     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1136     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1137     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1138     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1139     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1140     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1141     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1142     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1143     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1144     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1145     default:
1146       Res = "Unknown";
1147     }
1148     break;
1149   case COFF::IMAGE_FILE_MACHINE_ARMNT:
1150     switch (Reloc->Type) {
1151     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1152     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1153     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1154     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1155     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1156     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1157     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1158     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1159     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1160     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1161     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1162     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1163     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1164     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1165     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1166     default:
1167       Res = "Unknown";
1168     }
1169     break;
1170   case COFF::IMAGE_FILE_MACHINE_I386:
1171     switch (Reloc->Type) {
1172     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1173     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1174     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1175     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1176     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1177     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1178     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1179     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1180     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1181     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1182     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1183     default:
1184       Res = "Unknown";
1185     }
1186     break;
1187   default:
1188     Res = "Unknown";
1189   }
1190   Result.append(Res.begin(), Res.end());
1191 }
1192 
1193 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1194 
1195 bool COFFObjectFile::isRelocatableObject() const {
1196   return !DataDirectory;
1197 }
1198 
1199 bool ImportDirectoryEntryRef::
1200 operator==(const ImportDirectoryEntryRef &Other) const {
1201   return ImportTable == Other.ImportTable && Index == Other.Index;
1202 }
1203 
1204 void ImportDirectoryEntryRef::moveNext() {
1205   ++Index;
1206   if (ImportTable[Index].isNull()) {
1207     Index = -1;
1208     ImportTable = nullptr;
1209   }
1210 }
1211 
1212 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1213     const coff_import_directory_table_entry *&Result) const {
1214   return getObject(Result, OwningObject->Data, ImportTable + Index);
1215 }
1216 
1217 static imported_symbol_iterator
1218 makeImportedSymbolIterator(const COFFObjectFile *Object,
1219                            uintptr_t Ptr, int Index) {
1220   if (Object->getBytesInAddress() == 4) {
1221     auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1222     return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1223   }
1224   auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1225   return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1226 }
1227 
1228 static imported_symbol_iterator
1229 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1230   uintptr_t IntPtr = 0;
1231   Object->getRvaPtr(RVA, IntPtr);
1232   return makeImportedSymbolIterator(Object, IntPtr, 0);
1233 }
1234 
1235 static imported_symbol_iterator
1236 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1237   uintptr_t IntPtr = 0;
1238   Object->getRvaPtr(RVA, IntPtr);
1239   // Forward the pointer to the last entry which is null.
1240   int Index = 0;
1241   if (Object->getBytesInAddress() == 4) {
1242     auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1243     while (*Entry++)
1244       ++Index;
1245   } else {
1246     auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1247     while (*Entry++)
1248       ++Index;
1249   }
1250   return makeImportedSymbolIterator(Object, IntPtr, Index);
1251 }
1252 
1253 imported_symbol_iterator
1254 ImportDirectoryEntryRef::imported_symbol_begin() const {
1255   return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
1256                              OwningObject);
1257 }
1258 
1259 imported_symbol_iterator
1260 ImportDirectoryEntryRef::imported_symbol_end() const {
1261   return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
1262                            OwningObject);
1263 }
1264 
1265 iterator_range<imported_symbol_iterator>
1266 ImportDirectoryEntryRef::imported_symbols() const {
1267   return make_range(imported_symbol_begin(), imported_symbol_end());
1268 }
1269 
1270 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
1271   return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1272                              OwningObject);
1273 }
1274 
1275 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
1276   return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1277                            OwningObject);
1278 }
1279 
1280 iterator_range<imported_symbol_iterator>
1281 ImportDirectoryEntryRef::lookup_table_symbols() const {
1282   return make_range(lookup_table_begin(), lookup_table_end());
1283 }
1284 
1285 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1286   uintptr_t IntPtr = 0;
1287   if (std::error_code EC =
1288           OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1289     return EC;
1290   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1291   return std::error_code();
1292 }
1293 
1294 std::error_code
1295 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t  &Result) const {
1296   Result = ImportTable[Index].ImportLookupTableRVA;
1297   return std::error_code();
1298 }
1299 
1300 std::error_code
1301 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1302   Result = ImportTable[Index].ImportAddressTableRVA;
1303   return std::error_code();
1304 }
1305 
1306 bool DelayImportDirectoryEntryRef::
1307 operator==(const DelayImportDirectoryEntryRef &Other) const {
1308   return Table == Other.Table && Index == Other.Index;
1309 }
1310 
1311 void DelayImportDirectoryEntryRef::moveNext() {
1312   ++Index;
1313 }
1314 
1315 imported_symbol_iterator
1316 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1317   return importedSymbolBegin(Table[Index].DelayImportNameTable,
1318                              OwningObject);
1319 }
1320 
1321 imported_symbol_iterator
1322 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1323   return importedSymbolEnd(Table[Index].DelayImportNameTable,
1324                            OwningObject);
1325 }
1326 
1327 iterator_range<imported_symbol_iterator>
1328 DelayImportDirectoryEntryRef::imported_symbols() const {
1329   return make_range(imported_symbol_begin(), imported_symbol_end());
1330 }
1331 
1332 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1333   uintptr_t IntPtr = 0;
1334   if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1335     return EC;
1336   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1337   return std::error_code();
1338 }
1339 
1340 std::error_code DelayImportDirectoryEntryRef::
1341 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1342   Result = Table;
1343   return std::error_code();
1344 }
1345 
1346 std::error_code DelayImportDirectoryEntryRef::
1347 getImportAddress(int AddrIndex, uint64_t &Result) const {
1348   uint32_t RVA = Table[Index].DelayImportAddressTable +
1349       AddrIndex * (OwningObject->is64() ? 8 : 4);
1350   uintptr_t IntPtr = 0;
1351   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1352     return EC;
1353   if (OwningObject->is64())
1354     Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1355   else
1356     Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1357   return std::error_code();
1358 }
1359 
1360 bool ExportDirectoryEntryRef::
1361 operator==(const ExportDirectoryEntryRef &Other) const {
1362   return ExportTable == Other.ExportTable && Index == Other.Index;
1363 }
1364 
1365 void ExportDirectoryEntryRef::moveNext() {
1366   ++Index;
1367 }
1368 
1369 // Returns the name of the current export symbol. If the symbol is exported only
1370 // by ordinal, the empty string is set as a result.
1371 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1372   uintptr_t IntPtr = 0;
1373   if (std::error_code EC =
1374           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1375     return EC;
1376   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1377   return std::error_code();
1378 }
1379 
1380 // Returns the starting ordinal number.
1381 std::error_code
1382 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1383   Result = ExportTable->OrdinalBase;
1384   return std::error_code();
1385 }
1386 
1387 // Returns the export ordinal of the current export symbol.
1388 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1389   Result = ExportTable->OrdinalBase + Index;
1390   return std::error_code();
1391 }
1392 
1393 // Returns the address of the current export symbol.
1394 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1395   uintptr_t IntPtr = 0;
1396   if (std::error_code EC =
1397           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1398     return EC;
1399   const export_address_table_entry *entry =
1400       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1401   Result = entry[Index].ExportRVA;
1402   return std::error_code();
1403 }
1404 
1405 // Returns the name of the current export symbol. If the symbol is exported only
1406 // by ordinal, the empty string is set as a result.
1407 std::error_code
1408 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1409   uintptr_t IntPtr = 0;
1410   if (std::error_code EC =
1411           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1412     return EC;
1413   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1414 
1415   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1416   int Offset = 0;
1417   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1418        I < E; ++I, ++Offset) {
1419     if (*I != Index)
1420       continue;
1421     if (std::error_code EC =
1422             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1423       return EC;
1424     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1425     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1426       return EC;
1427     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1428     return std::error_code();
1429   }
1430   Result = "";
1431   return std::error_code();
1432 }
1433 
1434 std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1435   const data_directory *DataEntry;
1436   if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
1437     return EC;
1438   uint32_t RVA;
1439   if (auto EC = getExportRVA(RVA))
1440     return EC;
1441   uint32_t Begin = DataEntry->RelativeVirtualAddress;
1442   uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1443   Result = (Begin <= RVA && RVA < End);
1444   return std::error_code();
1445 }
1446 
1447 std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1448   uint32_t RVA;
1449   if (auto EC = getExportRVA(RVA))
1450     return EC;
1451   uintptr_t IntPtr = 0;
1452   if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1453     return EC;
1454   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1455   return std::error_code();
1456 }
1457 
1458 bool ImportedSymbolRef::
1459 operator==(const ImportedSymbolRef &Other) const {
1460   return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1461       && Index == Other.Index;
1462 }
1463 
1464 void ImportedSymbolRef::moveNext() {
1465   ++Index;
1466 }
1467 
1468 std::error_code
1469 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1470   uint32_t RVA;
1471   if (Entry32) {
1472     // If a symbol is imported only by ordinal, it has no name.
1473     if (Entry32[Index].isOrdinal())
1474       return std::error_code();
1475     RVA = Entry32[Index].getHintNameRVA();
1476   } else {
1477     if (Entry64[Index].isOrdinal())
1478       return std::error_code();
1479     RVA = Entry64[Index].getHintNameRVA();
1480   }
1481   uintptr_t IntPtr = 0;
1482   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1483     return EC;
1484   // +2 because the first two bytes is hint.
1485   Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1486   return std::error_code();
1487 }
1488 
1489 std::error_code ImportedSymbolRef::isOrdinal(bool &Result) const {
1490   if (Entry32)
1491     Result = Entry32[Index].isOrdinal();
1492   else
1493     Result = Entry64[Index].isOrdinal();
1494   return std::error_code();
1495 }
1496 
1497 std::error_code ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
1498   if (Entry32)
1499     Result = Entry32[Index].getHintNameRVA();
1500   else
1501     Result = Entry64[Index].getHintNameRVA();
1502   return std::error_code();
1503 }
1504 
1505 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1506   uint32_t RVA;
1507   if (Entry32) {
1508     if (Entry32[Index].isOrdinal()) {
1509       Result = Entry32[Index].getOrdinal();
1510       return std::error_code();
1511     }
1512     RVA = Entry32[Index].getHintNameRVA();
1513   } else {
1514     if (Entry64[Index].isOrdinal()) {
1515       Result = Entry64[Index].getOrdinal();
1516       return std::error_code();
1517     }
1518     RVA = Entry64[Index].getHintNameRVA();
1519   }
1520   uintptr_t IntPtr = 0;
1521   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1522     return EC;
1523   Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1524   return std::error_code();
1525 }
1526 
1527 ErrorOr<std::unique_ptr<COFFObjectFile>>
1528 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1529   std::error_code EC;
1530   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1531   if (EC)
1532     return EC;
1533   return std::move(Ret);
1534 }
1535 
1536 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1537   return Header == Other.Header && Index == Other.Index;
1538 }
1539 
1540 void BaseRelocRef::moveNext() {
1541   // Header->BlockSize is the size of the current block, including the
1542   // size of the header itself.
1543   uint32_t Size = sizeof(*Header) +
1544       sizeof(coff_base_reloc_block_entry) * (Index + 1);
1545   if (Size == Header->BlockSize) {
1546     // .reloc contains a list of base relocation blocks. Each block
1547     // consists of the header followed by entries. The header contains
1548     // how many entories will follow. When we reach the end of the
1549     // current block, proceed to the next block.
1550     Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1551         reinterpret_cast<const uint8_t *>(Header) + Size);
1552     Index = 0;
1553   } else {
1554     ++Index;
1555   }
1556 }
1557 
1558 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1559   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1560   Type = Entry[Index].getType();
1561   return std::error_code();
1562 }
1563 
1564 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1565   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1566   Result = Header->PageRVA + Entry[Index].getOffset();
1567   return std::error_code();
1568 }
1569