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