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