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