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