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