xref: /llvm-project/llvm/lib/Object/COFFObjectFile.cpp (revision 77ecf90c52641aadedf6bad7c8bea5b217b49729)
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 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
667     : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
668       COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
669       DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
670       SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
671       ImportDirectory(nullptr),
672       DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
673       ExportDirectory(nullptr), BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
674       DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr) {
675   // Check that we at least have enough room for a header.
676   if (!checkSize(Data, EC, sizeof(coff_file_header)))
677     return;
678 
679   // The current location in the file where we are looking at.
680   uint64_t CurPtr = 0;
681 
682   // PE header is optional and is present only in executables. If it exists,
683   // it is placed right after COFF header.
684   bool HasPEHeader = false;
685 
686   // Check if this is a PE/COFF file.
687   if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
688     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
689     // PE signature to find 'normal' COFF header.
690     const auto *DH = reinterpret_cast<const dos_header *>(base());
691     if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
692       CurPtr = DH->AddressOfNewExeHeader;
693       // Check the PE magic bytes. ("PE\0\0")
694       if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
695         EC = object_error::parse_failed;
696         return;
697       }
698       CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
699       HasPEHeader = true;
700     }
701   }
702 
703   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
704     return;
705 
706   // It might be a bigobj file, let's check.  Note that COFF bigobj and COFF
707   // import libraries share a common prefix but bigobj is more restrictive.
708   if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
709       COFFHeader->NumberOfSections == uint16_t(0xffff) &&
710       checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
711     if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
712       return;
713 
714     // Verify that we are dealing with bigobj.
715     if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
716         std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
717                     sizeof(COFF::BigObjMagic)) == 0) {
718       COFFHeader = nullptr;
719       CurPtr += sizeof(coff_bigobj_file_header);
720     } else {
721       // It's not a bigobj.
722       COFFBigObjHeader = nullptr;
723     }
724   }
725   if (COFFHeader) {
726     // The prior checkSize call may have failed.  This isn't a hard error
727     // because we were just trying to sniff out bigobj.
728     EC = std::error_code();
729     CurPtr += sizeof(coff_file_header);
730 
731     if (COFFHeader->isImportLibrary())
732       return;
733   }
734 
735   if (HasPEHeader) {
736     const pe32_header *Header;
737     if ((EC = getObject(Header, Data, base() + CurPtr)))
738       return;
739 
740     const uint8_t *DataDirAddr;
741     uint64_t DataDirSize;
742     if (Header->Magic == COFF::PE32Header::PE32) {
743       PE32Header = Header;
744       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
745       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
746     } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
747       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
748       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
749       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
750     } else {
751       // It's neither PE32 nor PE32+.
752       EC = object_error::parse_failed;
753       return;
754     }
755     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
756       return;
757   }
758 
759   if (COFFHeader)
760     CurPtr += COFFHeader->SizeOfOptionalHeader;
761 
762   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
763                       (uint64_t)getNumberOfSections() * sizeof(coff_section))))
764     return;
765 
766   // Initialize the pointer to the symbol table.
767   if (getPointerToSymbolTable() != 0) {
768     if ((EC = initSymbolTablePtr())) {
769       SymbolTable16 = nullptr;
770       SymbolTable32 = nullptr;
771       StringTable = nullptr;
772       StringTableSize = 0;
773     }
774   } else {
775     // We had better not have any symbols if we don't have a symbol table.
776     if (getNumberOfSymbols() != 0) {
777       EC = object_error::parse_failed;
778       return;
779     }
780   }
781 
782   // Initialize the pointer to the beginning of the import table.
783   if ((EC = initImportTablePtr()))
784     return;
785   if ((EC = initDelayImportTablePtr()))
786     return;
787 
788   // Initialize the pointer to the export table.
789   if ((EC = initExportTablePtr()))
790     return;
791 
792   // Initialize the pointer to the base relocation table.
793   if ((EC = initBaseRelocPtr()))
794     return;
795 
796   // Initialize the pointer to the export table.
797   if ((EC = initDebugDirectoryPtr()))
798     return;
799 
800   if ((EC = initLoadConfigPtr()))
801     return;
802 
803   EC = std::error_code();
804 }
805 
806 basic_symbol_iterator COFFObjectFile::symbol_begin() const {
807   DataRefImpl Ret;
808   Ret.p = getSymbolTable();
809   return basic_symbol_iterator(SymbolRef(Ret, this));
810 }
811 
812 basic_symbol_iterator COFFObjectFile::symbol_end() const {
813   // The symbol table ends where the string table begins.
814   DataRefImpl Ret;
815   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
816   return basic_symbol_iterator(SymbolRef(Ret, this));
817 }
818 
819 import_directory_iterator COFFObjectFile::import_directory_begin() const {
820   if (!ImportDirectory)
821     return import_directory_end();
822   if (ImportDirectory->isNull())
823     return import_directory_end();
824   return import_directory_iterator(
825       ImportDirectoryEntryRef(ImportDirectory, 0, this));
826 }
827 
828 import_directory_iterator COFFObjectFile::import_directory_end() const {
829   return import_directory_iterator(
830       ImportDirectoryEntryRef(nullptr, -1, this));
831 }
832 
833 delay_import_directory_iterator
834 COFFObjectFile::delay_import_directory_begin() const {
835   return delay_import_directory_iterator(
836       DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
837 }
838 
839 delay_import_directory_iterator
840 COFFObjectFile::delay_import_directory_end() const {
841   return delay_import_directory_iterator(
842       DelayImportDirectoryEntryRef(
843           DelayImportDirectory, NumberOfDelayImportDirectory, this));
844 }
845 
846 export_directory_iterator COFFObjectFile::export_directory_begin() const {
847   return export_directory_iterator(
848       ExportDirectoryEntryRef(ExportDirectory, 0, this));
849 }
850 
851 export_directory_iterator COFFObjectFile::export_directory_end() const {
852   if (!ExportDirectory)
853     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
854   ExportDirectoryEntryRef Ref(ExportDirectory,
855                               ExportDirectory->AddressTableEntries, this);
856   return export_directory_iterator(Ref);
857 }
858 
859 section_iterator COFFObjectFile::section_begin() const {
860   DataRefImpl Ret;
861   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
862   return section_iterator(SectionRef(Ret, this));
863 }
864 
865 section_iterator COFFObjectFile::section_end() const {
866   DataRefImpl Ret;
867   int NumSections =
868       COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
869   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
870   return section_iterator(SectionRef(Ret, this));
871 }
872 
873 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
874   return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
875 }
876 
877 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
878   return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
879 }
880 
881 uint8_t COFFObjectFile::getBytesInAddress() const {
882   return getArch() == Triple::x86_64 || getArch() == Triple::aarch64 ? 8 : 4;
883 }
884 
885 StringRef COFFObjectFile::getFileFormatName() const {
886   switch(getMachine()) {
887   case COFF::IMAGE_FILE_MACHINE_I386:
888     return "COFF-i386";
889   case COFF::IMAGE_FILE_MACHINE_AMD64:
890     return "COFF-x86-64";
891   case COFF::IMAGE_FILE_MACHINE_ARMNT:
892     return "COFF-ARM";
893   case COFF::IMAGE_FILE_MACHINE_ARM64:
894     return "COFF-ARM64";
895   default:
896     return "COFF-<unknown arch>";
897   }
898 }
899 
900 Triple::ArchType COFFObjectFile::getArch() const {
901   switch (getMachine()) {
902   case COFF::IMAGE_FILE_MACHINE_I386:
903     return Triple::x86;
904   case COFF::IMAGE_FILE_MACHINE_AMD64:
905     return Triple::x86_64;
906   case COFF::IMAGE_FILE_MACHINE_ARMNT:
907     return Triple::thumb;
908   case COFF::IMAGE_FILE_MACHINE_ARM64:
909     return Triple::aarch64;
910   default:
911     return Triple::UnknownArch;
912   }
913 }
914 
915 Expected<uint64_t> COFFObjectFile::getStartAddress() const {
916   if (PE32Header)
917     return PE32Header->AddressOfEntryPoint;
918   return 0;
919 }
920 
921 iterator_range<import_directory_iterator>
922 COFFObjectFile::import_directories() const {
923   return make_range(import_directory_begin(), import_directory_end());
924 }
925 
926 iterator_range<delay_import_directory_iterator>
927 COFFObjectFile::delay_import_directories() const {
928   return make_range(delay_import_directory_begin(),
929                     delay_import_directory_end());
930 }
931 
932 iterator_range<export_directory_iterator>
933 COFFObjectFile::export_directories() const {
934   return make_range(export_directory_begin(), export_directory_end());
935 }
936 
937 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
938   return make_range(base_reloc_begin(), base_reloc_end());
939 }
940 
941 std::error_code
942 COFFObjectFile::getDataDirectory(uint32_t Index,
943                                  const data_directory *&Res) const {
944   // Error if there's no data directory or the index is out of range.
945   if (!DataDirectory) {
946     Res = nullptr;
947     return object_error::parse_failed;
948   }
949   assert(PE32Header || PE32PlusHeader);
950   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
951                                : PE32PlusHeader->NumberOfRvaAndSize;
952   if (Index >= NumEnt) {
953     Res = nullptr;
954     return object_error::parse_failed;
955   }
956   Res = &DataDirectory[Index];
957   return std::error_code();
958 }
959 
960 Expected<const coff_section *> COFFObjectFile::getSection(int32_t Index) const {
961   // Perhaps getting the section of a reserved section index should be an error,
962   // but callers rely on this to return null.
963   if (COFF::isReservedSectionNumber(Index))
964     return (const coff_section *)nullptr;
965   if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
966     // We already verified the section table data, so no need to check again.
967     return SectionTable + (Index - 1);
968   }
969   return errorCodeToError(object_error::parse_failed);
970 }
971 
972 Expected<StringRef> COFFObjectFile::getString(uint32_t Offset) const {
973   if (StringTableSize <= 4)
974     // Tried to get a string from an empty string table.
975     return errorCodeToError(object_error::parse_failed);
976   if (Offset >= StringTableSize)
977     return errorCodeToError(object_error::unexpected_eof);
978   return StringRef(StringTable + Offset);
979 }
980 
981 Expected<StringRef> COFFObjectFile::getSymbolName(COFFSymbolRef Symbol) const {
982   return getSymbolName(Symbol.getGeneric());
983 }
984 
985 Expected<StringRef>
986 COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol) const {
987   // Check for string table entry. First 4 bytes are 0.
988   if (Symbol->Name.Offset.Zeroes == 0)
989     return getString(Symbol->Name.Offset.Offset);
990 
991   // Null terminated, let ::strlen figure out the length.
992   if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
993     return StringRef(Symbol->Name.ShortName);
994 
995   // Not null terminated, use all 8 bytes.
996   return StringRef(Symbol->Name.ShortName, COFF::NameSize);
997 }
998 
999 ArrayRef<uint8_t>
1000 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
1001   const uint8_t *Aux = nullptr;
1002 
1003   size_t SymbolSize = getSymbolTableEntrySize();
1004   if (Symbol.getNumberOfAuxSymbols() > 0) {
1005     // AUX data comes immediately after the symbol in COFF
1006     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
1007 #ifndef NDEBUG
1008     // Verify that the Aux symbol points to a valid entry in the symbol table.
1009     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
1010     if (Offset < getPointerToSymbolTable() ||
1011         Offset >=
1012             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
1013       report_fatal_error("Aux Symbol data was outside of symbol table.");
1014 
1015     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
1016            "Aux Symbol data did not point to the beginning of a symbol");
1017 #endif
1018   }
1019   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
1020 }
1021 
1022 uint32_t COFFObjectFile::getSymbolIndex(COFFSymbolRef Symbol) const {
1023   uintptr_t Offset =
1024       reinterpret_cast<uintptr_t>(Symbol.getRawPtr()) - getSymbolTable();
1025   assert(Offset % getSymbolTableEntrySize() == 0 &&
1026          "Symbol did not point to the beginning of a symbol");
1027   size_t Index = Offset / getSymbolTableEntrySize();
1028   assert(Index < getNumberOfSymbols());
1029   return Index;
1030 }
1031 
1032 Expected<StringRef>
1033 COFFObjectFile::getSectionName(const coff_section *Sec) const {
1034   StringRef Name;
1035   if (Sec->Name[COFF::NameSize - 1] == 0)
1036     // Null terminated, let ::strlen figure out the length.
1037     Name = Sec->Name;
1038   else
1039     // Not null terminated, use all 8 bytes.
1040     Name = StringRef(Sec->Name, COFF::NameSize);
1041 
1042   // Check for string table entry. First byte is '/'.
1043   if (Name.startswith("/")) {
1044     uint32_t Offset;
1045     if (Name.startswith("//")) {
1046       if (decodeBase64StringEntry(Name.substr(2), Offset))
1047         return createStringError(object_error::parse_failed,
1048                                  "invalid section name");
1049     } else {
1050       if (Name.substr(1).getAsInteger(10, Offset))
1051         return createStringError(object_error::parse_failed,
1052                                  "invalid section name");
1053     }
1054     return getString(Offset);
1055   }
1056 
1057   return Name;
1058 }
1059 
1060 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
1061   // SizeOfRawData and VirtualSize change what they represent depending on
1062   // whether or not we have an executable image.
1063   //
1064   // For object files, SizeOfRawData contains the size of section's data;
1065   // VirtualSize should be zero but isn't due to buggy COFF writers.
1066   //
1067   // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1068   // actual section size is in VirtualSize.  It is possible for VirtualSize to
1069   // be greater than SizeOfRawData; the contents past that point should be
1070   // considered to be zero.
1071   if (getDOSHeader())
1072     return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1073   return Sec->SizeOfRawData;
1074 }
1075 
1076 Error COFFObjectFile::getSectionContents(const coff_section *Sec,
1077                                          ArrayRef<uint8_t> &Res) const {
1078   // In COFF, a virtual section won't have any in-file
1079   // content, so the file pointer to the content will be zero.
1080   if (Sec->PointerToRawData == 0)
1081     return Error::success();
1082   // The only thing that we need to verify is that the contents is contained
1083   // within the file bounds. We don't need to make sure it doesn't cover other
1084   // data, as there's nothing that says that is not allowed.
1085   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1086   uint32_t SectionSize = getSectionSize(Sec);
1087   if (checkOffset(Data, ConStart, SectionSize))
1088     return make_error<BinaryError>();
1089   Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1090   return Error::success();
1091 }
1092 
1093 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1094   return reinterpret_cast<const coff_relocation*>(Rel.p);
1095 }
1096 
1097 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1098   Rel.p = reinterpret_cast<uintptr_t>(
1099             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1100 }
1101 
1102 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1103   const coff_relocation *R = toRel(Rel);
1104   return R->VirtualAddress;
1105 }
1106 
1107 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1108   const coff_relocation *R = toRel(Rel);
1109   DataRefImpl Ref;
1110   if (R->SymbolTableIndex >= getNumberOfSymbols())
1111     return symbol_end();
1112   if (SymbolTable16)
1113     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1114   else if (SymbolTable32)
1115     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1116   else
1117     llvm_unreachable("no symbol table pointer!");
1118   return symbol_iterator(SymbolRef(Ref, this));
1119 }
1120 
1121 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
1122   const coff_relocation* R = toRel(Rel);
1123   return R->Type;
1124 }
1125 
1126 const coff_section *
1127 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1128   return toSec(Section.getRawDataRefImpl());
1129 }
1130 
1131 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1132   if (SymbolTable16)
1133     return toSymb<coff_symbol16>(Ref);
1134   if (SymbolTable32)
1135     return toSymb<coff_symbol32>(Ref);
1136   llvm_unreachable("no symbol table pointer!");
1137 }
1138 
1139 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1140   return getCOFFSymbol(Symbol.getRawDataRefImpl());
1141 }
1142 
1143 const coff_relocation *
1144 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1145   return toRel(Reloc.getRawDataRefImpl());
1146 }
1147 
1148 ArrayRef<coff_relocation>
1149 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1150   return {getFirstReloc(Sec, Data, base()),
1151           getNumberOfRelocations(Sec, Data, base())};
1152 }
1153 
1154 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
1155   case COFF::reloc_type:                                                       \
1156     return #reloc_type;
1157 
1158 StringRef COFFObjectFile::getRelocationTypeName(uint16_t Type) const {
1159   switch (getMachine()) {
1160   case COFF::IMAGE_FILE_MACHINE_AMD64:
1161     switch (Type) {
1162     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1163     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1164     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1165     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1166     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1167     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1168     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1169     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1170     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1171     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1172     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1173     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1174     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1175     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1176     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1177     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1178     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1179     default:
1180       return "Unknown";
1181     }
1182     break;
1183   case COFF::IMAGE_FILE_MACHINE_ARMNT:
1184     switch (Type) {
1185     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1186     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1187     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1188     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1189     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1190     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1191     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1192     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1193     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_REL32);
1194     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1195     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1196     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1197     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1198     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1199     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1200     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1201     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_PAIR);
1202     default:
1203       return "Unknown";
1204     }
1205     break;
1206   case COFF::IMAGE_FILE_MACHINE_ARM64:
1207     switch (Type) {
1208     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ABSOLUTE);
1209     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32);
1210     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32NB);
1211     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH26);
1212     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEBASE_REL21);
1213     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL21);
1214     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12A);
1215     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12L);
1216     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL);
1217     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12A);
1218     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_HIGH12A);
1219     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12L);
1220     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_TOKEN);
1221     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECTION);
1222     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR64);
1223     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH19);
1224     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH14);
1225     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL32);
1226     default:
1227       return "Unknown";
1228     }
1229     break;
1230   case COFF::IMAGE_FILE_MACHINE_I386:
1231     switch (Type) {
1232     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1233     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1234     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1235     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1236     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1237     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1238     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1239     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1240     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1241     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1242     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1243     default:
1244       return "Unknown";
1245     }
1246     break;
1247   default:
1248     return "Unknown";
1249   }
1250 }
1251 
1252 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1253 
1254 void COFFObjectFile::getRelocationTypeName(
1255     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1256   const coff_relocation *Reloc = toRel(Rel);
1257   StringRef Res = getRelocationTypeName(Reloc->Type);
1258   Result.append(Res.begin(), Res.end());
1259 }
1260 
1261 bool COFFObjectFile::isRelocatableObject() const {
1262   return !DataDirectory;
1263 }
1264 
1265 StringRef COFFObjectFile::mapDebugSectionName(StringRef Name) const {
1266   return StringSwitch<StringRef>(Name)
1267       .Case("eh_fram", "eh_frame")
1268       .Default(Name);
1269 }
1270 
1271 bool ImportDirectoryEntryRef::
1272 operator==(const ImportDirectoryEntryRef &Other) const {
1273   return ImportTable == Other.ImportTable && Index == Other.Index;
1274 }
1275 
1276 void ImportDirectoryEntryRef::moveNext() {
1277   ++Index;
1278   if (ImportTable[Index].isNull()) {
1279     Index = -1;
1280     ImportTable = nullptr;
1281   }
1282 }
1283 
1284 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1285     const coff_import_directory_table_entry *&Result) const {
1286   return getObject(Result, OwningObject->Data, ImportTable + Index);
1287 }
1288 
1289 static imported_symbol_iterator
1290 makeImportedSymbolIterator(const COFFObjectFile *Object,
1291                            uintptr_t Ptr, int Index) {
1292   if (Object->getBytesInAddress() == 4) {
1293     auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1294     return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1295   }
1296   auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1297   return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1298 }
1299 
1300 static imported_symbol_iterator
1301 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1302   uintptr_t IntPtr = 0;
1303   Object->getRvaPtr(RVA, IntPtr);
1304   return makeImportedSymbolIterator(Object, IntPtr, 0);
1305 }
1306 
1307 static imported_symbol_iterator
1308 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1309   uintptr_t IntPtr = 0;
1310   Object->getRvaPtr(RVA, IntPtr);
1311   // Forward the pointer to the last entry which is null.
1312   int Index = 0;
1313   if (Object->getBytesInAddress() == 4) {
1314     auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1315     while (*Entry++)
1316       ++Index;
1317   } else {
1318     auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1319     while (*Entry++)
1320       ++Index;
1321   }
1322   return makeImportedSymbolIterator(Object, IntPtr, Index);
1323 }
1324 
1325 imported_symbol_iterator
1326 ImportDirectoryEntryRef::imported_symbol_begin() const {
1327   return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
1328                              OwningObject);
1329 }
1330 
1331 imported_symbol_iterator
1332 ImportDirectoryEntryRef::imported_symbol_end() const {
1333   return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
1334                            OwningObject);
1335 }
1336 
1337 iterator_range<imported_symbol_iterator>
1338 ImportDirectoryEntryRef::imported_symbols() const {
1339   return make_range(imported_symbol_begin(), imported_symbol_end());
1340 }
1341 
1342 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
1343   return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1344                              OwningObject);
1345 }
1346 
1347 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
1348   return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1349                            OwningObject);
1350 }
1351 
1352 iterator_range<imported_symbol_iterator>
1353 ImportDirectoryEntryRef::lookup_table_symbols() const {
1354   return make_range(lookup_table_begin(), lookup_table_end());
1355 }
1356 
1357 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1358   uintptr_t IntPtr = 0;
1359   if (std::error_code EC =
1360           OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1361     return EC;
1362   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1363   return std::error_code();
1364 }
1365 
1366 std::error_code
1367 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t  &Result) const {
1368   Result = ImportTable[Index].ImportLookupTableRVA;
1369   return std::error_code();
1370 }
1371 
1372 std::error_code
1373 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1374   Result = ImportTable[Index].ImportAddressTableRVA;
1375   return std::error_code();
1376 }
1377 
1378 bool DelayImportDirectoryEntryRef::
1379 operator==(const DelayImportDirectoryEntryRef &Other) const {
1380   return Table == Other.Table && Index == Other.Index;
1381 }
1382 
1383 void DelayImportDirectoryEntryRef::moveNext() {
1384   ++Index;
1385 }
1386 
1387 imported_symbol_iterator
1388 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1389   return importedSymbolBegin(Table[Index].DelayImportNameTable,
1390                              OwningObject);
1391 }
1392 
1393 imported_symbol_iterator
1394 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1395   return importedSymbolEnd(Table[Index].DelayImportNameTable,
1396                            OwningObject);
1397 }
1398 
1399 iterator_range<imported_symbol_iterator>
1400 DelayImportDirectoryEntryRef::imported_symbols() const {
1401   return make_range(imported_symbol_begin(), imported_symbol_end());
1402 }
1403 
1404 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1405   uintptr_t IntPtr = 0;
1406   if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1407     return EC;
1408   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1409   return std::error_code();
1410 }
1411 
1412 std::error_code DelayImportDirectoryEntryRef::
1413 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1414   Result = &Table[Index];
1415   return std::error_code();
1416 }
1417 
1418 std::error_code DelayImportDirectoryEntryRef::
1419 getImportAddress(int AddrIndex, uint64_t &Result) const {
1420   uint32_t RVA = Table[Index].DelayImportAddressTable +
1421       AddrIndex * (OwningObject->is64() ? 8 : 4);
1422   uintptr_t IntPtr = 0;
1423   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1424     return EC;
1425   if (OwningObject->is64())
1426     Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1427   else
1428     Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1429   return std::error_code();
1430 }
1431 
1432 bool ExportDirectoryEntryRef::
1433 operator==(const ExportDirectoryEntryRef &Other) const {
1434   return ExportTable == Other.ExportTable && Index == Other.Index;
1435 }
1436 
1437 void ExportDirectoryEntryRef::moveNext() {
1438   ++Index;
1439 }
1440 
1441 // Returns the name of the current export symbol. If the symbol is exported only
1442 // by ordinal, the empty string is set as a result.
1443 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1444   uintptr_t IntPtr = 0;
1445   if (std::error_code EC =
1446           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1447     return EC;
1448   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1449   return std::error_code();
1450 }
1451 
1452 // Returns the starting ordinal number.
1453 std::error_code
1454 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1455   Result = ExportTable->OrdinalBase;
1456   return std::error_code();
1457 }
1458 
1459 // Returns the export ordinal of the current export symbol.
1460 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1461   Result = ExportTable->OrdinalBase + Index;
1462   return std::error_code();
1463 }
1464 
1465 // Returns the address of the current export symbol.
1466 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1467   uintptr_t IntPtr = 0;
1468   if (std::error_code EC =
1469           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1470     return EC;
1471   const export_address_table_entry *entry =
1472       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1473   Result = entry[Index].ExportRVA;
1474   return std::error_code();
1475 }
1476 
1477 // Returns the name of the current export symbol. If the symbol is exported only
1478 // by ordinal, the empty string is set as a result.
1479 std::error_code
1480 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1481   uintptr_t IntPtr = 0;
1482   if (std::error_code EC =
1483           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1484     return EC;
1485   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1486 
1487   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1488   int Offset = 0;
1489   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1490        I < E; ++I, ++Offset) {
1491     if (*I != Index)
1492       continue;
1493     if (std::error_code EC =
1494             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1495       return EC;
1496     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1497     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1498       return EC;
1499     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1500     return std::error_code();
1501   }
1502   Result = "";
1503   return std::error_code();
1504 }
1505 
1506 std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1507   const data_directory *DataEntry;
1508   if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
1509     return EC;
1510   uint32_t RVA;
1511   if (auto EC = getExportRVA(RVA))
1512     return EC;
1513   uint32_t Begin = DataEntry->RelativeVirtualAddress;
1514   uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1515   Result = (Begin <= RVA && RVA < End);
1516   return std::error_code();
1517 }
1518 
1519 std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1520   uint32_t RVA;
1521   if (auto EC = getExportRVA(RVA))
1522     return EC;
1523   uintptr_t IntPtr = 0;
1524   if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1525     return EC;
1526   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1527   return std::error_code();
1528 }
1529 
1530 bool ImportedSymbolRef::
1531 operator==(const ImportedSymbolRef &Other) const {
1532   return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1533       && Index == Other.Index;
1534 }
1535 
1536 void ImportedSymbolRef::moveNext() {
1537   ++Index;
1538 }
1539 
1540 std::error_code
1541 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1542   uint32_t RVA;
1543   if (Entry32) {
1544     // If a symbol is imported only by ordinal, it has no name.
1545     if (Entry32[Index].isOrdinal())
1546       return std::error_code();
1547     RVA = Entry32[Index].getHintNameRVA();
1548   } else {
1549     if (Entry64[Index].isOrdinal())
1550       return std::error_code();
1551     RVA = Entry64[Index].getHintNameRVA();
1552   }
1553   uintptr_t IntPtr = 0;
1554   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1555     return EC;
1556   // +2 because the first two bytes is hint.
1557   Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1558   return std::error_code();
1559 }
1560 
1561 std::error_code ImportedSymbolRef::isOrdinal(bool &Result) const {
1562   if (Entry32)
1563     Result = Entry32[Index].isOrdinal();
1564   else
1565     Result = Entry64[Index].isOrdinal();
1566   return std::error_code();
1567 }
1568 
1569 std::error_code ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
1570   if (Entry32)
1571     Result = Entry32[Index].getHintNameRVA();
1572   else
1573     Result = Entry64[Index].getHintNameRVA();
1574   return std::error_code();
1575 }
1576 
1577 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1578   uint32_t RVA;
1579   if (Entry32) {
1580     if (Entry32[Index].isOrdinal()) {
1581       Result = Entry32[Index].getOrdinal();
1582       return std::error_code();
1583     }
1584     RVA = Entry32[Index].getHintNameRVA();
1585   } else {
1586     if (Entry64[Index].isOrdinal()) {
1587       Result = Entry64[Index].getOrdinal();
1588       return std::error_code();
1589     }
1590     RVA = Entry64[Index].getHintNameRVA();
1591   }
1592   uintptr_t IntPtr = 0;
1593   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1594     return EC;
1595   Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1596   return std::error_code();
1597 }
1598 
1599 Expected<std::unique_ptr<COFFObjectFile>>
1600 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1601   std::error_code EC;
1602   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1603   if (EC)
1604     return errorCodeToError(EC);
1605   return std::move(Ret);
1606 }
1607 
1608 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1609   return Header == Other.Header && Index == Other.Index;
1610 }
1611 
1612 void BaseRelocRef::moveNext() {
1613   // Header->BlockSize is the size of the current block, including the
1614   // size of the header itself.
1615   uint32_t Size = sizeof(*Header) +
1616       sizeof(coff_base_reloc_block_entry) * (Index + 1);
1617   if (Size == Header->BlockSize) {
1618     // .reloc contains a list of base relocation blocks. Each block
1619     // consists of the header followed by entries. The header contains
1620     // how many entories will follow. When we reach the end of the
1621     // current block, proceed to the next block.
1622     Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1623         reinterpret_cast<const uint8_t *>(Header) + Size);
1624     Index = 0;
1625   } else {
1626     ++Index;
1627   }
1628 }
1629 
1630 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1631   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1632   Type = Entry[Index].getType();
1633   return std::error_code();
1634 }
1635 
1636 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1637   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1638   Result = Header->PageRVA + Entry[Index].getOffset();
1639   return std::error_code();
1640 }
1641 
1642 #define RETURN_IF_ERROR(Expr)                                                  \
1643   do {                                                                         \
1644     Error E = (Expr);                                                          \
1645     if (E)                                                                     \
1646       return std::move(E);                                                     \
1647   } while (0)
1648 
1649 Expected<ArrayRef<UTF16>>
1650 ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) {
1651   BinaryStreamReader Reader = BinaryStreamReader(BBS);
1652   Reader.setOffset(Offset);
1653   uint16_t Length;
1654   RETURN_IF_ERROR(Reader.readInteger(Length));
1655   ArrayRef<UTF16> RawDirString;
1656   RETURN_IF_ERROR(Reader.readArray(RawDirString, Length));
1657   return RawDirString;
1658 }
1659 
1660 Expected<ArrayRef<UTF16>>
1661 ResourceSectionRef::getEntryNameString(const coff_resource_dir_entry &Entry) {
1662   return getDirStringAtOffset(Entry.Identifier.getNameOffset());
1663 }
1664 
1665 Expected<const coff_resource_dir_table &>
1666 ResourceSectionRef::getTableAtOffset(uint32_t Offset) {
1667   const coff_resource_dir_table *Table = nullptr;
1668 
1669   BinaryStreamReader Reader(BBS);
1670   Reader.setOffset(Offset);
1671   RETURN_IF_ERROR(Reader.readObject(Table));
1672   assert(Table != nullptr);
1673   return *Table;
1674 }
1675 
1676 Expected<const coff_resource_dir_entry &>
1677 ResourceSectionRef::getTableEntryAtOffset(uint32_t Offset) {
1678   const coff_resource_dir_entry *Entry = nullptr;
1679 
1680   BinaryStreamReader Reader(BBS);
1681   Reader.setOffset(Offset);
1682   RETURN_IF_ERROR(Reader.readObject(Entry));
1683   assert(Entry != nullptr);
1684   return *Entry;
1685 }
1686 
1687 Expected<const coff_resource_data_entry &>
1688 ResourceSectionRef::getDataEntryAtOffset(uint32_t Offset) {
1689   const coff_resource_data_entry *Entry = nullptr;
1690 
1691   BinaryStreamReader Reader(BBS);
1692   Reader.setOffset(Offset);
1693   RETURN_IF_ERROR(Reader.readObject(Entry));
1694   assert(Entry != nullptr);
1695   return *Entry;
1696 }
1697 
1698 Expected<const coff_resource_dir_table &>
1699 ResourceSectionRef::getEntrySubDir(const coff_resource_dir_entry &Entry) {
1700   assert(Entry.Offset.isSubDir());
1701   return getTableAtOffset(Entry.Offset.value());
1702 }
1703 
1704 Expected<const coff_resource_data_entry &>
1705 ResourceSectionRef::getEntryData(const coff_resource_dir_entry &Entry) {
1706   assert(!Entry.Offset.isSubDir());
1707   return getDataEntryAtOffset(Entry.Offset.value());
1708 }
1709 
1710 Expected<const coff_resource_dir_table &> ResourceSectionRef::getBaseTable() {
1711   return getTableAtOffset(0);
1712 }
1713 
1714 Expected<const coff_resource_dir_entry &>
1715 ResourceSectionRef::getTableEntry(const coff_resource_dir_table &Table,
1716                                   uint32_t Index) {
1717   if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries))
1718     return createStringError(object_error::parse_failed, "index out of range");
1719   const uint8_t *TablePtr = reinterpret_cast<const uint8_t *>(&Table);
1720   ptrdiff_t TableOffset = TablePtr - BBS.data().data();
1721   return getTableEntryAtOffset(TableOffset + sizeof(Table) +
1722                                Index * sizeof(coff_resource_dir_entry));
1723 }
1724 
1725 Error ResourceSectionRef::load(const COFFObjectFile *O) {
1726   for (const SectionRef &S : O->sections()) {
1727     Expected<StringRef> Name = S.getName();
1728     if (!Name)
1729       return Name.takeError();
1730 
1731     if (*Name == ".rsrc" || *Name == ".rsrc$01")
1732       return load(O, S);
1733   }
1734   return createStringError(object_error::parse_failed,
1735                            "no resource section found");
1736 }
1737 
1738 Error ResourceSectionRef::load(const COFFObjectFile *O, const SectionRef &S) {
1739   Obj = O;
1740   Section = S;
1741   Expected<StringRef> Contents = Section.getContents();
1742   if (!Contents)
1743     return Contents.takeError();
1744   BBS = BinaryByteStream(*Contents, support::little);
1745   const coff_section *COFFSect = Obj->getCOFFSection(Section);
1746   ArrayRef<coff_relocation> OrigRelocs = Obj->getRelocations(COFFSect);
1747   Relocs.reserve(OrigRelocs.size());
1748   for (const coff_relocation &R : OrigRelocs)
1749     Relocs.push_back(&R);
1750   std::sort(Relocs.begin(), Relocs.end(),
1751             [](const coff_relocation *A, const coff_relocation *B) {
1752               return A->VirtualAddress < B->VirtualAddress;
1753             });
1754   return Error::success();
1755 }
1756 
1757 Expected<StringRef>
1758 ResourceSectionRef::getContents(const coff_resource_data_entry &Entry) {
1759   if (!Obj)
1760     return createStringError(object_error::parse_failed, "no object provided");
1761 
1762   // Find a potential relocation at the DataRVA field (first member of
1763   // the coff_resource_data_entry struct).
1764   const uint8_t *EntryPtr = reinterpret_cast<const uint8_t *>(&Entry);
1765   ptrdiff_t EntryOffset = EntryPtr - BBS.data().data();
1766   coff_relocation RelocTarget{ulittle32_t(EntryOffset), ulittle32_t(0),
1767                               ulittle16_t(0)};
1768   auto RelocsForOffset =
1769       std::equal_range(Relocs.begin(), Relocs.end(), &RelocTarget,
1770                        [](const coff_relocation *A, const coff_relocation *B) {
1771                          return A->VirtualAddress < B->VirtualAddress;
1772                        });
1773 
1774   if (RelocsForOffset.first != RelocsForOffset.second) {
1775     // We found a relocation with the right offset. Check that it does have
1776     // the expected type.
1777     const coff_relocation &R = **RelocsForOffset.first;
1778     uint16_t RVAReloc;
1779     switch (Obj->getMachine()) {
1780     case COFF::IMAGE_FILE_MACHINE_I386:
1781       RVAReloc = COFF::IMAGE_REL_I386_DIR32NB;
1782       break;
1783     case COFF::IMAGE_FILE_MACHINE_AMD64:
1784       RVAReloc = COFF::IMAGE_REL_AMD64_ADDR32NB;
1785       break;
1786     case COFF::IMAGE_FILE_MACHINE_ARMNT:
1787       RVAReloc = COFF::IMAGE_REL_ARM_ADDR32NB;
1788       break;
1789     case COFF::IMAGE_FILE_MACHINE_ARM64:
1790       RVAReloc = COFF::IMAGE_REL_ARM64_ADDR32NB;
1791       break;
1792     default:
1793       return createStringError(object_error::parse_failed,
1794                                "unsupported architecture");
1795     }
1796     if (R.Type != RVAReloc)
1797       return createStringError(object_error::parse_failed,
1798                                "unexpected relocation type");
1799     // Get the relocation's symbol
1800     Expected<COFFSymbolRef> Sym = Obj->getSymbol(R.SymbolTableIndex);
1801     if (!Sym)
1802       return Sym.takeError();
1803     // And the symbol's section
1804     Expected<const coff_section *> Section =
1805         Obj->getSection(Sym->getSectionNumber());
1806     if (!Section)
1807       return Section.takeError();
1808     // Add the initial value of DataRVA to the symbol's offset to find the
1809     // data it points at.
1810     uint64_t Offset = Entry.DataRVA + Sym->getValue();
1811     ArrayRef<uint8_t> Contents;
1812     if (Error E = Obj->getSectionContents(*Section, Contents))
1813       return std::move(E);
1814     if (Offset + Entry.DataSize > Contents.size())
1815       return createStringError(object_error::parse_failed,
1816                                "data outside of section");
1817     // Return a reference to the data inside the section.
1818     return StringRef(reinterpret_cast<const char *>(Contents.data()) + Offset,
1819                      Entry.DataSize);
1820   } else {
1821     // Relocatable objects need a relocation for the DataRVA field.
1822     if (Obj->isRelocatableObject())
1823       return createStringError(object_error::parse_failed,
1824                                "no relocation found for DataRVA");
1825 
1826     // Locate the section that contains the address that DataRVA points at.
1827     uint64_t VA = Entry.DataRVA + Obj->getImageBase();
1828     for (const SectionRef &S : Obj->sections()) {
1829       if (VA >= S.getAddress() &&
1830           VA + Entry.DataSize <= S.getAddress() + S.getSize()) {
1831         uint64_t Offset = VA - S.getAddress();
1832         Expected<StringRef> Contents = S.getContents();
1833         if (!Contents)
1834           return Contents.takeError();
1835         return Contents->slice(Offset, Offset + Entry.DataSize);
1836       }
1837     }
1838     return createStringError(object_error::parse_failed,
1839                              "address not found in image");
1840   }
1841 }
1842