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