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