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