xref: /llvm-project/llvm/lib/Object/COFFObjectFile.cpp (revision 776c6828a584ac7ba04bc50ad1b9cd2de21c55fc)
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 Expected<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 errorCodeToError(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 
533   // Find the section that contains the RVA. This is needed because the RVA is
534   // the import table's memory address which is different from its file offset.
535   uintptr_t IntPtr = 0;
536   if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
537     return EC;
538   if (std::error_code EC = checkOffset(Data, IntPtr, DataEntry->Size))
539     return EC;
540   ImportDirectory = reinterpret_cast<
541       const coff_import_directory_table_entry *>(IntPtr);
542   return std::error_code();
543 }
544 
545 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
546 std::error_code COFFObjectFile::initDelayImportTablePtr() {
547   const data_directory *DataEntry;
548   if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
549     return std::error_code();
550   if (DataEntry->RelativeVirtualAddress == 0)
551     return std::error_code();
552 
553   uint32_t RVA = DataEntry->RelativeVirtualAddress;
554   NumberOfDelayImportDirectory = DataEntry->Size /
555       sizeof(delay_import_directory_table_entry) - 1;
556 
557   uintptr_t IntPtr = 0;
558   if (std::error_code EC = getRvaPtr(RVA, IntPtr))
559     return EC;
560   DelayImportDirectory = reinterpret_cast<
561       const delay_import_directory_table_entry *>(IntPtr);
562   return std::error_code();
563 }
564 
565 // Find the export table.
566 std::error_code COFFObjectFile::initExportTablePtr() {
567   // First, we get the RVA of the export table. If the file lacks a pointer to
568   // the export table, do nothing.
569   const data_directory *DataEntry;
570   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
571     return std::error_code();
572 
573   // Do nothing if the pointer to export table is NULL.
574   if (DataEntry->RelativeVirtualAddress == 0)
575     return std::error_code();
576 
577   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
578   uintptr_t IntPtr = 0;
579   if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
580     return EC;
581   ExportDirectory =
582       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
583   return std::error_code();
584 }
585 
586 std::error_code COFFObjectFile::initBaseRelocPtr() {
587   const data_directory *DataEntry;
588   if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
589     return std::error_code();
590   if (DataEntry->RelativeVirtualAddress == 0)
591     return std::error_code();
592 
593   uintptr_t IntPtr = 0;
594   if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
595     return EC;
596   BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
597       IntPtr);
598   BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
599       IntPtr + DataEntry->Size);
600   return std::error_code();
601 }
602 
603 std::error_code COFFObjectFile::initDebugDirectoryPtr() {
604   // Get the RVA of the debug directory. Do nothing if it does not exist.
605   const data_directory *DataEntry;
606   if (getDataDirectory(COFF::DEBUG_DIRECTORY, DataEntry))
607     return std::error_code();
608 
609   // Do nothing if the RVA is NULL.
610   if (DataEntry->RelativeVirtualAddress == 0)
611     return std::error_code();
612 
613   // Check that the size is a multiple of the entry size.
614   if (DataEntry->Size % sizeof(debug_directory) != 0)
615     return object_error::parse_failed;
616 
617   uintptr_t IntPtr = 0;
618   if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
619     return EC;
620   DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
621   if (std::error_code EC = getRvaPtr(
622           DataEntry->RelativeVirtualAddress + DataEntry->Size, IntPtr))
623     return EC;
624   DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(IntPtr);
625   return std::error_code();
626 }
627 
628 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
629     : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
630       COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
631       DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
632       SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
633       ImportDirectory(nullptr),
634       DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
635       ExportDirectory(nullptr), BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
636       DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr) {
637   // Check that we at least have enough room for a header.
638   if (!checkSize(Data, EC, sizeof(coff_file_header)))
639     return;
640 
641   // The current location in the file where we are looking at.
642   uint64_t CurPtr = 0;
643 
644   // PE header is optional and is present only in executables. If it exists,
645   // it is placed right after COFF header.
646   bool HasPEHeader = false;
647 
648   // Check if this is a PE/COFF file.
649   if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
650     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
651     // PE signature to find 'normal' COFF header.
652     const auto *DH = reinterpret_cast<const dos_header *>(base());
653     if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
654       CurPtr = DH->AddressOfNewExeHeader;
655       // Check the PE magic bytes. ("PE\0\0")
656       if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
657         EC = object_error::parse_failed;
658         return;
659       }
660       CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
661       HasPEHeader = true;
662     }
663   }
664 
665   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
666     return;
667 
668   // It might be a bigobj file, let's check.  Note that COFF bigobj and COFF
669   // import libraries share a common prefix but bigobj is more restrictive.
670   if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
671       COFFHeader->NumberOfSections == uint16_t(0xffff) &&
672       checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
673     if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
674       return;
675 
676     // Verify that we are dealing with bigobj.
677     if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
678         std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
679                     sizeof(COFF::BigObjMagic)) == 0) {
680       COFFHeader = nullptr;
681       CurPtr += sizeof(coff_bigobj_file_header);
682     } else {
683       // It's not a bigobj.
684       COFFBigObjHeader = nullptr;
685     }
686   }
687   if (COFFHeader) {
688     // The prior checkSize call may have failed.  This isn't a hard error
689     // because we were just trying to sniff out bigobj.
690     EC = std::error_code();
691     CurPtr += sizeof(coff_file_header);
692 
693     if (COFFHeader->isImportLibrary())
694       return;
695   }
696 
697   if (HasPEHeader) {
698     const pe32_header *Header;
699     if ((EC = getObject(Header, Data, base() + CurPtr)))
700       return;
701 
702     const uint8_t *DataDirAddr;
703     uint64_t DataDirSize;
704     if (Header->Magic == COFF::PE32Header::PE32) {
705       PE32Header = Header;
706       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
707       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
708     } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
709       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
710       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
711       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
712     } else {
713       // It's neither PE32 nor PE32+.
714       EC = object_error::parse_failed;
715       return;
716     }
717     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
718       return;
719   }
720 
721   CurPtr += COFFHeader->SizeOfOptionalHeader;
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   if (!ImportDirectory)
775     return import_directory_end();
776   if (ImportDirectory->isNull())
777     return import_directory_end();
778   return import_directory_iterator(
779       ImportDirectoryEntryRef(ImportDirectory, 0, this));
780 }
781 
782 import_directory_iterator COFFObjectFile::import_directory_end() const {
783   return import_directory_iterator(
784       ImportDirectoryEntryRef(nullptr, -1, this));
785 }
786 
787 delay_import_directory_iterator
788 COFFObjectFile::delay_import_directory_begin() const {
789   return delay_import_directory_iterator(
790       DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
791 }
792 
793 delay_import_directory_iterator
794 COFFObjectFile::delay_import_directory_end() const {
795   return delay_import_directory_iterator(
796       DelayImportDirectoryEntryRef(
797           DelayImportDirectory, NumberOfDelayImportDirectory, this));
798 }
799 
800 export_directory_iterator COFFObjectFile::export_directory_begin() const {
801   return export_directory_iterator(
802       ExportDirectoryEntryRef(ExportDirectory, 0, this));
803 }
804 
805 export_directory_iterator COFFObjectFile::export_directory_end() const {
806   if (!ExportDirectory)
807     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
808   ExportDirectoryEntryRef Ref(ExportDirectory,
809                               ExportDirectory->AddressTableEntries, this);
810   return export_directory_iterator(Ref);
811 }
812 
813 section_iterator COFFObjectFile::section_begin() const {
814   DataRefImpl Ret;
815   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
816   return section_iterator(SectionRef(Ret, this));
817 }
818 
819 section_iterator COFFObjectFile::section_end() const {
820   DataRefImpl Ret;
821   int NumSections =
822       COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
823   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
824   return section_iterator(SectionRef(Ret, this));
825 }
826 
827 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
828   return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
829 }
830 
831 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
832   return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
833 }
834 
835 uint8_t COFFObjectFile::getBytesInAddress() const {
836   return getArch() == Triple::x86_64 ? 8 : 4;
837 }
838 
839 StringRef COFFObjectFile::getFileFormatName() const {
840   switch(getMachine()) {
841   case COFF::IMAGE_FILE_MACHINE_I386:
842     return "COFF-i386";
843   case COFF::IMAGE_FILE_MACHINE_AMD64:
844     return "COFF-x86-64";
845   case COFF::IMAGE_FILE_MACHINE_ARMNT:
846     return "COFF-ARM";
847   case COFF::IMAGE_FILE_MACHINE_ARM64:
848     return "COFF-ARM64";
849   default:
850     return "COFF-<unknown arch>";
851   }
852 }
853 
854 unsigned COFFObjectFile::getArch() const {
855   switch (getMachine()) {
856   case COFF::IMAGE_FILE_MACHINE_I386:
857     return Triple::x86;
858   case COFF::IMAGE_FILE_MACHINE_AMD64:
859     return Triple::x86_64;
860   case COFF::IMAGE_FILE_MACHINE_ARMNT:
861     return Triple::thumb;
862   case COFF::IMAGE_FILE_MACHINE_ARM64:
863     return Triple::aarch64;
864   default:
865     return Triple::UnknownArch;
866   }
867 }
868 
869 iterator_range<import_directory_iterator>
870 COFFObjectFile::import_directories() const {
871   return make_range(import_directory_begin(), import_directory_end());
872 }
873 
874 iterator_range<delay_import_directory_iterator>
875 COFFObjectFile::delay_import_directories() const {
876   return make_range(delay_import_directory_begin(),
877                     delay_import_directory_end());
878 }
879 
880 iterator_range<export_directory_iterator>
881 COFFObjectFile::export_directories() const {
882   return make_range(export_directory_begin(), export_directory_end());
883 }
884 
885 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
886   return make_range(base_reloc_begin(), base_reloc_end());
887 }
888 
889 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
890   Res = PE32Header;
891   return std::error_code();
892 }
893 
894 std::error_code
895 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
896   Res = PE32PlusHeader;
897   return std::error_code();
898 }
899 
900 std::error_code
901 COFFObjectFile::getDataDirectory(uint32_t Index,
902                                  const data_directory *&Res) const {
903   // Error if if there's no data directory or the index is out of range.
904   if (!DataDirectory) {
905     Res = nullptr;
906     return object_error::parse_failed;
907   }
908   assert(PE32Header || PE32PlusHeader);
909   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
910                                : PE32PlusHeader->NumberOfRvaAndSize;
911   if (Index >= NumEnt) {
912     Res = nullptr;
913     return object_error::parse_failed;
914   }
915   Res = &DataDirectory[Index];
916   return std::error_code();
917 }
918 
919 std::error_code COFFObjectFile::getSection(int32_t Index,
920                                            const coff_section *&Result) const {
921   Result = nullptr;
922   if (COFF::isReservedSectionNumber(Index))
923     return std::error_code();
924   if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
925     // We already verified the section table data, so no need to check again.
926     Result = SectionTable + (Index - 1);
927     return std::error_code();
928   }
929   return object_error::parse_failed;
930 }
931 
932 std::error_code COFFObjectFile::getString(uint32_t Offset,
933                                           StringRef &Result) const {
934   if (StringTableSize <= 4)
935     // Tried to get a string from an empty string table.
936     return object_error::parse_failed;
937   if (Offset >= StringTableSize)
938     return object_error::unexpected_eof;
939   Result = StringRef(StringTable + Offset);
940   return std::error_code();
941 }
942 
943 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
944                                               StringRef &Res) const {
945   return getSymbolName(Symbol.getGeneric(), Res);
946 }
947 
948 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
949                                               StringRef &Res) const {
950   // Check for string table entry. First 4 bytes are 0.
951   if (Symbol->Name.Offset.Zeroes == 0) {
952     if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
953       return EC;
954     return std::error_code();
955   }
956 
957   if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
958     // Null terminated, let ::strlen figure out the length.
959     Res = StringRef(Symbol->Name.ShortName);
960   else
961     // Not null terminated, use all 8 bytes.
962     Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
963   return std::error_code();
964 }
965 
966 ArrayRef<uint8_t>
967 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
968   const uint8_t *Aux = nullptr;
969 
970   size_t SymbolSize = getSymbolTableEntrySize();
971   if (Symbol.getNumberOfAuxSymbols() > 0) {
972     // AUX data comes immediately after the symbol in COFF
973     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
974 # ifndef NDEBUG
975     // Verify that the Aux symbol points to a valid entry in the symbol table.
976     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
977     if (Offset < getPointerToSymbolTable() ||
978         Offset >=
979             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
980       report_fatal_error("Aux Symbol data was outside of symbol table.");
981 
982     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
983            "Aux Symbol data did not point to the beginning of a symbol");
984 # endif
985   }
986   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
987 }
988 
989 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
990                                                StringRef &Res) const {
991   StringRef Name;
992   if (Sec->Name[COFF::NameSize - 1] == 0)
993     // Null terminated, let ::strlen figure out the length.
994     Name = Sec->Name;
995   else
996     // Not null terminated, use all 8 bytes.
997     Name = StringRef(Sec->Name, COFF::NameSize);
998 
999   // Check for string table entry. First byte is '/'.
1000   if (Name.startswith("/")) {
1001     uint32_t Offset;
1002     if (Name.startswith("//")) {
1003       if (decodeBase64StringEntry(Name.substr(2), Offset))
1004         return object_error::parse_failed;
1005     } else {
1006       if (Name.substr(1).getAsInteger(10, Offset))
1007         return object_error::parse_failed;
1008     }
1009     if (std::error_code EC = getString(Offset, Name))
1010       return EC;
1011   }
1012 
1013   Res = Name;
1014   return std::error_code();
1015 }
1016 
1017 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
1018   // SizeOfRawData and VirtualSize change what they represent depending on
1019   // whether or not we have an executable image.
1020   //
1021   // For object files, SizeOfRawData contains the size of section's data;
1022   // VirtualSize should be zero but isn't due to buggy COFF writers.
1023   //
1024   // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
1025   // actual section size is in VirtualSize.  It is possible for VirtualSize to
1026   // be greater than SizeOfRawData; the contents past that point should be
1027   // considered to be zero.
1028   if (getDOSHeader())
1029     return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
1030   return Sec->SizeOfRawData;
1031 }
1032 
1033 std::error_code
1034 COFFObjectFile::getSectionContents(const coff_section *Sec,
1035                                    ArrayRef<uint8_t> &Res) const {
1036   // In COFF, a virtual section won't have any in-file
1037   // content, so the file pointer to the content will be zero.
1038   if (Sec->PointerToRawData == 0)
1039     return object_error::parse_failed;
1040   // The only thing that we need to verify is that the contents is contained
1041   // within the file bounds. We don't need to make sure it doesn't cover other
1042   // data, as there's nothing that says that is not allowed.
1043   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1044   uint32_t SectionSize = getSectionSize(Sec);
1045   if (checkOffset(Data, ConStart, SectionSize))
1046     return object_error::parse_failed;
1047   Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1048   return std::error_code();
1049 }
1050 
1051 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1052   return reinterpret_cast<const coff_relocation*>(Rel.p);
1053 }
1054 
1055 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1056   Rel.p = reinterpret_cast<uintptr_t>(
1057             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1058 }
1059 
1060 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
1061   const coff_relocation *R = toRel(Rel);
1062   return R->VirtualAddress;
1063 }
1064 
1065 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1066   const coff_relocation *R = toRel(Rel);
1067   DataRefImpl Ref;
1068   if (R->SymbolTableIndex >= getNumberOfSymbols())
1069     return symbol_end();
1070   if (SymbolTable16)
1071     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1072   else if (SymbolTable32)
1073     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1074   else
1075     llvm_unreachable("no symbol table pointer!");
1076   return symbol_iterator(SymbolRef(Ref, this));
1077 }
1078 
1079 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
1080   const coff_relocation* R = toRel(Rel);
1081   return R->Type;
1082 }
1083 
1084 const coff_section *
1085 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1086   return toSec(Section.getRawDataRefImpl());
1087 }
1088 
1089 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1090   if (SymbolTable16)
1091     return toSymb<coff_symbol16>(Ref);
1092   if (SymbolTable32)
1093     return toSymb<coff_symbol32>(Ref);
1094   llvm_unreachable("no symbol table pointer!");
1095 }
1096 
1097 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1098   return getCOFFSymbol(Symbol.getRawDataRefImpl());
1099 }
1100 
1101 const coff_relocation *
1102 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1103   return toRel(Reloc.getRawDataRefImpl());
1104 }
1105 
1106 iterator_range<const coff_relocation *>
1107 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1108   const coff_relocation *I = getFirstReloc(Sec, Data, base());
1109   const coff_relocation *E = I;
1110   if (I)
1111     E += getNumberOfRelocations(Sec, Data, base());
1112   return make_range(I, E);
1113 }
1114 
1115 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
1116   case COFF::reloc_type:                                                       \
1117     Res = #reloc_type;                                                         \
1118     break;
1119 
1120 void COFFObjectFile::getRelocationTypeName(
1121     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1122   const coff_relocation *Reloc = toRel(Rel);
1123   StringRef Res;
1124   switch (getMachine()) {
1125   case COFF::IMAGE_FILE_MACHINE_AMD64:
1126     switch (Reloc->Type) {
1127     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1128     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1129     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1130     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1131     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1132     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1133     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1134     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1135     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1136     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1137     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1138     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1139     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1140     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1141     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1142     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1143     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1144     default:
1145       Res = "Unknown";
1146     }
1147     break;
1148   case COFF::IMAGE_FILE_MACHINE_ARMNT:
1149     switch (Reloc->Type) {
1150     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1151     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1152     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1153     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1154     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1155     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1156     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1157     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1158     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1159     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1160     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1161     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1162     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1163     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1164     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1165     default:
1166       Res = "Unknown";
1167     }
1168     break;
1169   case COFF::IMAGE_FILE_MACHINE_I386:
1170     switch (Reloc->Type) {
1171     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1172     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1173     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1174     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1175     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1176     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1177     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1178     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1179     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1180     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1181     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1182     default:
1183       Res = "Unknown";
1184     }
1185     break;
1186   default:
1187     Res = "Unknown";
1188   }
1189   Result.append(Res.begin(), Res.end());
1190 }
1191 
1192 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1193 
1194 bool COFFObjectFile::isRelocatableObject() const {
1195   return !DataDirectory;
1196 }
1197 
1198 bool ImportDirectoryEntryRef::
1199 operator==(const ImportDirectoryEntryRef &Other) const {
1200   return ImportTable == Other.ImportTable && Index == Other.Index;
1201 }
1202 
1203 void ImportDirectoryEntryRef::moveNext() {
1204   ++Index;
1205   if (ImportTable[Index].isNull()) {
1206     Index = -1;
1207     ImportTable = nullptr;
1208   }
1209 }
1210 
1211 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1212     const coff_import_directory_table_entry *&Result) const {
1213   return getObject(Result, OwningObject->Data, ImportTable + Index);
1214 }
1215 
1216 static imported_symbol_iterator
1217 makeImportedSymbolIterator(const COFFObjectFile *Object,
1218                            uintptr_t Ptr, int Index) {
1219   if (Object->getBytesInAddress() == 4) {
1220     auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1221     return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1222   }
1223   auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1224   return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1225 }
1226 
1227 static imported_symbol_iterator
1228 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1229   uintptr_t IntPtr = 0;
1230   Object->getRvaPtr(RVA, IntPtr);
1231   return makeImportedSymbolIterator(Object, IntPtr, 0);
1232 }
1233 
1234 static imported_symbol_iterator
1235 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1236   uintptr_t IntPtr = 0;
1237   Object->getRvaPtr(RVA, IntPtr);
1238   // Forward the pointer to the last entry which is null.
1239   int Index = 0;
1240   if (Object->getBytesInAddress() == 4) {
1241     auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1242     while (*Entry++)
1243       ++Index;
1244   } else {
1245     auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1246     while (*Entry++)
1247       ++Index;
1248   }
1249   return makeImportedSymbolIterator(Object, IntPtr, Index);
1250 }
1251 
1252 imported_symbol_iterator
1253 ImportDirectoryEntryRef::imported_symbol_begin() const {
1254   return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
1255                              OwningObject);
1256 }
1257 
1258 imported_symbol_iterator
1259 ImportDirectoryEntryRef::imported_symbol_end() const {
1260   return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
1261                            OwningObject);
1262 }
1263 
1264 iterator_range<imported_symbol_iterator>
1265 ImportDirectoryEntryRef::imported_symbols() const {
1266   return make_range(imported_symbol_begin(), imported_symbol_end());
1267 }
1268 
1269 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
1270   return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1271                              OwningObject);
1272 }
1273 
1274 imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
1275   return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1276                            OwningObject);
1277 }
1278 
1279 iterator_range<imported_symbol_iterator>
1280 ImportDirectoryEntryRef::lookup_table_symbols() const {
1281   return make_range(lookup_table_begin(), lookup_table_end());
1282 }
1283 
1284 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1285   uintptr_t IntPtr = 0;
1286   if (std::error_code EC =
1287           OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1288     return EC;
1289   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1290   return std::error_code();
1291 }
1292 
1293 std::error_code
1294 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t  &Result) const {
1295   Result = ImportTable[Index].ImportLookupTableRVA;
1296   return std::error_code();
1297 }
1298 
1299 std::error_code
1300 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1301   Result = ImportTable[Index].ImportAddressTableRVA;
1302   return std::error_code();
1303 }
1304 
1305 bool DelayImportDirectoryEntryRef::
1306 operator==(const DelayImportDirectoryEntryRef &Other) const {
1307   return Table == Other.Table && Index == Other.Index;
1308 }
1309 
1310 void DelayImportDirectoryEntryRef::moveNext() {
1311   ++Index;
1312 }
1313 
1314 imported_symbol_iterator
1315 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1316   return importedSymbolBegin(Table[Index].DelayImportNameTable,
1317                              OwningObject);
1318 }
1319 
1320 imported_symbol_iterator
1321 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1322   return importedSymbolEnd(Table[Index].DelayImportNameTable,
1323                            OwningObject);
1324 }
1325 
1326 iterator_range<imported_symbol_iterator>
1327 DelayImportDirectoryEntryRef::imported_symbols() const {
1328   return make_range(imported_symbol_begin(), imported_symbol_end());
1329 }
1330 
1331 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1332   uintptr_t IntPtr = 0;
1333   if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1334     return EC;
1335   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1336   return std::error_code();
1337 }
1338 
1339 std::error_code DelayImportDirectoryEntryRef::
1340 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1341   Result = Table;
1342   return std::error_code();
1343 }
1344 
1345 std::error_code DelayImportDirectoryEntryRef::
1346 getImportAddress(int AddrIndex, uint64_t &Result) const {
1347   uint32_t RVA = Table[Index].DelayImportAddressTable +
1348       AddrIndex * (OwningObject->is64() ? 8 : 4);
1349   uintptr_t IntPtr = 0;
1350   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1351     return EC;
1352   if (OwningObject->is64())
1353     Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1354   else
1355     Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1356   return std::error_code();
1357 }
1358 
1359 bool ExportDirectoryEntryRef::
1360 operator==(const ExportDirectoryEntryRef &Other) const {
1361   return ExportTable == Other.ExportTable && Index == Other.Index;
1362 }
1363 
1364 void ExportDirectoryEntryRef::moveNext() {
1365   ++Index;
1366 }
1367 
1368 // Returns the name of the current export symbol. If the symbol is exported only
1369 // by ordinal, the empty string is set as a result.
1370 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1371   uintptr_t IntPtr = 0;
1372   if (std::error_code EC =
1373           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1374     return EC;
1375   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1376   return std::error_code();
1377 }
1378 
1379 // Returns the starting ordinal number.
1380 std::error_code
1381 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1382   Result = ExportTable->OrdinalBase;
1383   return std::error_code();
1384 }
1385 
1386 // Returns the export ordinal of the current export symbol.
1387 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1388   Result = ExportTable->OrdinalBase + Index;
1389   return std::error_code();
1390 }
1391 
1392 // Returns the address of the current export symbol.
1393 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1394   uintptr_t IntPtr = 0;
1395   if (std::error_code EC =
1396           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1397     return EC;
1398   const export_address_table_entry *entry =
1399       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1400   Result = entry[Index].ExportRVA;
1401   return std::error_code();
1402 }
1403 
1404 // Returns the name of the current export symbol. If the symbol is exported only
1405 // by ordinal, the empty string is set as a result.
1406 std::error_code
1407 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1408   uintptr_t IntPtr = 0;
1409   if (std::error_code EC =
1410           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1411     return EC;
1412   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1413 
1414   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1415   int Offset = 0;
1416   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1417        I < E; ++I, ++Offset) {
1418     if (*I != Index)
1419       continue;
1420     if (std::error_code EC =
1421             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1422       return EC;
1423     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1424     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1425       return EC;
1426     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1427     return std::error_code();
1428   }
1429   Result = "";
1430   return std::error_code();
1431 }
1432 
1433 std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1434   const data_directory *DataEntry;
1435   if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
1436     return EC;
1437   uint32_t RVA;
1438   if (auto EC = getExportRVA(RVA))
1439     return EC;
1440   uint32_t Begin = DataEntry->RelativeVirtualAddress;
1441   uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1442   Result = (Begin <= RVA && RVA < End);
1443   return std::error_code();
1444 }
1445 
1446 std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1447   uint32_t RVA;
1448   if (auto EC = getExportRVA(RVA))
1449     return EC;
1450   uintptr_t IntPtr = 0;
1451   if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1452     return EC;
1453   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1454   return std::error_code();
1455 }
1456 
1457 bool ImportedSymbolRef::
1458 operator==(const ImportedSymbolRef &Other) const {
1459   return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1460       && Index == Other.Index;
1461 }
1462 
1463 void ImportedSymbolRef::moveNext() {
1464   ++Index;
1465 }
1466 
1467 std::error_code
1468 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1469   uint32_t RVA;
1470   if (Entry32) {
1471     // If a symbol is imported only by ordinal, it has no name.
1472     if (Entry32[Index].isOrdinal())
1473       return std::error_code();
1474     RVA = Entry32[Index].getHintNameRVA();
1475   } else {
1476     if (Entry64[Index].isOrdinal())
1477       return std::error_code();
1478     RVA = Entry64[Index].getHintNameRVA();
1479   }
1480   uintptr_t IntPtr = 0;
1481   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1482     return EC;
1483   // +2 because the first two bytes is hint.
1484   Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1485   return std::error_code();
1486 }
1487 
1488 std::error_code ImportedSymbolRef::isOrdinal(bool &Result) const {
1489   if (Entry32)
1490     Result = Entry32[Index].isOrdinal();
1491   else
1492     Result = Entry64[Index].isOrdinal();
1493   return std::error_code();
1494 }
1495 
1496 std::error_code ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
1497   if (Entry32)
1498     Result = Entry32[Index].getHintNameRVA();
1499   else
1500     Result = Entry64[Index].getHintNameRVA();
1501   return std::error_code();
1502 }
1503 
1504 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1505   uint32_t RVA;
1506   if (Entry32) {
1507     if (Entry32[Index].isOrdinal()) {
1508       Result = Entry32[Index].getOrdinal();
1509       return std::error_code();
1510     }
1511     RVA = Entry32[Index].getHintNameRVA();
1512   } else {
1513     if (Entry64[Index].isOrdinal()) {
1514       Result = Entry64[Index].getOrdinal();
1515       return std::error_code();
1516     }
1517     RVA = Entry64[Index].getHintNameRVA();
1518   }
1519   uintptr_t IntPtr = 0;
1520   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1521     return EC;
1522   Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1523   return std::error_code();
1524 }
1525 
1526 ErrorOr<std::unique_ptr<COFFObjectFile>>
1527 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1528   std::error_code EC;
1529   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1530   if (EC)
1531     return EC;
1532   return std::move(Ret);
1533 }
1534 
1535 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1536   return Header == Other.Header && Index == Other.Index;
1537 }
1538 
1539 void BaseRelocRef::moveNext() {
1540   // Header->BlockSize is the size of the current block, including the
1541   // size of the header itself.
1542   uint32_t Size = sizeof(*Header) +
1543       sizeof(coff_base_reloc_block_entry) * (Index + 1);
1544   if (Size == Header->BlockSize) {
1545     // .reloc contains a list of base relocation blocks. Each block
1546     // consists of the header followed by entries. The header contains
1547     // how many entories will follow. When we reach the end of the
1548     // current block, proceed to the next block.
1549     Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1550         reinterpret_cast<const uint8_t *>(Header) + Size);
1551     Index = 0;
1552   } else {
1553     ++Index;
1554   }
1555 }
1556 
1557 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1558   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1559   Type = Entry[Index].getType();
1560   return std::error_code();
1561 }
1562 
1563 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1564   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1565   Result = Header->PageRVA + Entry[Index].getOffset();
1566   return std::error_code();
1567 }
1568