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