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