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