xref: /llvm-project/llvm/lib/Object/COFFObjectFile.cpp (revision 6a6185fd78a61eb2a2f05beefe17b67feed86de0)
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::isSectionText(DataRefImpl Ref) const {
296   const coff_section *Sec = toSec(Ref);
297   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
298 }
299 
300 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
301   const coff_section *Sec = toSec(Ref);
302   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
303 }
304 
305 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
306   const coff_section *Sec = toSec(Ref);
307   const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
308                             COFF::IMAGE_SCN_MEM_READ |
309                             COFF::IMAGE_SCN_MEM_WRITE;
310   return (Sec->Characteristics & BssFlags) == BssFlags;
311 }
312 
313 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
314   uintptr_t Offset =
315       uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
316   assert((Offset % sizeof(coff_section)) == 0);
317   return (Offset / sizeof(coff_section)) + 1;
318 }
319 
320 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
321   const coff_section *Sec = toSec(Ref);
322   // In COFF, a virtual section won't have any in-file
323   // content, so the file pointer to the content will be zero.
324   return Sec->PointerToRawData == 0;
325 }
326 
327 static uint32_t getNumberOfRelocations(const coff_section *Sec,
328                                        MemoryBufferRef M, const uint8_t *base) {
329   // The field for the number of relocations in COFF section table is only
330   // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
331   // NumberOfRelocations field, and the actual relocation count is stored in the
332   // VirtualAddress field in the first relocation entry.
333   if (Sec->hasExtendedRelocations()) {
334     const coff_relocation *FirstReloc;
335     if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
336         base + Sec->PointerToRelocations)))
337       return 0;
338     // -1 to exclude this first relocation entry.
339     return FirstReloc->VirtualAddress - 1;
340   }
341   return Sec->NumberOfRelocations;
342 }
343 
344 static const coff_relocation *
345 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
346   uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
347   if (!NumRelocs)
348     return nullptr;
349   auto begin = reinterpret_cast<const coff_relocation *>(
350       Base + Sec->PointerToRelocations);
351   if (Sec->hasExtendedRelocations()) {
352     // Skip the first relocation entry repurposed to store the number of
353     // relocations.
354     begin++;
355   }
356   if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
357     return nullptr;
358   return begin;
359 }
360 
361 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
362   const coff_section *Sec = toSec(Ref);
363   const coff_relocation *begin = getFirstReloc(Sec, Data, base());
364   if (begin && Sec->VirtualAddress != 0)
365     report_fatal_error("Sections with relocations should have an address of 0");
366   DataRefImpl Ret;
367   Ret.p = reinterpret_cast<uintptr_t>(begin);
368   return relocation_iterator(RelocationRef(Ret, this));
369 }
370 
371 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
372   const coff_section *Sec = toSec(Ref);
373   const coff_relocation *I = getFirstReloc(Sec, Data, base());
374   if (I)
375     I += getNumberOfRelocations(Sec, Data, base());
376   DataRefImpl Ret;
377   Ret.p = reinterpret_cast<uintptr_t>(I);
378   return relocation_iterator(RelocationRef(Ret, this));
379 }
380 
381 // Initialize the pointer to the symbol table.
382 std::error_code COFFObjectFile::initSymbolTablePtr() {
383   if (COFFHeader)
384     if (std::error_code EC = getObject(
385             SymbolTable16, Data, base() + getPointerToSymbolTable(),
386             (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
387       return EC;
388 
389   if (COFFBigObjHeader)
390     if (std::error_code EC = getObject(
391             SymbolTable32, Data, base() + getPointerToSymbolTable(),
392             (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
393       return EC;
394 
395   // Find string table. The first four byte of the string table contains the
396   // total size of the string table, including the size field itself. If the
397   // string table is empty, the value of the first four byte would be 4.
398   uint32_t StringTableOffset = getPointerToSymbolTable() +
399                                getNumberOfSymbols() * getSymbolTableEntrySize();
400   const uint8_t *StringTableAddr = base() + StringTableOffset;
401   const ulittle32_t *StringTableSizePtr;
402   if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
403     return EC;
404   StringTableSize = *StringTableSizePtr;
405   if (std::error_code EC =
406           getObject(StringTable, Data, StringTableAddr, StringTableSize))
407     return EC;
408 
409   // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
410   // tools like cvtres write a size of 0 for an empty table instead of 4.
411   if (StringTableSize < 4)
412       StringTableSize = 4;
413 
414   // Check that the string table is null terminated if has any in it.
415   if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
416     return  object_error::parse_failed;
417   return std::error_code();
418 }
419 
420 uint64_t COFFObjectFile::getImageBase() const {
421   if (PE32Header)
422     return PE32Header->ImageBase;
423   else if (PE32PlusHeader)
424     return PE32PlusHeader->ImageBase;
425   // This actually comes up in practice.
426   return 0;
427 }
428 
429 // Returns the file offset for the given VA.
430 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
431   uint64_t ImageBase = getImageBase();
432   uint64_t Rva = Addr - ImageBase;
433   assert(Rva <= UINT32_MAX);
434   return getRvaPtr((uint32_t)Rva, Res);
435 }
436 
437 // Returns the file offset for the given RVA.
438 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
439   for (const SectionRef &S : sections()) {
440     const coff_section *Section = getCOFFSection(S);
441     uint32_t SectionStart = Section->VirtualAddress;
442     uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
443     if (SectionStart <= Addr && Addr < SectionEnd) {
444       uint32_t Offset = Addr - SectionStart;
445       Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
446       return std::error_code();
447     }
448   }
449   return object_error::parse_failed;
450 }
451 
452 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
453 // table entry.
454 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
455                                             StringRef &Name) const {
456   uintptr_t IntPtr = 0;
457   if (std::error_code EC = getRvaPtr(Rva, IntPtr))
458     return EC;
459   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
460   Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
461   Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
462   return std::error_code();
463 }
464 
465 // Find the import table.
466 std::error_code COFFObjectFile::initImportTablePtr() {
467   // First, we get the RVA of the import table. If the file lacks a pointer to
468   // the import table, do nothing.
469   const data_directory *DataEntry;
470   if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
471     return std::error_code();
472 
473   // Do nothing if the pointer to import table is NULL.
474   if (DataEntry->RelativeVirtualAddress == 0)
475     return std::error_code();
476 
477   uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
478   // -1 because the last entry is the null entry.
479   NumberOfImportDirectory = DataEntry->Size /
480       sizeof(import_directory_table_entry) - 1;
481 
482   // Find the section that contains the RVA. This is needed because the RVA is
483   // the import table's memory address which is different from its file offset.
484   uintptr_t IntPtr = 0;
485   if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
486     return EC;
487   ImportDirectory = reinterpret_cast<
488       const import_directory_table_entry *>(IntPtr);
489   return std::error_code();
490 }
491 
492 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
493 std::error_code COFFObjectFile::initDelayImportTablePtr() {
494   const data_directory *DataEntry;
495   if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
496     return std::error_code();
497   if (DataEntry->RelativeVirtualAddress == 0)
498     return std::error_code();
499 
500   uint32_t RVA = DataEntry->RelativeVirtualAddress;
501   NumberOfDelayImportDirectory = DataEntry->Size /
502       sizeof(delay_import_directory_table_entry) - 1;
503 
504   uintptr_t IntPtr = 0;
505   if (std::error_code EC = getRvaPtr(RVA, IntPtr))
506     return EC;
507   DelayImportDirectory = reinterpret_cast<
508       const delay_import_directory_table_entry *>(IntPtr);
509   return std::error_code();
510 }
511 
512 // Find the export table.
513 std::error_code COFFObjectFile::initExportTablePtr() {
514   // First, we get the RVA of the export table. If the file lacks a pointer to
515   // the export table, do nothing.
516   const data_directory *DataEntry;
517   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
518     return std::error_code();
519 
520   // Do nothing if the pointer to export table is NULL.
521   if (DataEntry->RelativeVirtualAddress == 0)
522     return std::error_code();
523 
524   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
525   uintptr_t IntPtr = 0;
526   if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
527     return EC;
528   ExportDirectory =
529       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
530   return std::error_code();
531 }
532 
533 std::error_code COFFObjectFile::initBaseRelocPtr() {
534   const data_directory *DataEntry;
535   if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
536     return std::error_code();
537   if (DataEntry->RelativeVirtualAddress == 0)
538     return std::error_code();
539 
540   uintptr_t IntPtr = 0;
541   if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
542     return EC;
543   BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
544       IntPtr);
545   BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
546       IntPtr + DataEntry->Size);
547   return std::error_code();
548 }
549 
550 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
551     : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
552       COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
553       DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
554       SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
555       ImportDirectory(nullptr), NumberOfImportDirectory(0),
556       DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
557       ExportDirectory(nullptr), BaseRelocHeader(nullptr),
558       BaseRelocEnd(nullptr) {
559   // Check that we at least have enough room for a header.
560   if (!checkSize(Data, EC, sizeof(coff_file_header)))
561     return;
562 
563   // The current location in the file where we are looking at.
564   uint64_t CurPtr = 0;
565 
566   // PE header is optional and is present only in executables. If it exists,
567   // it is placed right after COFF header.
568   bool HasPEHeader = false;
569 
570   // Check if this is a PE/COFF file.
571   if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
572     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
573     // PE signature to find 'normal' COFF header.
574     const auto *DH = reinterpret_cast<const dos_header *>(base());
575     if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
576       CurPtr = DH->AddressOfNewExeHeader;
577       // Check the PE magic bytes. ("PE\0\0")
578       if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
579         EC = object_error::parse_failed;
580         return;
581       }
582       CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
583       HasPEHeader = true;
584     }
585   }
586 
587   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
588     return;
589 
590   // It might be a bigobj file, let's check.  Note that COFF bigobj and COFF
591   // import libraries share a common prefix but bigobj is more restrictive.
592   if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
593       COFFHeader->NumberOfSections == uint16_t(0xffff) &&
594       checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
595     if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
596       return;
597 
598     // Verify that we are dealing with bigobj.
599     if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
600         std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
601                     sizeof(COFF::BigObjMagic)) == 0) {
602       COFFHeader = nullptr;
603       CurPtr += sizeof(coff_bigobj_file_header);
604     } else {
605       // It's not a bigobj.
606       COFFBigObjHeader = nullptr;
607     }
608   }
609   if (COFFHeader) {
610     // The prior checkSize call may have failed.  This isn't a hard error
611     // because we were just trying to sniff out bigobj.
612     EC = std::error_code();
613     CurPtr += sizeof(coff_file_header);
614 
615     if (COFFHeader->isImportLibrary())
616       return;
617   }
618 
619   if (HasPEHeader) {
620     const pe32_header *Header;
621     if ((EC = getObject(Header, Data, base() + CurPtr)))
622       return;
623 
624     const uint8_t *DataDirAddr;
625     uint64_t DataDirSize;
626     if (Header->Magic == COFF::PE32Header::PE32) {
627       PE32Header = Header;
628       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
629       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
630     } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
631       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
632       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
633       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
634     } else {
635       // It's neither PE32 nor PE32+.
636       EC = object_error::parse_failed;
637       return;
638     }
639     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
640       return;
641     CurPtr += COFFHeader->SizeOfOptionalHeader;
642   }
643 
644   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
645                       (uint64_t)getNumberOfSections() * sizeof(coff_section))))
646     return;
647 
648   // Initialize the pointer to the symbol table.
649   if (getPointerToSymbolTable() != 0) {
650     if ((EC = initSymbolTablePtr()))
651       return;
652   } else {
653     // We had better not have any symbols if we don't have a symbol table.
654     if (getNumberOfSymbols() != 0) {
655       EC = object_error::parse_failed;
656       return;
657     }
658   }
659 
660   // Initialize the pointer to the beginning of the import table.
661   if ((EC = initImportTablePtr()))
662     return;
663   if ((EC = initDelayImportTablePtr()))
664     return;
665 
666   // Initialize the pointer to the export table.
667   if ((EC = initExportTablePtr()))
668     return;
669 
670   // Initialize the pointer to the base relocation table.
671   if ((EC = initBaseRelocPtr()))
672     return;
673 
674   EC = std::error_code();
675 }
676 
677 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
678   DataRefImpl Ret;
679   Ret.p = getSymbolTable();
680   return basic_symbol_iterator(SymbolRef(Ret, this));
681 }
682 
683 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
684   // The symbol table ends where the string table begins.
685   DataRefImpl Ret;
686   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
687   return basic_symbol_iterator(SymbolRef(Ret, this));
688 }
689 
690 import_directory_iterator COFFObjectFile::import_directory_begin() const {
691   return import_directory_iterator(
692       ImportDirectoryEntryRef(ImportDirectory, 0, this));
693 }
694 
695 import_directory_iterator COFFObjectFile::import_directory_end() const {
696   return import_directory_iterator(
697       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
698 }
699 
700 delay_import_directory_iterator
701 COFFObjectFile::delay_import_directory_begin() const {
702   return delay_import_directory_iterator(
703       DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
704 }
705 
706 delay_import_directory_iterator
707 COFFObjectFile::delay_import_directory_end() const {
708   return delay_import_directory_iterator(
709       DelayImportDirectoryEntryRef(
710           DelayImportDirectory, NumberOfDelayImportDirectory, this));
711 }
712 
713 export_directory_iterator COFFObjectFile::export_directory_begin() const {
714   return export_directory_iterator(
715       ExportDirectoryEntryRef(ExportDirectory, 0, this));
716 }
717 
718 export_directory_iterator COFFObjectFile::export_directory_end() const {
719   if (!ExportDirectory)
720     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
721   ExportDirectoryEntryRef Ref(ExportDirectory,
722                               ExportDirectory->AddressTableEntries, this);
723   return export_directory_iterator(Ref);
724 }
725 
726 section_iterator COFFObjectFile::section_begin() const {
727   DataRefImpl Ret;
728   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
729   return section_iterator(SectionRef(Ret, this));
730 }
731 
732 section_iterator COFFObjectFile::section_end() const {
733   DataRefImpl Ret;
734   int NumSections =
735       COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
736   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
737   return section_iterator(SectionRef(Ret, this));
738 }
739 
740 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
741   return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
742 }
743 
744 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
745   return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
746 }
747 
748 uint8_t COFFObjectFile::getBytesInAddress() const {
749   return getArch() == Triple::x86_64 ? 8 : 4;
750 }
751 
752 StringRef COFFObjectFile::getFileFormatName() const {
753   switch(getMachine()) {
754   case COFF::IMAGE_FILE_MACHINE_I386:
755     return "COFF-i386";
756   case COFF::IMAGE_FILE_MACHINE_AMD64:
757     return "COFF-x86-64";
758   case COFF::IMAGE_FILE_MACHINE_ARMNT:
759     return "COFF-ARM";
760   case COFF::IMAGE_FILE_MACHINE_ARM64:
761     return "COFF-ARM64";
762   default:
763     return "COFF-<unknown arch>";
764   }
765 }
766 
767 unsigned COFFObjectFile::getArch() const {
768   switch (getMachine()) {
769   case COFF::IMAGE_FILE_MACHINE_I386:
770     return Triple::x86;
771   case COFF::IMAGE_FILE_MACHINE_AMD64:
772     return Triple::x86_64;
773   case COFF::IMAGE_FILE_MACHINE_ARMNT:
774     return Triple::thumb;
775   case COFF::IMAGE_FILE_MACHINE_ARM64:
776     return Triple::aarch64;
777   default:
778     return Triple::UnknownArch;
779   }
780 }
781 
782 iterator_range<import_directory_iterator>
783 COFFObjectFile::import_directories() const {
784   return make_range(import_directory_begin(), import_directory_end());
785 }
786 
787 iterator_range<delay_import_directory_iterator>
788 COFFObjectFile::delay_import_directories() const {
789   return make_range(delay_import_directory_begin(),
790                     delay_import_directory_end());
791 }
792 
793 iterator_range<export_directory_iterator>
794 COFFObjectFile::export_directories() const {
795   return make_range(export_directory_begin(), export_directory_end());
796 }
797 
798 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
799   return make_range(base_reloc_begin(), base_reloc_end());
800 }
801 
802 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
803   Res = PE32Header;
804   return std::error_code();
805 }
806 
807 std::error_code
808 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
809   Res = PE32PlusHeader;
810   return std::error_code();
811 }
812 
813 std::error_code
814 COFFObjectFile::getDataDirectory(uint32_t Index,
815                                  const data_directory *&Res) const {
816   // Error if if there's no data directory or the index is out of range.
817   if (!DataDirectory) {
818     Res = nullptr;
819     return object_error::parse_failed;
820   }
821   assert(PE32Header || PE32PlusHeader);
822   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
823                                : PE32PlusHeader->NumberOfRvaAndSize;
824   if (Index >= NumEnt) {
825     Res = nullptr;
826     return object_error::parse_failed;
827   }
828   Res = &DataDirectory[Index];
829   return std::error_code();
830 }
831 
832 std::error_code COFFObjectFile::getSection(int32_t Index,
833                                            const coff_section *&Result) const {
834   Result = nullptr;
835   if (COFF::isReservedSectionNumber(Index))
836     return std::error_code();
837   if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
838     // We already verified the section table data, so no need to check again.
839     Result = SectionTable + (Index - 1);
840     return std::error_code();
841   }
842   return object_error::parse_failed;
843 }
844 
845 std::error_code COFFObjectFile::getString(uint32_t Offset,
846                                           StringRef &Result) const {
847   if (StringTableSize <= 4)
848     // Tried to get a string from an empty string table.
849     return object_error::parse_failed;
850   if (Offset >= StringTableSize)
851     return object_error::unexpected_eof;
852   Result = StringRef(StringTable + Offset);
853   return std::error_code();
854 }
855 
856 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
857                                               StringRef &Res) const {
858   return getSymbolName(Symbol.getGeneric(), Res);
859 }
860 
861 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
862                                               StringRef &Res) const {
863   // Check for string table entry. First 4 bytes are 0.
864   if (Symbol->Name.Offset.Zeroes == 0) {
865     if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
866       return EC;
867     return std::error_code();
868   }
869 
870   if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
871     // Null terminated, let ::strlen figure out the length.
872     Res = StringRef(Symbol->Name.ShortName);
873   else
874     // Not null terminated, use all 8 bytes.
875     Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
876   return std::error_code();
877 }
878 
879 ArrayRef<uint8_t>
880 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
881   const uint8_t *Aux = nullptr;
882 
883   size_t SymbolSize = getSymbolTableEntrySize();
884   if (Symbol.getNumberOfAuxSymbols() > 0) {
885     // AUX data comes immediately after the symbol in COFF
886     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
887 # ifndef NDEBUG
888     // Verify that the Aux symbol points to a valid entry in the symbol table.
889     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
890     if (Offset < getPointerToSymbolTable() ||
891         Offset >=
892             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
893       report_fatal_error("Aux Symbol data was outside of symbol table.");
894 
895     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
896            "Aux Symbol data did not point to the beginning of a symbol");
897 # endif
898   }
899   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
900 }
901 
902 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
903                                                StringRef &Res) const {
904   StringRef Name;
905   if (Sec->Name[COFF::NameSize - 1] == 0)
906     // Null terminated, let ::strlen figure out the length.
907     Name = Sec->Name;
908   else
909     // Not null terminated, use all 8 bytes.
910     Name = StringRef(Sec->Name, COFF::NameSize);
911 
912   // Check for string table entry. First byte is '/'.
913   if (Name.startswith("/")) {
914     uint32_t Offset;
915     if (Name.startswith("//")) {
916       if (decodeBase64StringEntry(Name.substr(2), Offset))
917         return object_error::parse_failed;
918     } else {
919       if (Name.substr(1).getAsInteger(10, Offset))
920         return object_error::parse_failed;
921     }
922     if (std::error_code EC = getString(Offset, Name))
923       return EC;
924   }
925 
926   Res = Name;
927   return std::error_code();
928 }
929 
930 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
931   // SizeOfRawData and VirtualSize change what they represent depending on
932   // whether or not we have an executable image.
933   //
934   // For object files, SizeOfRawData contains the size of section's data;
935   // VirtualSize should be zero but isn't due to buggy COFF writers.
936   //
937   // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
938   // actual section size is in VirtualSize.  It is possible for VirtualSize to
939   // be greater than SizeOfRawData; the contents past that point should be
940   // considered to be zero.
941   if (getDOSHeader())
942     return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
943   return Sec->SizeOfRawData;
944 }
945 
946 std::error_code
947 COFFObjectFile::getSectionContents(const coff_section *Sec,
948                                    ArrayRef<uint8_t> &Res) const {
949   // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
950   // don't do anything interesting for them.
951   assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
952          "BSS sections don't have contents!");
953   // The only thing that we need to verify is that the contents is contained
954   // within the file bounds. We don't need to make sure it doesn't cover other
955   // data, as there's nothing that says that is not allowed.
956   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
957   uint32_t SectionSize = getSectionSize(Sec);
958   if (checkOffset(Data, ConStart, SectionSize))
959     return object_error::parse_failed;
960   Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
961   return std::error_code();
962 }
963 
964 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
965   return reinterpret_cast<const coff_relocation*>(Rel.p);
966 }
967 
968 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
969   Rel.p = reinterpret_cast<uintptr_t>(
970             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
971 }
972 
973 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
974   const coff_relocation *R = toRel(Rel);
975   return R->VirtualAddress;
976 }
977 
978 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
979   const coff_relocation *R = toRel(Rel);
980   DataRefImpl Ref;
981   if (R->SymbolTableIndex >= getNumberOfSymbols())
982     return symbol_end();
983   if (SymbolTable16)
984     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
985   else if (SymbolTable32)
986     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
987   else
988     llvm_unreachable("no symbol table pointer!");
989   return symbol_iterator(SymbolRef(Ref, this));
990 }
991 
992 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
993   const coff_relocation* R = toRel(Rel);
994   return R->Type;
995 }
996 
997 const coff_section *
998 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
999   return toSec(Section.getRawDataRefImpl());
1000 }
1001 
1002 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1003   if (SymbolTable16)
1004     return toSymb<coff_symbol16>(Ref);
1005   if (SymbolTable32)
1006     return toSymb<coff_symbol32>(Ref);
1007   llvm_unreachable("no symbol table pointer!");
1008 }
1009 
1010 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1011   return getCOFFSymbol(Symbol.getRawDataRefImpl());
1012 }
1013 
1014 const coff_relocation *
1015 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1016   return toRel(Reloc.getRawDataRefImpl());
1017 }
1018 
1019 iterator_range<const coff_relocation *>
1020 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1021   const coff_relocation *I = getFirstReloc(Sec, Data, base());
1022   const coff_relocation *E = I;
1023   if (I)
1024     E += getNumberOfRelocations(Sec, Data, base());
1025   return make_range(I, E);
1026 }
1027 
1028 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
1029   case COFF::reloc_type:                                                       \
1030     Res = #reloc_type;                                                         \
1031     break;
1032 
1033 void COFFObjectFile::getRelocationTypeName(
1034     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1035   const coff_relocation *Reloc = toRel(Rel);
1036   StringRef Res;
1037   switch (getMachine()) {
1038   case COFF::IMAGE_FILE_MACHINE_AMD64:
1039     switch (Reloc->Type) {
1040     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1041     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1042     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1043     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1044     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1045     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1046     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1047     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1048     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1049     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1050     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1051     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1052     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1053     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1054     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1055     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1056     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1057     default:
1058       Res = "Unknown";
1059     }
1060     break;
1061   case COFF::IMAGE_FILE_MACHINE_ARMNT:
1062     switch (Reloc->Type) {
1063     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1064     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1065     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1066     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1067     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1068     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1069     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1070     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1071     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1072     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1073     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1074     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1075     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1076     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1077     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1078     default:
1079       Res = "Unknown";
1080     }
1081     break;
1082   case COFF::IMAGE_FILE_MACHINE_I386:
1083     switch (Reloc->Type) {
1084     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1085     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1086     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1087     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1088     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1089     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1090     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1091     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1092     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1093     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1094     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1095     default:
1096       Res = "Unknown";
1097     }
1098     break;
1099   default:
1100     Res = "Unknown";
1101   }
1102   Result.append(Res.begin(), Res.end());
1103 }
1104 
1105 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1106 
1107 bool COFFObjectFile::isRelocatableObject() const {
1108   return !DataDirectory;
1109 }
1110 
1111 bool ImportDirectoryEntryRef::
1112 operator==(const ImportDirectoryEntryRef &Other) const {
1113   return ImportTable == Other.ImportTable && Index == Other.Index;
1114 }
1115 
1116 void ImportDirectoryEntryRef::moveNext() {
1117   ++Index;
1118 }
1119 
1120 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1121     const import_directory_table_entry *&Result) const {
1122   Result = ImportTable + Index;
1123   return std::error_code();
1124 }
1125 
1126 static imported_symbol_iterator
1127 makeImportedSymbolIterator(const COFFObjectFile *Object,
1128                            uintptr_t Ptr, int Index) {
1129   if (Object->getBytesInAddress() == 4) {
1130     auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1131     return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1132   }
1133   auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1134   return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1135 }
1136 
1137 static imported_symbol_iterator
1138 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1139   uintptr_t IntPtr = 0;
1140   Object->getRvaPtr(RVA, IntPtr);
1141   return makeImportedSymbolIterator(Object, IntPtr, 0);
1142 }
1143 
1144 static imported_symbol_iterator
1145 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1146   uintptr_t IntPtr = 0;
1147   Object->getRvaPtr(RVA, IntPtr);
1148   // Forward the pointer to the last entry which is null.
1149   int Index = 0;
1150   if (Object->getBytesInAddress() == 4) {
1151     auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1152     while (*Entry++)
1153       ++Index;
1154   } else {
1155     auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1156     while (*Entry++)
1157       ++Index;
1158   }
1159   return makeImportedSymbolIterator(Object, IntPtr, Index);
1160 }
1161 
1162 imported_symbol_iterator
1163 ImportDirectoryEntryRef::imported_symbol_begin() const {
1164   return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1165                              OwningObject);
1166 }
1167 
1168 imported_symbol_iterator
1169 ImportDirectoryEntryRef::imported_symbol_end() const {
1170   return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1171                            OwningObject);
1172 }
1173 
1174 iterator_range<imported_symbol_iterator>
1175 ImportDirectoryEntryRef::imported_symbols() const {
1176   return make_range(imported_symbol_begin(), imported_symbol_end());
1177 }
1178 
1179 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1180   uintptr_t IntPtr = 0;
1181   if (std::error_code EC =
1182           OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1183     return EC;
1184   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1185   return std::error_code();
1186 }
1187 
1188 std::error_code
1189 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t  &Result) const {
1190   Result = ImportTable[Index].ImportLookupTableRVA;
1191   return std::error_code();
1192 }
1193 
1194 std::error_code
1195 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1196   Result = ImportTable[Index].ImportAddressTableRVA;
1197   return std::error_code();
1198 }
1199 
1200 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1201     const import_lookup_table_entry32 *&Result) const {
1202   uintptr_t IntPtr = 0;
1203   uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1204   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1205     return EC;
1206   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1207   return std::error_code();
1208 }
1209 
1210 bool DelayImportDirectoryEntryRef::
1211 operator==(const DelayImportDirectoryEntryRef &Other) const {
1212   return Table == Other.Table && Index == Other.Index;
1213 }
1214 
1215 void DelayImportDirectoryEntryRef::moveNext() {
1216   ++Index;
1217 }
1218 
1219 imported_symbol_iterator
1220 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1221   return importedSymbolBegin(Table[Index].DelayImportNameTable,
1222                              OwningObject);
1223 }
1224 
1225 imported_symbol_iterator
1226 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1227   return importedSymbolEnd(Table[Index].DelayImportNameTable,
1228                            OwningObject);
1229 }
1230 
1231 iterator_range<imported_symbol_iterator>
1232 DelayImportDirectoryEntryRef::imported_symbols() const {
1233   return make_range(imported_symbol_begin(), imported_symbol_end());
1234 }
1235 
1236 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1237   uintptr_t IntPtr = 0;
1238   if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1239     return EC;
1240   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1241   return std::error_code();
1242 }
1243 
1244 std::error_code DelayImportDirectoryEntryRef::
1245 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1246   Result = Table;
1247   return std::error_code();
1248 }
1249 
1250 std::error_code DelayImportDirectoryEntryRef::
1251 getImportAddress(int AddrIndex, uint64_t &Result) const {
1252   uint32_t RVA = Table[Index].DelayImportAddressTable +
1253       AddrIndex * (OwningObject->is64() ? 8 : 4);
1254   uintptr_t IntPtr = 0;
1255   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1256     return EC;
1257   if (OwningObject->is64())
1258     Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1259   else
1260     Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1261   return std::error_code();
1262 }
1263 
1264 bool ExportDirectoryEntryRef::
1265 operator==(const ExportDirectoryEntryRef &Other) const {
1266   return ExportTable == Other.ExportTable && Index == Other.Index;
1267 }
1268 
1269 void ExportDirectoryEntryRef::moveNext() {
1270   ++Index;
1271 }
1272 
1273 // Returns the name of the current export symbol. If the symbol is exported only
1274 // by ordinal, the empty string is set as a result.
1275 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1276   uintptr_t IntPtr = 0;
1277   if (std::error_code EC =
1278           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1279     return EC;
1280   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1281   return std::error_code();
1282 }
1283 
1284 // Returns the starting ordinal number.
1285 std::error_code
1286 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1287   Result = ExportTable->OrdinalBase;
1288   return std::error_code();
1289 }
1290 
1291 // Returns the export ordinal of the current export symbol.
1292 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1293   Result = ExportTable->OrdinalBase + Index;
1294   return std::error_code();
1295 }
1296 
1297 // Returns the address of the current export symbol.
1298 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1299   uintptr_t IntPtr = 0;
1300   if (std::error_code EC =
1301           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1302     return EC;
1303   const export_address_table_entry *entry =
1304       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1305   Result = entry[Index].ExportRVA;
1306   return std::error_code();
1307 }
1308 
1309 // Returns the name of the current export symbol. If the symbol is exported only
1310 // by ordinal, the empty string is set as a result.
1311 std::error_code
1312 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1313   uintptr_t IntPtr = 0;
1314   if (std::error_code EC =
1315           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1316     return EC;
1317   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1318 
1319   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1320   int Offset = 0;
1321   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1322        I < E; ++I, ++Offset) {
1323     if (*I != Index)
1324       continue;
1325     if (std::error_code EC =
1326             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1327       return EC;
1328     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1329     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1330       return EC;
1331     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1332     return std::error_code();
1333   }
1334   Result = "";
1335   return std::error_code();
1336 }
1337 
1338 std::error_code ExportDirectoryEntryRef::isForwarder(bool &Result) const {
1339   const data_directory *DataEntry;
1340   if (auto EC = OwningObject->getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
1341     return EC;
1342   uint32_t RVA;
1343   if (auto EC = getExportRVA(RVA))
1344     return EC;
1345   uint32_t Begin = DataEntry->RelativeVirtualAddress;
1346   uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
1347   Result = (Begin <= RVA && RVA < End);
1348   return std::error_code();
1349 }
1350 
1351 std::error_code ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
1352   uint32_t RVA;
1353   if (auto EC = getExportRVA(RVA))
1354     return EC;
1355   uintptr_t IntPtr = 0;
1356   if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
1357     return EC;
1358   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1359   return std::error_code();
1360 }
1361 
1362 bool ImportedSymbolRef::
1363 operator==(const ImportedSymbolRef &Other) const {
1364   return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1365       && Index == Other.Index;
1366 }
1367 
1368 void ImportedSymbolRef::moveNext() {
1369   ++Index;
1370 }
1371 
1372 std::error_code
1373 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1374   uint32_t RVA;
1375   if (Entry32) {
1376     // If a symbol is imported only by ordinal, it has no name.
1377     if (Entry32[Index].isOrdinal())
1378       return std::error_code();
1379     RVA = Entry32[Index].getHintNameRVA();
1380   } else {
1381     if (Entry64[Index].isOrdinal())
1382       return std::error_code();
1383     RVA = Entry64[Index].getHintNameRVA();
1384   }
1385   uintptr_t IntPtr = 0;
1386   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1387     return EC;
1388   // +2 because the first two bytes is hint.
1389   Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1390   return std::error_code();
1391 }
1392 
1393 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1394   uint32_t RVA;
1395   if (Entry32) {
1396     if (Entry32[Index].isOrdinal()) {
1397       Result = Entry32[Index].getOrdinal();
1398       return std::error_code();
1399     }
1400     RVA = Entry32[Index].getHintNameRVA();
1401   } else {
1402     if (Entry64[Index].isOrdinal()) {
1403       Result = Entry64[Index].getOrdinal();
1404       return std::error_code();
1405     }
1406     RVA = Entry64[Index].getHintNameRVA();
1407   }
1408   uintptr_t IntPtr = 0;
1409   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1410     return EC;
1411   Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1412   return std::error_code();
1413 }
1414 
1415 ErrorOr<std::unique_ptr<COFFObjectFile>>
1416 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1417   std::error_code EC;
1418   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1419   if (EC)
1420     return EC;
1421   return std::move(Ret);
1422 }
1423 
1424 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1425   return Header == Other.Header && Index == Other.Index;
1426 }
1427 
1428 void BaseRelocRef::moveNext() {
1429   // Header->BlockSize is the size of the current block, including the
1430   // size of the header itself.
1431   uint32_t Size = sizeof(*Header) +
1432       sizeof(coff_base_reloc_block_entry) * (Index + 1);
1433   if (Size == Header->BlockSize) {
1434     // .reloc contains a list of base relocation blocks. Each block
1435     // consists of the header followed by entries. The header contains
1436     // how many entories will follow. When we reach the end of the
1437     // current block, proceed to the next block.
1438     Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1439         reinterpret_cast<const uint8_t *>(Header) + Size);
1440     Index = 0;
1441   } else {
1442     ++Index;
1443   }
1444 }
1445 
1446 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1447   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1448   Type = Entry[Index].getType();
1449   return std::error_code();
1450 }
1451 
1452 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1453   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1454   Result = Header->PageRVA + Entry[Index].getOffset();
1455   return std::error_code();
1456 }
1457