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