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