xref: /llvm-project/llvm/lib/Object/COFFObjectFile.cpp (revision f27f3f8491dfc7aa41f6cd8a95763acc677d379c)
1 //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the COFFObjectFile class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Object/COFF.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/ADT/iterator_range.h"
19 #include "llvm/Support/COFF.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <cctype>
23 #include <limits>
24 
25 using namespace llvm;
26 using namespace object;
27 
28 using support::ulittle16_t;
29 using support::ulittle32_t;
30 using support::ulittle64_t;
31 using support::little16_t;
32 
33 // Returns false if size is greater than the buffer size. And sets ec.
34 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
35   if (M.getBufferSize() < Size) {
36     EC = object_error::unexpected_eof;
37     return false;
38   }
39   return true;
40 }
41 
42 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
43                                    const uint64_t Size) {
44   if (Addr + Size < Addr || Addr + Size < Size ||
45       Addr + Size > uintptr_t(M.getBufferEnd()) ||
46       Addr < uintptr_t(M.getBufferStart())) {
47     return object_error::unexpected_eof;
48   }
49   return std::error_code();
50 }
51 
52 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
53 // Returns unexpected_eof if error.
54 template <typename T>
55 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
56                                  const void *Ptr,
57                                  const uint64_t Size = sizeof(T)) {
58   uintptr_t Addr = uintptr_t(Ptr);
59   if (std::error_code EC = checkOffset(M, Addr, Size))
60     return EC;
61   Obj = reinterpret_cast<const T *>(Addr);
62   return std::error_code();
63 }
64 
65 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
66 // prefixed slashes.
67 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
68   assert(Str.size() <= 6 && "String too long, possible overflow.");
69   if (Str.size() > 6)
70     return true;
71 
72   uint64_t Value = 0;
73   while (!Str.empty()) {
74     unsigned CharVal;
75     if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
76       CharVal = Str[0] - 'A';
77     else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
78       CharVal = Str[0] - 'a' + 26;
79     else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
80       CharVal = Str[0] - '0' + 52;
81     else if (Str[0] == '+') // 62
82       CharVal = 62;
83     else if (Str[0] == '/') // 63
84       CharVal = 63;
85     else
86       return true;
87 
88     Value = (Value * 64) + CharVal;
89     Str = Str.substr(1);
90   }
91 
92   if (Value > std::numeric_limits<uint32_t>::max())
93     return true;
94 
95   Result = static_cast<uint32_t>(Value);
96   return false;
97 }
98 
99 template <typename coff_symbol_type>
100 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
101   const coff_symbol_type *Addr =
102       reinterpret_cast<const coff_symbol_type *>(Ref.p);
103 
104   assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
105 #ifndef NDEBUG
106   // Verify that the symbol points to a valid entry in the symbol table.
107   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
108 
109   assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
110          "Symbol did not point to the beginning of a symbol");
111 #endif
112 
113   return Addr;
114 }
115 
116 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
117   const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
118 
119 # ifndef NDEBUG
120   // Verify that the section points to a valid entry in the section table.
121   if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
122     report_fatal_error("Section was outside of section table.");
123 
124   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
125   assert(Offset % sizeof(coff_section) == 0 &&
126          "Section did not point to the beginning of a section");
127 # endif
128 
129   return Addr;
130 }
131 
132 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
133   auto End = reinterpret_cast<uintptr_t>(StringTable);
134   if (SymbolTable16) {
135     const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
136     Symb += 1 + Symb->NumberOfAuxSymbols;
137     Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
138   } else if (SymbolTable32) {
139     const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
140     Symb += 1 + Symb->NumberOfAuxSymbols;
141     Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
142   } else {
143     llvm_unreachable("no symbol table pointer!");
144   }
145 }
146 
147 Expected<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
148   COFFSymbolRef Symb = getCOFFSymbol(Ref);
149   StringRef Result;
150   std::error_code EC = getSymbolName(Symb, Result);
151   if (EC)
152     return errorCodeToError(EC);
153   return Result;
154 }
155 
156 uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const {
157   return getCOFFSymbol(Ref).getValue();
158 }
159 
160 ErrorOr<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
161   uint64_t Result = getSymbolValue(Ref);
162   COFFSymbolRef Symb = getCOFFSymbol(Ref);
163   int32_t SectionNumber = Symb.getSectionNumber();
164 
165   if (Symb.isAnyUndefined() || Symb.isCommon() ||
166       COFF::isReservedSectionNumber(SectionNumber))
167     return Result;
168 
169   const coff_section *Section = nullptr;
170   if (std::error_code EC = getSection(SectionNumber, Section))
171     return EC;
172   Result += Section->VirtualAddress;
173 
174   // The section VirtualAddress does not include ImageBase, and we want to
175   // return virtual addresses.
176   Result += getImageBase();
177 
178   return Result;
179 }
180 
181 Expected<SymbolRef::Type> COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
182   COFFSymbolRef Symb = getCOFFSymbol(Ref);
183   int32_t SectionNumber = Symb.getSectionNumber();
184 
185   if (Symb.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION)
186     return SymbolRef::ST_Function;
187   if (Symb.isAnyUndefined())
188     return SymbolRef::ST_Unknown;
189   if (Symb.isCommon())
190     return SymbolRef::ST_Data;
191   if (Symb.isFileRecord())
192     return SymbolRef::ST_File;
193 
194   // TODO: perhaps we need a new symbol type ST_Section.
195   if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
196     return SymbolRef::ST_Debug;
197 
198   if (!COFF::isReservedSectionNumber(SectionNumber))
199     return SymbolRef::ST_Data;
200 
201   return SymbolRef::ST_Other;
202 }
203 
204 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
205   COFFSymbolRef Symb = getCOFFSymbol(Ref);
206   uint32_t Result = SymbolRef::SF_None;
207 
208   if (Symb.isExternal() || Symb.isWeakExternal())
209     Result |= SymbolRef::SF_Global;
210 
211   if (Symb.isWeakExternal())
212     Result |= SymbolRef::SF_Weak;
213 
214   if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
215     Result |= SymbolRef::SF_Absolute;
216 
217   if (Symb.isFileRecord())
218     Result |= SymbolRef::SF_FormatSpecific;
219 
220   if (Symb.isSectionDefinition())
221     Result |= SymbolRef::SF_FormatSpecific;
222 
223   if (Symb.isCommon())
224     Result |= SymbolRef::SF_Common;
225 
226   if (Symb.isAnyUndefined())
227     Result |= SymbolRef::SF_Undefined;
228 
229   return Result;
230 }
231 
232 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
233   COFFSymbolRef Symb = getCOFFSymbol(Ref);
234   return Symb.getValue();
235 }
236 
237 Expected<section_iterator>
238 COFFObjectFile::getSymbolSection(DataRefImpl Ref) const {
239   COFFSymbolRef Symb = getCOFFSymbol(Ref);
240   if (COFF::isReservedSectionNumber(Symb.getSectionNumber()))
241     return section_end();
242   const coff_section *Sec = nullptr;
243   if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
244     return errorCodeToError(EC);
245   DataRefImpl Ret;
246   Ret.p = reinterpret_cast<uintptr_t>(Sec);
247   return section_iterator(SectionRef(Ret, this));
248 }
249 
250 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
251   COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
252   return Symb.getSectionNumber();
253 }
254 
255 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
256   const coff_section *Sec = toSec(Ref);
257   Sec += 1;
258   Ref.p = reinterpret_cast<uintptr_t>(Sec);
259 }
260 
261 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
262                                                StringRef &Result) const {
263   const coff_section *Sec = toSec(Ref);
264   return getSectionName(Sec, Result);
265 }
266 
267 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
268   const coff_section *Sec = toSec(Ref);
269   uint64_t Result = Sec->VirtualAddress;
270 
271   // The section VirtualAddress does not include ImageBase, and we want to
272   // return virtual addresses.
273   Result += getImageBase();
274   return Result;
275 }
276 
277 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
278   return getSectionSize(toSec(Ref));
279 }
280 
281 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
282                                                    StringRef &Result) const {
283   const coff_section *Sec = toSec(Ref);
284   ArrayRef<uint8_t> Res;
285   std::error_code EC = getSectionContents(Sec, Res);
286   Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
287   return EC;
288 }
289 
290 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
291   const coff_section *Sec = toSec(Ref);
292   return Sec->getAlignment();
293 }
294 
295 bool COFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
296   return false;
297 }
298 
299 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
300   const coff_section *Sec = toSec(Ref);
301   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
302 }
303 
304 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
305   const coff_section *Sec = toSec(Ref);
306   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
307 }
308 
309 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
310   const coff_section *Sec = toSec(Ref);
311   const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
312                             COFF::IMAGE_SCN_MEM_READ |
313                             COFF::IMAGE_SCN_MEM_WRITE;
314   return (Sec->Characteristics & BssFlags) == BssFlags;
315 }
316 
317 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
318   uintptr_t Offset =
319       uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
320   assert((Offset % sizeof(coff_section)) == 0);
321   return (Offset / sizeof(coff_section)) + 1;
322 }
323 
324 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
325   const coff_section *Sec = toSec(Ref);
326   // In COFF, a virtual section won't have any in-file
327   // content, so the file pointer to the content will be zero.
328   return Sec->PointerToRawData == 0;
329 }
330 
331 static uint32_t getNumberOfRelocations(const coff_section *Sec,
332                                        MemoryBufferRef M, const uint8_t *base) {
333   // The field for the number of relocations in COFF section table is only
334   // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
335   // NumberOfRelocations field, and the actual relocation count is stored in the
336   // VirtualAddress field in the first relocation entry.
337   if (Sec->hasExtendedRelocations()) {
338     const coff_relocation *FirstReloc;
339     if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
340         base + Sec->PointerToRelocations)))
341       return 0;
342     // -1 to exclude this first relocation entry.
343     return FirstReloc->VirtualAddress - 1;
344   }
345   return Sec->NumberOfRelocations;
346 }
347 
348 static const coff_relocation *
349 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
350   uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
351   if (!NumRelocs)
352     return nullptr;
353   auto begin = reinterpret_cast<const coff_relocation *>(
354       Base + Sec->PointerToRelocations);
355   if (Sec->hasExtendedRelocations()) {
356     // Skip the first relocation entry repurposed to store the number of
357     // relocations.
358     begin++;
359   }
360   if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
361     return nullptr;
362   return begin;
363 }
364 
365 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
366   const coff_section *Sec = toSec(Ref);
367   const coff_relocation *begin = getFirstReloc(Sec, Data, base());
368   if (begin && Sec->VirtualAddress != 0)
369     report_fatal_error("Sections with relocations should have an address of 0");
370   DataRefImpl Ret;
371   Ret.p = reinterpret_cast<uintptr_t>(begin);
372   return relocation_iterator(RelocationRef(Ret, this));
373 }
374 
375 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
376   const coff_section *Sec = toSec(Ref);
377   const coff_relocation *I = getFirstReloc(Sec, Data, base());
378   if (I)
379     I += getNumberOfRelocations(Sec, Data, base());
380   DataRefImpl Ret;
381   Ret.p = reinterpret_cast<uintptr_t>(I);
382   return relocation_iterator(RelocationRef(Ret, this));
383 }
384 
385 // Initialize the pointer to the symbol table.
386 std::error_code COFFObjectFile::initSymbolTablePtr() {
387   if (COFFHeader)
388     if (std::error_code EC = getObject(
389             SymbolTable16, Data, base() + getPointerToSymbolTable(),
390             (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
391       return EC;
392 
393   if (COFFBigObjHeader)
394     if (std::error_code EC = getObject(
395             SymbolTable32, Data, base() + getPointerToSymbolTable(),
396             (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
397       return EC;
398 
399   // Find string table. The first four byte of the string table contains the
400   // total size of the string table, including the size field itself. If the
401   // string table is empty, the value of the first four byte would be 4.
402   uint32_t StringTableOffset = getPointerToSymbolTable() +
403                                getNumberOfSymbols() * getSymbolTableEntrySize();
404   const uint8_t *StringTableAddr = base() + StringTableOffset;
405   const ulittle32_t *StringTableSizePtr;
406   if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
407     return EC;
408   StringTableSize = *StringTableSizePtr;
409   if (std::error_code EC =
410           getObject(StringTable, Data, StringTableAddr, StringTableSize))
411     return EC;
412 
413   // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
414   // tools like cvtres write a size of 0 for an empty table instead of 4.
415   if (StringTableSize < 4)
416       StringTableSize = 4;
417 
418   // Check that the string table is null terminated if has any in it.
419   if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
420     return  object_error::parse_failed;
421   return std::error_code();
422 }
423 
424 uint64_t COFFObjectFile::getImageBase() const {
425   if (PE32Header)
426     return PE32Header->ImageBase;
427   else if (PE32PlusHeader)
428     return PE32PlusHeader->ImageBase;
429   // This actually comes up in practice.
430   return 0;
431 }
432 
433 // Returns the file offset for the given VA.
434 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
435   uint64_t ImageBase = getImageBase();
436   uint64_t Rva = Addr - ImageBase;
437   assert(Rva <= UINT32_MAX);
438   return getRvaPtr((uint32_t)Rva, Res);
439 }
440 
441 // Returns the file offset for the given RVA.
442 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
443   for (const SectionRef &S : sections()) {
444     const coff_section *Section = getCOFFSection(S);
445     uint32_t SectionStart = Section->VirtualAddress;
446     uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
447     if (SectionStart <= Addr && Addr < SectionEnd) {
448       uint32_t Offset = Addr - SectionStart;
449       Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
450       return std::error_code();
451     }
452   }
453   return object_error::parse_failed;
454 }
455 
456 std::error_code
457 COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
458                                      ArrayRef<uint8_t> &Contents) const {
459   for (const SectionRef &S : sections()) {
460     const coff_section *Section = getCOFFSection(S);
461     uint32_t SectionStart = Section->VirtualAddress;
462     // Check if this RVA is within the section bounds. Be careful about integer
463     // overflow.
464     uint32_t OffsetIntoSection = RVA - SectionStart;
465     if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize &&
466         Size <= Section->VirtualSize - OffsetIntoSection) {
467       uintptr_t Begin =
468           uintptr_t(base()) + Section->PointerToRawData + OffsetIntoSection;
469       Contents =
470           ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size);
471       return std::error_code();
472     }
473   }
474   return object_error::parse_failed;
475 }
476 
477 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
478 // table entry.
479 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
480                                             StringRef &Name) const {
481   uintptr_t IntPtr = 0;
482   if (std::error_code EC = getRvaPtr(Rva, IntPtr))
483     return EC;
484   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
485   Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
486   Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
487   return std::error_code();
488 }
489 
490 std::error_code COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir,
491                                                 const debug_pdb_info *&PDBInfo,
492                                                 StringRef &PDBFileName) const {
493   ArrayRef<uint8_t> InfoBytes;
494   if (std::error_code EC = getRvaAndSizeAsBytes(
495           DebugDir->AddressOfRawData, DebugDir->SizeOfData, InfoBytes))
496     return EC;
497   if (InfoBytes.size() < sizeof(debug_pdb_info) + 1)
498     return object_error::parse_failed;
499   PDBInfo = reinterpret_cast<const debug_pdb_info *>(InfoBytes.data());
500   InfoBytes = InfoBytes.drop_front(sizeof(debug_pdb_info));
501   PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()),
502                           InfoBytes.size());
503   // Truncate the name at the first null byte. Ignore any padding.
504   PDBFileName = PDBFileName.split('\0').first;
505   return std::error_code();
506 }
507 
508 std::error_code COFFObjectFile::getDebugPDBInfo(const debug_pdb_info *&PDBInfo,
509                                                 StringRef &PDBFileName) const {
510   for (const debug_directory &D : debug_directories())
511     if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW)
512       return getDebugPDBInfo(&D, PDBInfo, PDBFileName);
513   // If we get here, there is no PDB info to return.
514   PDBInfo = nullptr;
515   PDBFileName = StringRef();
516   return std::error_code();
517 }
518 
519 // Find the import table.
520 std::error_code COFFObjectFile::initImportTablePtr() {
521   // First, we get the RVA of the import table. If the file lacks a pointer to
522   // the import table, do nothing.
523   const data_directory *DataEntry;
524   if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
525     return std::error_code();
526 
527   // Do nothing if the pointer to import table is NULL.
528   if (DataEntry->RelativeVirtualAddress == 0)
529     return std::error_code();
530 
531   uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
532   // -1 because the last entry is the null entry.
533   NumberOfImportDirectory = DataEntry->Size /
534       sizeof(import_directory_table_entry) - 1;
535 
536   // Find the section that contains the RVA. This is needed because the RVA is
537   // the import table's memory address which is different from its file offset.
538   uintptr_t IntPtr = 0;
539   if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
540     return EC;
541   ImportDirectory = reinterpret_cast<
542       const import_directory_table_entry *>(IntPtr);
543   return std::error_code();
544 }
545 
546 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
547 std::error_code COFFObjectFile::initDelayImportTablePtr() {
548   const data_directory *DataEntry;
549   if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
550     return std::error_code();
551   if (DataEntry->RelativeVirtualAddress == 0)
552     return std::error_code();
553 
554   uint32_t RVA = DataEntry->RelativeVirtualAddress;
555   NumberOfDelayImportDirectory = DataEntry->Size /
556       sizeof(delay_import_directory_table_entry) - 1;
557 
558   uintptr_t IntPtr = 0;
559   if (std::error_code EC = getRvaPtr(RVA, IntPtr))
560     return EC;
561   DelayImportDirectory = reinterpret_cast<
562       const delay_import_directory_table_entry *>(IntPtr);
563   return std::error_code();
564 }
565 
566 // Find the export table.
567 std::error_code COFFObjectFile::initExportTablePtr() {
568   // First, we get the RVA of the export table. If the file lacks a pointer to
569   // the export table, do nothing.
570   const data_directory *DataEntry;
571   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
572     return std::error_code();
573 
574   // Do nothing if the pointer to export table is NULL.
575   if (DataEntry->RelativeVirtualAddress == 0)
576     return std::error_code();
577 
578   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
579   uintptr_t IntPtr = 0;
580   if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
581     return EC;
582   ExportDirectory =
583       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
584   return std::error_code();
585 }
586 
587 std::error_code COFFObjectFile::initBaseRelocPtr() {
588   const data_directory *DataEntry;
589   if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
590     return std::error_code();
591   if (DataEntry->RelativeVirtualAddress == 0)
592     return std::error_code();
593 
594   uintptr_t IntPtr = 0;
595   if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
596     return EC;
597   BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
598       IntPtr);
599   BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
600       IntPtr + DataEntry->Size);
601   return std::error_code();
602 }
603 
604 std::error_code COFFObjectFile::initDebugDirectoryPtr() {
605   // Get the RVA of the debug directory. Do nothing if it does not exist.
606   const data_directory *DataEntry;
607   if (getDataDirectory(COFF::DEBUG_DIRECTORY, DataEntry))
608     return std::error_code();
609 
610   // Do nothing if the RVA is NULL.
611   if (DataEntry->RelativeVirtualAddress == 0)
612     return std::error_code();
613 
614   // Check that the size is a multiple of the entry size.
615   if (DataEntry->Size % sizeof(debug_directory) != 0)
616     return object_error::parse_failed;
617 
618   uintptr_t IntPtr = 0;
619   if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
620     return EC;
621   DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
622   if (std::error_code EC = getRvaPtr(
623           DataEntry->RelativeVirtualAddress + DataEntry->Size, IntPtr))
624     return EC;
625   DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(IntPtr);
626   return std::error_code();
627 }
628 
629 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
630     : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
631       COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
632       DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
633       SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
634       ImportDirectory(nullptr), NumberOfImportDirectory(0),
635       DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
636       ExportDirectory(nullptr), BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
637       DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr) {
638   // Check that we at least have enough room for a header.
639   if (!checkSize(Data, EC, sizeof(coff_file_header)))
640     return;
641 
642   // The current location in the file where we are looking at.
643   uint64_t CurPtr = 0;
644 
645   // PE header is optional and is present only in executables. If it exists,
646   // it is placed right after COFF header.
647   bool HasPEHeader = false;
648 
649   // Check if this is a PE/COFF file.
650   if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
651     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
652     // PE signature to find 'normal' COFF header.
653     const auto *DH = reinterpret_cast<const dos_header *>(base());
654     if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
655       CurPtr = DH->AddressOfNewExeHeader;
656       // Check the PE magic bytes. ("PE\0\0")
657       if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
658         EC = object_error::parse_failed;
659         return;
660       }
661       CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
662       HasPEHeader = true;
663     }
664   }
665 
666   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
667     return;
668 
669   // It might be a bigobj file, let's check.  Note that COFF bigobj and COFF
670   // import libraries share a common prefix but bigobj is more restrictive.
671   if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
672       COFFHeader->NumberOfSections == uint16_t(0xffff) &&
673       checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
674     if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
675       return;
676 
677     // Verify that we are dealing with bigobj.
678     if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
679         std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
680                     sizeof(COFF::BigObjMagic)) == 0) {
681       COFFHeader = nullptr;
682       CurPtr += sizeof(coff_bigobj_file_header);
683     } else {
684       // It's not a bigobj.
685       COFFBigObjHeader = nullptr;
686     }
687   }
688   if (COFFHeader) {
689     // The prior checkSize call may have failed.  This isn't a hard error
690     // because we were just trying to sniff out bigobj.
691     EC = std::error_code();
692     CurPtr += sizeof(coff_file_header);
693 
694     if (COFFHeader->isImportLibrary())
695       return;
696   }
697 
698   if (HasPEHeader) {
699     const pe32_header *Header;
700     if ((EC = getObject(Header, Data, base() + CurPtr)))
701       return;
702 
703     const uint8_t *DataDirAddr;
704     uint64_t DataDirSize;
705     if (Header->Magic == COFF::PE32Header::PE32) {
706       PE32Header = Header;
707       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
708       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
709     } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
710       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
711       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
712       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
713     } else {
714       // It's neither PE32 nor PE32+.
715       EC = object_error::parse_failed;
716       return;
717     }
718     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
719       return;
720     CurPtr += COFFHeader->SizeOfOptionalHeader;
721   }
722 
723   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
724                       (uint64_t)getNumberOfSections() * sizeof(coff_section))))
725     return;
726 
727   // Initialize the pointer to the symbol table.
728   if (getPointerToSymbolTable() != 0) {
729     if ((EC = initSymbolTablePtr()))
730       return;
731   } else {
732     // We had better not have any symbols if we don't have a symbol table.
733     if (getNumberOfSymbols() != 0) {
734       EC = object_error::parse_failed;
735       return;
736     }
737   }
738 
739   // Initialize the pointer to the beginning of the import table.
740   if ((EC = initImportTablePtr()))
741     return;
742   if ((EC = initDelayImportTablePtr()))
743     return;
744 
745   // Initialize the pointer to the export table.
746   if ((EC = initExportTablePtr()))
747     return;
748 
749   // Initialize the pointer to the base relocation table.
750   if ((EC = initBaseRelocPtr()))
751     return;
752 
753   // Initialize the pointer to the export table.
754   if ((EC = initDebugDirectoryPtr()))
755     return;
756 
757   EC = std::error_code();
758 }
759 
760 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
761   DataRefImpl Ret;
762   Ret.p = getSymbolTable();
763   return basic_symbol_iterator(SymbolRef(Ret, this));
764 }
765 
766 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
767   // The symbol table ends where the string table begins.
768   DataRefImpl Ret;
769   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
770   return basic_symbol_iterator(SymbolRef(Ret, this));
771 }
772 
773 import_directory_iterator COFFObjectFile::import_directory_begin() const {
774   return import_directory_iterator(
775       ImportDirectoryEntryRef(ImportDirectory, 0, this));
776 }
777 
778 import_directory_iterator COFFObjectFile::import_directory_end() const {
779   return import_directory_iterator(
780       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
781 }
782 
783 delay_import_directory_iterator
784 COFFObjectFile::delay_import_directory_begin() const {
785   return delay_import_directory_iterator(
786       DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
787 }
788 
789 delay_import_directory_iterator
790 COFFObjectFile::delay_import_directory_end() const {
791   return delay_import_directory_iterator(
792       DelayImportDirectoryEntryRef(
793           DelayImportDirectory, NumberOfDelayImportDirectory, this));
794 }
795 
796 export_directory_iterator COFFObjectFile::export_directory_begin() const {
797   return export_directory_iterator(
798       ExportDirectoryEntryRef(ExportDirectory, 0, this));
799 }
800 
801 export_directory_iterator COFFObjectFile::export_directory_end() const {
802   if (!ExportDirectory)
803     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
804   ExportDirectoryEntryRef Ref(ExportDirectory,
805                               ExportDirectory->AddressTableEntries, this);
806   return export_directory_iterator(Ref);
807 }
808 
809 section_iterator COFFObjectFile::section_begin() const {
810   DataRefImpl Ret;
811   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
812   return section_iterator(SectionRef(Ret, this));
813 }
814 
815 section_iterator COFFObjectFile::section_end() const {
816   DataRefImpl Ret;
817   int NumSections =
818       COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
819   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
820   return section_iterator(SectionRef(Ret, this));
821 }
822 
823 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
824   return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
825 }
826 
827 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
828   return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
829 }
830 
831 uint8_t COFFObjectFile::getBytesInAddress() const {
832   return getArch() == Triple::x86_64 ? 8 : 4;
833 }
834 
835 StringRef COFFObjectFile::getFileFormatName() const {
836   switch(getMachine()) {
837   case COFF::IMAGE_FILE_MACHINE_I386:
838     return "COFF-i386";
839   case COFF::IMAGE_FILE_MACHINE_AMD64:
840     return "COFF-x86-64";
841   case COFF::IMAGE_FILE_MACHINE_ARMNT:
842     return "COFF-ARM";
843   case COFF::IMAGE_FILE_MACHINE_ARM64:
844     return "COFF-ARM64";
845   default:
846     return "COFF-<unknown arch>";
847   }
848 }
849 
850 unsigned COFFObjectFile::getArch() const {
851   switch (getMachine()) {
852   case COFF::IMAGE_FILE_MACHINE_I386:
853     return Triple::x86;
854   case COFF::IMAGE_FILE_MACHINE_AMD64:
855     return Triple::x86_64;
856   case COFF::IMAGE_FILE_MACHINE_ARMNT:
857     return Triple::thumb;
858   case COFF::IMAGE_FILE_MACHINE_ARM64:
859     return Triple::aarch64;
860   default:
861     return Triple::UnknownArch;
862   }
863 }
864 
865 iterator_range<import_directory_iterator>
866 COFFObjectFile::import_directories() const {
867   return make_range(import_directory_begin(), import_directory_end());
868 }
869 
870 iterator_range<delay_import_directory_iterator>
871 COFFObjectFile::delay_import_directories() const {
872   return make_range(delay_import_directory_begin(),
873                     delay_import_directory_end());
874 }
875 
876 iterator_range<export_directory_iterator>
877 COFFObjectFile::export_directories() const {
878   return make_range(export_directory_begin(), export_directory_end());
879 }
880 
881 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
882   return make_range(base_reloc_begin(), base_reloc_end());
883 }
884 
885 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
886   Res = PE32Header;
887   return std::error_code();
888 }
889 
890 std::error_code
891 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
892   Res = PE32PlusHeader;
893   return std::error_code();
894 }
895 
896 std::error_code
897 COFFObjectFile::getDataDirectory(uint32_t Index,
898                                  const data_directory *&Res) const {
899   // Error if if there's no data directory or the index is out of range.
900   if (!DataDirectory) {
901     Res = nullptr;
902     return object_error::parse_failed;
903   }
904   assert(PE32Header || PE32PlusHeader);
905   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
906                                : PE32PlusHeader->NumberOfRvaAndSize;
907   if (Index >= NumEnt) {
908     Res = nullptr;
909     return object_error::parse_failed;
910   }
911   Res = &DataDirectory[Index];
912   return std::error_code();
913 }
914 
915 std::error_code COFFObjectFile::getSection(int32_t Index,
916                                            const coff_section *&Result) const {
917   Result = nullptr;
918   if (COFF::isReservedSectionNumber(Index))
919     return std::error_code();
920   if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
921     // We already verified the section table data, so no need to check again.
922     Result = SectionTable + (Index - 1);
923     return std::error_code();
924   }
925   return object_error::parse_failed;
926 }
927 
928 std::error_code COFFObjectFile::getString(uint32_t Offset,
929                                           StringRef &Result) const {
930   if (StringTableSize <= 4)
931     // Tried to get a string from an empty string table.
932     return object_error::parse_failed;
933   if (Offset >= StringTableSize)
934     return object_error::unexpected_eof;
935   Result = StringRef(StringTable + Offset);
936   return std::error_code();
937 }
938 
939 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
940                                               StringRef &Res) const {
941   return getSymbolName(Symbol.getGeneric(), Res);
942 }
943 
944 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
945                                               StringRef &Res) const {
946   // Check for string table entry. First 4 bytes are 0.
947   if (Symbol->Name.Offset.Zeroes == 0) {
948     if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
949       return EC;
950     return std::error_code();
951   }
952 
953   if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
954     // Null terminated, let ::strlen figure out the length.
955     Res = StringRef(Symbol->Name.ShortName);
956   else
957     // Not null terminated, use all 8 bytes.
958     Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
959   return std::error_code();
960 }
961 
962 ArrayRef<uint8_t>
963 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
964   const uint8_t *Aux = nullptr;
965 
966   size_t SymbolSize = getSymbolTableEntrySize();
967   if (Symbol.getNumberOfAuxSymbols() > 0) {
968     // AUX data comes immediately after the symbol in COFF
969     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
970 # ifndef NDEBUG
971     // Verify that the Aux symbol points to a valid entry in the symbol table.
972     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
973     if (Offset < getPointerToSymbolTable() ||
974         Offset >=
975             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
976       report_fatal_error("Aux Symbol data was outside of symbol table.");
977 
978     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
979            "Aux Symbol data did not point to the beginning of a symbol");
980 # endif
981   }
982   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
983 }
984 
985 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
986                                                StringRef &Res) const {
987   StringRef Name;
988   if (Sec->Name[COFF::NameSize - 1] == 0)
989     // Null terminated, let ::strlen figure out the length.
990     Name = Sec->Name;
991   else
992     // Not null terminated, use all 8 bytes.
993     Name = StringRef(Sec->Name, COFF::NameSize);
994 
995   // Check for string table entry. First byte is '/'.
996   if (Name.startswith("/")) {
997     uint32_t Offset;
998     if (Name.startswith("//")) {
999       if (decodeBase64StringEntry(Name.substr(2), Offset))
1000         return object_error::parse_failed;
1001     } else {
1002       if (Name.substr(1).getAsInteger(10, Offset))
1003         return object_error::parse_failed;
1004     }
1005     if (std::error_code EC = getString(Offset, Name))
1006       return EC;
1007   }
1008 
1009   Res = Name;
1010   return std::error_code();
1011 }
1012 
1013 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
1014   // SizeOfRawData and VirtualSize change what they represent depending on
1015   // whether or not we have an executable image.
1016   //
1017   // For object files, SizeOfRawData contains the size of section's data;
1018   // VirtualSize should be zero but isn't due to buggy COFF writers.
1019   //
1020   // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1021   // actual section size is in VirtualSize.  It is possible for VirtualSize to
1022   // be greater than SizeOfRawData; the contents past that point should be
1023   // considered to be zero.
1024   if (getDOSHeader())
1025     return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1026   return Sec->SizeOfRawData;
1027 }
1028 
1029 std::error_code
1030 COFFObjectFile::getSectionContents(const coff_section *Sec,
1031                                    ArrayRef<uint8_t> &Res) const {
1032   // In COFF, a virtual section won't have any in-file
1033   // content, so the file pointer to the content will be zero.
1034   if (Sec->PointerToRawData == 0)
1035     return object_error::parse_failed;
1036   // The only thing that we need to verify is that the contents is contained
1037   // within the file bounds. We don't need to make sure it doesn't cover other
1038   // data, as there's nothing that says that is not allowed.
1039   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1040   uint32_t SectionSize = getSectionSize(Sec);
1041   if (checkOffset(Data, ConStart, SectionSize))
1042     return object_error::parse_failed;
1043   Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1044   return std::error_code();
1045 }
1046 
1047 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1048   return reinterpret_cast<const coff_relocation*>(Rel.p);
1049 }
1050 
1051 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1052   Rel.p = reinterpret_cast<uintptr_t>(
1053             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1054 }
1055 
1056 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1057   const coff_relocation *R = toRel(Rel);
1058   return R->VirtualAddress;
1059 }
1060 
1061 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1062   const coff_relocation *R = toRel(Rel);
1063   DataRefImpl Ref;
1064   if (R->SymbolTableIndex >= getNumberOfSymbols())
1065     return symbol_end();
1066   if (SymbolTable16)
1067     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1068   else if (SymbolTable32)
1069     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1070   else
1071     llvm_unreachable("no symbol table pointer!");
1072   return symbol_iterator(SymbolRef(Ref, this));
1073 }
1074 
1075 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
1076   const coff_relocation* R = toRel(Rel);
1077   return R->Type;
1078 }
1079 
1080 const coff_section *
1081 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1082   return toSec(Section.getRawDataRefImpl());
1083 }
1084 
1085 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1086   if (SymbolTable16)
1087     return toSymb<coff_symbol16>(Ref);
1088   if (SymbolTable32)
1089     return toSymb<coff_symbol32>(Ref);
1090   llvm_unreachable("no symbol table pointer!");
1091 }
1092 
1093 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1094   return getCOFFSymbol(Symbol.getRawDataRefImpl());
1095 }
1096 
1097 const coff_relocation *
1098 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1099   return toRel(Reloc.getRawDataRefImpl());
1100 }
1101 
1102 iterator_range<const coff_relocation *>
1103 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1104   const coff_relocation *I = getFirstReloc(Sec, Data, base());
1105   const coff_relocation *E = I;
1106   if (I)
1107     E += getNumberOfRelocations(Sec, Data, base());
1108   return make_range(I, E);
1109 }
1110 
1111 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
1112   case COFF::reloc_type:                                                       \
1113     Res = #reloc_type;                                                         \
1114     break;
1115 
1116 void COFFObjectFile::getRelocationTypeName(
1117     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1118   const coff_relocation *Reloc = toRel(Rel);
1119   StringRef Res;
1120   switch (getMachine()) {
1121   case COFF::IMAGE_FILE_MACHINE_AMD64:
1122     switch (Reloc->Type) {
1123     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1124     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1125     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1126     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1127     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1128     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1129     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1130     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1131     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1132     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1133     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1134     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1135     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1136     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1137     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1138     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1139     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1140     default:
1141       Res = "Unknown";
1142     }
1143     break;
1144   case COFF::IMAGE_FILE_MACHINE_ARMNT:
1145     switch (Reloc->Type) {
1146     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1147     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1148     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1149     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1150     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1151     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1152     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1153     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1154     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1155     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1156     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1157     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1158     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1159     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1160     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1161     default:
1162       Res = "Unknown";
1163     }
1164     break;
1165   case COFF::IMAGE_FILE_MACHINE_I386:
1166     switch (Reloc->Type) {
1167     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1168     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1169     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1170     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1171     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1172     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1173     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1174     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1175     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1176     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1177     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1178     default:
1179       Res = "Unknown";
1180     }
1181     break;
1182   default:
1183     Res = "Unknown";
1184   }
1185   Result.append(Res.begin(), Res.end());
1186 }
1187 
1188 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1189 
1190 bool COFFObjectFile::isRelocatableObject() const {
1191   return !DataDirectory;
1192 }
1193 
1194 bool ImportDirectoryEntryRef::
1195 operator==(const ImportDirectoryEntryRef &Other) const {
1196   return ImportTable == Other.ImportTable && Index == Other.Index;
1197 }
1198 
1199 void ImportDirectoryEntryRef::moveNext() {
1200   ++Index;
1201 }
1202 
1203 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1204     const import_directory_table_entry *&Result) const {
1205   Result = ImportTable + Index;
1206   return std::error_code();
1207 }
1208 
1209 static imported_symbol_iterator
1210 makeImportedSymbolIterator(const COFFObjectFile *Object,
1211                            uintptr_t Ptr, int Index) {
1212   if (Object->getBytesInAddress() == 4) {
1213     auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1214     return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1215   }
1216   auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1217   return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1218 }
1219 
1220 static imported_symbol_iterator
1221 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1222   uintptr_t IntPtr = 0;
1223   Object->getRvaPtr(RVA, IntPtr);
1224   return makeImportedSymbolIterator(Object, IntPtr, 0);
1225 }
1226 
1227 static imported_symbol_iterator
1228 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1229   uintptr_t IntPtr = 0;
1230   Object->getRvaPtr(RVA, IntPtr);
1231   // Forward the pointer to the last entry which is null.
1232   int Index = 0;
1233   if (Object->getBytesInAddress() == 4) {
1234     auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1235     while (*Entry++)
1236       ++Index;
1237   } else {
1238     auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1239     while (*Entry++)
1240       ++Index;
1241   }
1242   return makeImportedSymbolIterator(Object, IntPtr, Index);
1243 }
1244 
1245 imported_symbol_iterator
1246 ImportDirectoryEntryRef::imported_symbol_begin() const {
1247   return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1248                              OwningObject);
1249 }
1250 
1251 imported_symbol_iterator
1252 ImportDirectoryEntryRef::imported_symbol_end() const {
1253   return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1254                            OwningObject);
1255 }
1256 
1257 iterator_range<imported_symbol_iterator>
1258 ImportDirectoryEntryRef::imported_symbols() const {
1259   return make_range(imported_symbol_begin(), imported_symbol_end());
1260 }
1261 
1262 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1263   uintptr_t IntPtr = 0;
1264   if (std::error_code EC =
1265           OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1266     return EC;
1267   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1268   return std::error_code();
1269 }
1270 
1271 std::error_code
1272 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t  &Result) const {
1273   Result = ImportTable[Index].ImportLookupTableRVA;
1274   return std::error_code();
1275 }
1276 
1277 std::error_code
1278 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1279   Result = ImportTable[Index].ImportAddressTableRVA;
1280   return std::error_code();
1281 }
1282 
1283 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1284     const import_lookup_table_entry32 *&Result) const {
1285   uintptr_t IntPtr = 0;
1286   uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1287   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1288     return EC;
1289   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1290   return std::error_code();
1291 }
1292 
1293 bool DelayImportDirectoryEntryRef::
1294 operator==(const DelayImportDirectoryEntryRef &Other) const {
1295   return Table == Other.Table && Index == Other.Index;
1296 }
1297 
1298 void DelayImportDirectoryEntryRef::moveNext() {
1299   ++Index;
1300 }
1301 
1302 imported_symbol_iterator
1303 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1304   return importedSymbolBegin(Table[Index].DelayImportNameTable,
1305                              OwningObject);
1306 }
1307 
1308 imported_symbol_iterator
1309 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1310   return importedSymbolEnd(Table[Index].DelayImportNameTable,
1311                            OwningObject);
1312 }
1313 
1314 iterator_range<imported_symbol_iterator>
1315 DelayImportDirectoryEntryRef::imported_symbols() const {
1316   return make_range(imported_symbol_begin(), imported_symbol_end());
1317 }
1318 
1319 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1320   uintptr_t IntPtr = 0;
1321   if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1322     return EC;
1323   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1324   return std::error_code();
1325 }
1326 
1327 std::error_code DelayImportDirectoryEntryRef::
1328 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1329   Result = Table;
1330   return std::error_code();
1331 }
1332 
1333 std::error_code DelayImportDirectoryEntryRef::
1334 getImportAddress(int AddrIndex, uint64_t &Result) const {
1335   uint32_t RVA = Table[Index].DelayImportAddressTable +
1336       AddrIndex * (OwningObject->is64() ? 8 : 4);
1337   uintptr_t IntPtr = 0;
1338   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1339     return EC;
1340   if (OwningObject->is64())
1341     Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1342   else
1343     Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1344   return std::error_code();
1345 }
1346 
1347 bool ExportDirectoryEntryRef::
1348 operator==(const ExportDirectoryEntryRef &Other) const {
1349   return ExportTable == Other.ExportTable && Index == Other.Index;
1350 }
1351 
1352 void ExportDirectoryEntryRef::moveNext() {
1353   ++Index;
1354 }
1355 
1356 // Returns the name of the current export symbol. If the symbol is exported only
1357 // by ordinal, the empty string is set as a result.
1358 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1359   uintptr_t IntPtr = 0;
1360   if (std::error_code EC =
1361           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1362     return EC;
1363   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1364   return std::error_code();
1365 }
1366 
1367 // Returns the starting ordinal number.
1368 std::error_code
1369 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1370   Result = ExportTable->OrdinalBase;
1371   return std::error_code();
1372 }
1373 
1374 // Returns the export ordinal of the current export symbol.
1375 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1376   Result = ExportTable->OrdinalBase + Index;
1377   return std::error_code();
1378 }
1379 
1380 // Returns the address of the current export symbol.
1381 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1382   uintptr_t IntPtr = 0;
1383   if (std::error_code EC =
1384           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1385     return EC;
1386   const export_address_table_entry *entry =
1387       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1388   Result = entry[Index].ExportRVA;
1389   return std::error_code();
1390 }
1391 
1392 // Returns the name of the current export symbol. If the symbol is exported only
1393 // by ordinal, the empty string is set as a result.
1394 std::error_code
1395 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1396   uintptr_t IntPtr = 0;
1397   if (std::error_code EC =
1398           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1399     return EC;
1400   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1401 
1402   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1403   int Offset = 0;
1404   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1405        I < E; ++I, ++Offset) {
1406     if (*I != Index)
1407       continue;
1408     if (std::error_code EC =
1409             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1410       return EC;
1411     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1412     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1413       return EC;
1414     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1415     return std::error_code();
1416   }
1417   Result = "";
1418   return std::error_code();
1419 }
1420 
1421 std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1422   const data_directory *DataEntry;
1423   if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
1424     return EC;
1425   uint32_t RVA;
1426   if (auto EC = getExportRVA(RVA))
1427     return EC;
1428   uint32_t Begin = DataEntry->RelativeVirtualAddress;
1429   uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1430   Result = (Begin <= RVA && RVA < End);
1431   return std::error_code();
1432 }
1433 
1434 std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1435   uint32_t RVA;
1436   if (auto EC = getExportRVA(RVA))
1437     return EC;
1438   uintptr_t IntPtr = 0;
1439   if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1440     return EC;
1441   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1442   return std::error_code();
1443 }
1444 
1445 bool ImportedSymbolRef::
1446 operator==(const ImportedSymbolRef &Other) const {
1447   return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1448       && Index == Other.Index;
1449 }
1450 
1451 void ImportedSymbolRef::moveNext() {
1452   ++Index;
1453 }
1454 
1455 std::error_code
1456 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1457   uint32_t RVA;
1458   if (Entry32) {
1459     // If a symbol is imported only by ordinal, it has no name.
1460     if (Entry32[Index].isOrdinal())
1461       return std::error_code();
1462     RVA = Entry32[Index].getHintNameRVA();
1463   } else {
1464     if (Entry64[Index].isOrdinal())
1465       return std::error_code();
1466     RVA = Entry64[Index].getHintNameRVA();
1467   }
1468   uintptr_t IntPtr = 0;
1469   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1470     return EC;
1471   // +2 because the first two bytes is hint.
1472   Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1473   return std::error_code();
1474 }
1475 
1476 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1477   uint32_t RVA;
1478   if (Entry32) {
1479     if (Entry32[Index].isOrdinal()) {
1480       Result = Entry32[Index].getOrdinal();
1481       return std::error_code();
1482     }
1483     RVA = Entry32[Index].getHintNameRVA();
1484   } else {
1485     if (Entry64[Index].isOrdinal()) {
1486       Result = Entry64[Index].getOrdinal();
1487       return std::error_code();
1488     }
1489     RVA = Entry64[Index].getHintNameRVA();
1490   }
1491   uintptr_t IntPtr = 0;
1492   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1493     return EC;
1494   Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1495   return std::error_code();
1496 }
1497 
1498 ErrorOr<std::unique_ptr<COFFObjectFile>>
1499 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1500   std::error_code EC;
1501   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1502   if (EC)
1503     return EC;
1504   return std::move(Ret);
1505 }
1506 
1507 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1508   return Header == Other.Header && Index == Other.Index;
1509 }
1510 
1511 void BaseRelocRef::moveNext() {
1512   // Header->BlockSize is the size of the current block, including the
1513   // size of the header itself.
1514   uint32_t Size = sizeof(*Header) +
1515       sizeof(coff_base_reloc_block_entry) * (Index + 1);
1516   if (Size == Header->BlockSize) {
1517     // .reloc contains a list of base relocation blocks. Each block
1518     // consists of the header followed by entries. The header contains
1519     // how many entories will follow. When we reach the end of the
1520     // current block, proceed to the next block.
1521     Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1522         reinterpret_cast<const uint8_t *>(Header) + Size);
1523     Index = 0;
1524   } else {
1525     ++Index;
1526   }
1527 }
1528 
1529 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1530   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1531   Type = Entry[Index].getType();
1532   return std::error_code();
1533 }
1534 
1535 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1536   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1537   Result = Header->PageRVA + Entry[Index].getOffset();
1538   return std::error_code();
1539 }
1540