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