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