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