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