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