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