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