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