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