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