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