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