Support: Delete {aligned_,}{u,}{little,big}8_t
[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::little16_t;
31
32 // Returns false if size is greater than the buffer size. And sets ec.
33 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
34   if (M.getBufferSize() < Size) {
35     EC = object_error::unexpected_eof;
36     return false;
37   }
38   return true;
39 }
40
41 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
42 // Returns unexpected_eof if error.
43 template <typename T>
44 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
45                                  const uint8_t *Ptr,
46                                  const size_t Size = sizeof(T)) {
47   uintptr_t Addr = uintptr_t(Ptr);
48   if (Addr + Size < Addr || Addr + Size < Size ||
49       Addr + Size > uintptr_t(M.getBufferEnd())) {
50     return object_error::unexpected_eof;
51   }
52   Obj = reinterpret_cast<const T *>(Addr);
53   return object_error::success;
54 }
55
56 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
57 // prefixed slashes.
58 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
59   assert(Str.size() <= 6 && "String too long, possible overflow.");
60   if (Str.size() > 6)
61     return true;
62
63   uint64_t Value = 0;
64   while (!Str.empty()) {
65     unsigned CharVal;
66     if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
67       CharVal = Str[0] - 'A';
68     else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
69       CharVal = Str[0] - 'a' + 26;
70     else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
71       CharVal = Str[0] - '0' + 52;
72     else if (Str[0] == '+') // 62
73       CharVal = 62;
74     else if (Str[0] == '/') // 63
75       CharVal = 63;
76     else
77       return true;
78
79     Value = (Value * 64) + CharVal;
80     Str = Str.substr(1);
81   }
82
83   if (Value > std::numeric_limits<uint32_t>::max())
84     return true;
85
86   Result = static_cast<uint32_t>(Value);
87   return false;
88 }
89
90 template <typename coff_symbol_type>
91 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
92   const coff_symbol_type *Addr =
93       reinterpret_cast<const coff_symbol_type *>(Ref.p);
94
95 #ifndef NDEBUG
96   // Verify that the symbol points to a valid entry in the symbol table.
97   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
98   if (Offset < getPointerToSymbolTable() ||
99       Offset >= getPointerToSymbolTable() +
100                     (getNumberOfSymbols() * sizeof(coff_symbol_type)))
101     report_fatal_error("Symbol was outside of symbol table.");
102
103   assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
104          "Symbol did not point to the beginning of a symbol");
105 #endif
106
107   return Addr;
108 }
109
110 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
111   const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
112
113 # ifndef NDEBUG
114   // Verify that the section points to a valid entry in the section table.
115   if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
116     report_fatal_error("Section was outside of section table.");
117
118   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
119   assert(Offset % sizeof(coff_section) == 0 &&
120          "Section did not point to the beginning of a section");
121 # endif
122
123   return Addr;
124 }
125
126 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
127   if (SymbolTable16) {
128     const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
129     Symb += 1 + Symb->NumberOfAuxSymbols;
130     Ref.p = reinterpret_cast<uintptr_t>(Symb);
131   } else if (SymbolTable32) {
132     const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
133     Symb += 1 + Symb->NumberOfAuxSymbols;
134     Ref.p = reinterpret_cast<uintptr_t>(Symb);
135   } else {
136     llvm_unreachable("no symbol table pointer!");
137   }
138 }
139
140 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
141                                               StringRef &Result) const {
142   COFFSymbolRef Symb = getCOFFSymbol(Ref);
143   return getSymbolName(Symb, Result);
144 }
145
146 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
147                                                  uint64_t &Result) const {
148   COFFSymbolRef Symb = getCOFFSymbol(Ref);
149   const coff_section *Section = nullptr;
150   if (std::error_code EC = getSection(Symb.getSectionNumber(), Section))
151     return EC;
152
153   if (Symb.getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED)
154     Result = UnknownAddressOrSize;
155   else if (Section)
156     Result = Section->VirtualAddress + Symb.getValue();
157   else
158     Result = Symb.getValue();
159   return object_error::success;
160 }
161
162 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
163                                               SymbolRef::Type &Result) const {
164   COFFSymbolRef Symb = getCOFFSymbol(Ref);
165   Result = SymbolRef::ST_Other;
166
167   if (Symb.getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
168       Symb.getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED) {
169     Result = SymbolRef::ST_Unknown;
170   } else if (Symb.isFunctionDefinition()) {
171     Result = SymbolRef::ST_Function;
172   } else {
173       uint32_t Characteristics = 0;
174       if (!COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
175         const coff_section *Section = nullptr;
176         if (std::error_code EC = getSection(Symb.getSectionNumber(), Section))
177           return EC;
178         Characteristics = Section->Characteristics;
179     }
180     if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
181         ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
182       Result = SymbolRef::ST_Data;
183   }
184   return object_error::success;
185 }
186
187 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
188   COFFSymbolRef Symb = getCOFFSymbol(Ref);
189   uint32_t Result = SymbolRef::SF_None;
190
191   // TODO: Correctly set SF_FormatSpecific, SF_Common
192
193   if (Symb.getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED) {
194     if (Symb.getValue() == 0)
195       Result |= SymbolRef::SF_Undefined;
196     else
197       Result |= SymbolRef::SF_Common;
198   }
199
200
201   // TODO: This are certainly too restrictive.
202   if (Symb.getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL)
203     Result |= SymbolRef::SF_Global;
204
205   if (Symb.getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
206     Result |= SymbolRef::SF_Weak;
207
208   if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
209     Result |= SymbolRef::SF_Absolute;
210
211   return Result;
212 }
213
214 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
215                                               uint64_t &Result) const {
216   // FIXME: Return the correct size. This requires looking at all the symbols
217   //        in the same section as this symbol, and looking for either the next
218   //        symbol, or the end of the section.
219   COFFSymbolRef Symb = getCOFFSymbol(Ref);
220   const coff_section *Section = nullptr;
221   if (std::error_code EC = getSection(Symb.getSectionNumber(), Section))
222     return EC;
223
224   if (Symb.getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED)
225     Result = UnknownAddressOrSize;
226   else if (Section)
227     Result = Section->SizeOfRawData - Symb.getValue();
228   else
229     Result = 0;
230   return object_error::success;
231 }
232
233 std::error_code
234 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
235                                  section_iterator &Result) const {
236   COFFSymbolRef Symb = getCOFFSymbol(Ref);
237   if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
238     Result = section_end();
239   } else {
240     const coff_section *Sec = nullptr;
241     if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
242       return EC;
243     DataRefImpl Ref;
244     Ref.p = reinterpret_cast<uintptr_t>(Sec);
245     Result = section_iterator(SectionRef(Ref, this));
246   }
247   return object_error::success;
248 }
249
250 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
251   const coff_section *Sec = toSec(Ref);
252   Sec += 1;
253   Ref.p = reinterpret_cast<uintptr_t>(Sec);
254 }
255
256 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
257                                                StringRef &Result) const {
258   const coff_section *Sec = toSec(Ref);
259   return getSectionName(Sec, Result);
260 }
261
262 std::error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
263                                                   uint64_t &Result) const {
264   const coff_section *Sec = toSec(Ref);
265   Result = Sec->VirtualAddress;
266   return object_error::success;
267 }
268
269 std::error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
270                                                uint64_t &Result) const {
271   const coff_section *Sec = toSec(Ref);
272   Result = Sec->SizeOfRawData;
273   return object_error::success;
274 }
275
276 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
277                                                    StringRef &Result) const {
278   const coff_section *Sec = toSec(Ref);
279   ArrayRef<uint8_t> Res;
280   std::error_code EC = getSectionContents(Sec, Res);
281   Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
282   return EC;
283 }
284
285 std::error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
286                                                     uint64_t &Res) const {
287   const coff_section *Sec = toSec(Ref);
288   if (!Sec)
289     return object_error::parse_failed;
290   Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
291   return object_error::success;
292 }
293
294 std::error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
295                                               bool &Result) const {
296   const coff_section *Sec = toSec(Ref);
297   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
298   return object_error::success;
299 }
300
301 std::error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
302                                               bool &Result) const {
303   const coff_section *Sec = toSec(Ref);
304   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
305   return object_error::success;
306 }
307
308 std::error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
309                                              bool &Result) const {
310   const coff_section *Sec = toSec(Ref);
311   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
312   return object_error::success;
313 }
314
315 std::error_code
316 COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
317                                               bool &Result) const {
318   // FIXME: Unimplemented
319   Result = true;
320   return object_error::success;
321 }
322
323 std::error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
324                                                  bool &Result) const {
325   const coff_section *Sec = toSec(Ref);
326   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
327   return object_error::success;
328 }
329
330 std::error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
331                                                   bool &Result) const {
332   // FIXME: Unimplemented.
333   Result = false;
334   return object_error::success;
335 }
336
337 std::error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
338                                                       bool &Result) const {
339   // FIXME: Unimplemented.
340   Result = false;
341   return object_error::success;
342 }
343
344 std::error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
345                                                       DataRefImpl SymbRef,
346                                                       bool &Result) const {
347   const coff_section *Sec = toSec(SecRef);
348   COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
349   const coff_section *SymbSec = nullptr;
350   if (std::error_code EC = getSection(Symb.getSectionNumber(), SymbSec))
351     return EC;
352   if (SymbSec == Sec)
353     Result = true;
354   else
355     Result = false;
356   return object_error::success;
357 }
358
359 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
360   const coff_section *Sec = toSec(Ref);
361   DataRefImpl Ret;
362   if (Sec->NumberOfRelocations == 0) {
363     Ret.p = 0;
364   } else {
365     auto begin = reinterpret_cast<const coff_relocation*>(
366         base() + Sec->PointerToRelocations);
367     if (Sec->hasExtendedRelocations()) {
368       // Skip the first relocation entry repurposed to store the number of
369       // relocations.
370       begin++;
371     }
372     Ret.p = reinterpret_cast<uintptr_t>(begin);
373   }
374   return relocation_iterator(RelocationRef(Ret, this));
375 }
376
377 static uint32_t getNumberOfRelocations(const coff_section *Sec,
378                                        const uint8_t *base) {
379   // The field for the number of relocations in COFF section table is only
380   // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
381   // NumberOfRelocations field, and the actual relocation count is stored in the
382   // VirtualAddress field in the first relocation entry.
383   if (Sec->hasExtendedRelocations()) {
384     auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
385         base + Sec->PointerToRelocations);
386     return FirstReloc->VirtualAddress;
387   }
388   return Sec->NumberOfRelocations;
389 }
390
391 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
392   const coff_section *Sec = toSec(Ref);
393   DataRefImpl Ret;
394   if (Sec->NumberOfRelocations == 0) {
395     Ret.p = 0;
396   } else {
397     auto begin = reinterpret_cast<const coff_relocation*>(
398         base() + Sec->PointerToRelocations);
399     uint32_t NumReloc = getNumberOfRelocations(Sec, base());
400     Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
401   }
402   return relocation_iterator(RelocationRef(Ret, this));
403 }
404
405 // Initialize the pointer to the symbol table.
406 std::error_code COFFObjectFile::initSymbolTablePtr() {
407   if (COFFHeader)
408     if (std::error_code EC =
409             getObject(SymbolTable16, Data, base() + getPointerToSymbolTable(),
410                       getNumberOfSymbols() * getSymbolTableEntrySize()))
411       return EC;
412
413   if (COFFBigObjHeader)
414     if (std::error_code EC =
415             getObject(SymbolTable32, Data, base() + getPointerToSymbolTable(),
416                       getNumberOfSymbols() * getSymbolTableEntrySize()))
417       return EC;
418
419   // Find string table. The first four byte of the string table contains the
420   // total size of the string table, including the size field itself. If the
421   // string table is empty, the value of the first four byte would be 4.
422   const uint8_t *StringTableAddr =
423       base() + getPointerToSymbolTable() +
424       getNumberOfSymbols() * getSymbolTableEntrySize();
425   const ulittle32_t *StringTableSizePtr;
426   if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
427     return EC;
428   StringTableSize = *StringTableSizePtr;
429   if (std::error_code EC =
430           getObject(StringTable, Data, StringTableAddr, StringTableSize))
431     return EC;
432
433   // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
434   // tools like cvtres write a size of 0 for an empty table instead of 4.
435   if (StringTableSize < 4)
436       StringTableSize = 4;
437
438   // Check that the string table is null terminated if has any in it.
439   if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
440     return  object_error::parse_failed;
441   return object_error::success;
442 }
443
444 // Returns the file offset for the given VA.
445 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
446   uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
447                                   : (uint64_t)PE32PlusHeader->ImageBase;
448   uint64_t Rva = Addr - ImageBase;
449   assert(Rva <= UINT32_MAX);
450   return getRvaPtr((uint32_t)Rva, Res);
451 }
452
453 // Returns the file offset for the given RVA.
454 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
455   for (const SectionRef &S : sections()) {
456     const coff_section *Section = getCOFFSection(S);
457     uint32_t SectionStart = Section->VirtualAddress;
458     uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
459     if (SectionStart <= Addr && Addr < SectionEnd) {
460       uint32_t Offset = Addr - SectionStart;
461       Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
462       return object_error::success;
463     }
464   }
465   return object_error::parse_failed;
466 }
467
468 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
469 // table entry.
470 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
471                                             StringRef &Name) const {
472   uintptr_t IntPtr = 0;
473   if (std::error_code EC = getRvaPtr(Rva, IntPtr))
474     return EC;
475   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
476   Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
477   Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
478   return object_error::success;
479 }
480
481 // Find the import table.
482 std::error_code COFFObjectFile::initImportTablePtr() {
483   // First, we get the RVA of the import table. If the file lacks a pointer to
484   // the import table, do nothing.
485   const data_directory *DataEntry;
486   if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
487     return object_error::success;
488
489   // Do nothing if the pointer to import table is NULL.
490   if (DataEntry->RelativeVirtualAddress == 0)
491     return object_error::success;
492
493   uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
494   NumberOfImportDirectory = DataEntry->Size /
495       sizeof(import_directory_table_entry);
496
497   // Find the section that contains the RVA. This is needed because the RVA is
498   // the import table's memory address which is different from its file offset.
499   uintptr_t IntPtr = 0;
500   if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
501     return EC;
502   ImportDirectory = reinterpret_cast<
503       const import_directory_table_entry *>(IntPtr);
504   return object_error::success;
505 }
506
507 // Find the export table.
508 std::error_code COFFObjectFile::initExportTablePtr() {
509   // First, we get the RVA of the export table. If the file lacks a pointer to
510   // the export table, do nothing.
511   const data_directory *DataEntry;
512   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
513     return object_error::success;
514
515   // Do nothing if the pointer to export table is NULL.
516   if (DataEntry->RelativeVirtualAddress == 0)
517     return object_error::success;
518
519   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
520   uintptr_t IntPtr = 0;
521   if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
522     return EC;
523   ExportDirectory =
524       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
525   return object_error::success;
526 }
527
528 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
529     : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
530       COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
531       DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
532       SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
533       ImportDirectory(nullptr), NumberOfImportDirectory(0),
534       ExportDirectory(nullptr) {
535   // Check that we at least have enough room for a header.
536   if (!checkSize(Data, EC, sizeof(coff_file_header)))
537     return;
538
539   // The current location in the file where we are looking at.
540   uint64_t CurPtr = 0;
541
542   // PE header is optional and is present only in executables. If it exists,
543   // it is placed right after COFF header.
544   bool HasPEHeader = false;
545
546   // Check if this is a PE/COFF file.
547   if (base()[0] == 0x4d && base()[1] == 0x5a) {
548     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
549     // PE signature to find 'normal' COFF header.
550     if (!checkSize(Data, EC, 0x3c + 8))
551       return;
552     CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
553     // Check the PE magic bytes. ("PE\0\0")
554     if (std::memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) !=
555         0) {
556       EC = object_error::parse_failed;
557       return;
558     }
559     CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
560     HasPEHeader = true;
561   }
562
563   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
564     return;
565
566   // It might be a bigobj file, let's check.  Note that COFF bigobj and COFF
567   // import libraries share a common prefix but bigobj is more restrictive.
568   if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
569       COFFHeader->NumberOfSections == uint16_t(0xffff) &&
570       checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
571     if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
572       return;
573
574     // Verify that we are dealing with bigobj.
575     if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
576         std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
577                     sizeof(COFF::BigObjMagic)) == 0) {
578       COFFHeader = nullptr;
579       CurPtr += sizeof(coff_bigobj_file_header);
580     } else {
581       // It's not a bigobj.
582       COFFBigObjHeader = nullptr;
583     }
584   }
585   if (COFFHeader) {
586     // The prior checkSize call may have failed.  This isn't a hard error
587     // because we were just trying to sniff out bigobj.
588     EC = object_error::success;
589     CurPtr += sizeof(coff_file_header);
590
591     if (COFFHeader->isImportLibrary())
592       return;
593   }
594
595   if (HasPEHeader) {
596     const pe32_header *Header;
597     if ((EC = getObject(Header, Data, base() + CurPtr)))
598       return;
599
600     const uint8_t *DataDirAddr;
601     uint64_t DataDirSize;
602     if (Header->Magic == 0x10b) {
603       PE32Header = Header;
604       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
605       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
606     } else if (Header->Magic == 0x20b) {
607       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
608       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
609       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
610     } else {
611       // It's neither PE32 nor PE32+.
612       EC = object_error::parse_failed;
613       return;
614     }
615     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
616       return;
617     CurPtr += COFFHeader->SizeOfOptionalHeader;
618   }
619
620   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
621                       getNumberOfSections() * sizeof(coff_section))))
622     return;
623
624   // Initialize the pointer to the symbol table.
625   if (getPointerToSymbolTable() != 0)
626     if ((EC = initSymbolTablePtr()))
627       return;
628
629   // Initialize the pointer to the beginning of the import table.
630   if ((EC = initImportTablePtr()))
631     return;
632
633   // Initialize the pointer to the export table.
634   if ((EC = initExportTablePtr()))
635     return;
636
637   EC = object_error::success;
638 }
639
640 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
641   DataRefImpl Ret;
642   Ret.p = getSymbolTable();
643   return basic_symbol_iterator(SymbolRef(Ret, this));
644 }
645
646 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
647   // The symbol table ends where the string table begins.
648   DataRefImpl Ret;
649   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
650   return basic_symbol_iterator(SymbolRef(Ret, this));
651 }
652
653 import_directory_iterator COFFObjectFile::import_directory_begin() const {
654   return import_directory_iterator(
655       ImportDirectoryEntryRef(ImportDirectory, 0, this));
656 }
657
658 import_directory_iterator COFFObjectFile::import_directory_end() const {
659   return import_directory_iterator(
660       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
661 }
662
663 export_directory_iterator COFFObjectFile::export_directory_begin() const {
664   return export_directory_iterator(
665       ExportDirectoryEntryRef(ExportDirectory, 0, this));
666 }
667
668 export_directory_iterator COFFObjectFile::export_directory_end() const {
669   if (!ExportDirectory)
670     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
671   ExportDirectoryEntryRef Ref(ExportDirectory,
672                               ExportDirectory->AddressTableEntries, this);
673   return export_directory_iterator(Ref);
674 }
675
676 section_iterator COFFObjectFile::section_begin() const {
677   DataRefImpl Ret;
678   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
679   return section_iterator(SectionRef(Ret, this));
680 }
681
682 section_iterator COFFObjectFile::section_end() const {
683   DataRefImpl Ret;
684   int NumSections =
685       COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
686   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
687   return section_iterator(SectionRef(Ret, this));
688 }
689
690 uint8_t COFFObjectFile::getBytesInAddress() const {
691   return getArch() == Triple::x86_64 ? 8 : 4;
692 }
693
694 StringRef COFFObjectFile::getFileFormatName() const {
695   switch(getMachine()) {
696   case COFF::IMAGE_FILE_MACHINE_I386:
697     return "COFF-i386";
698   case COFF::IMAGE_FILE_MACHINE_AMD64:
699     return "COFF-x86-64";
700   case COFF::IMAGE_FILE_MACHINE_ARMNT:
701     return "COFF-ARM";
702   default:
703     return "COFF-<unknown arch>";
704   }
705 }
706
707 unsigned COFFObjectFile::getArch() const {
708   switch (getMachine()) {
709   case COFF::IMAGE_FILE_MACHINE_I386:
710     return Triple::x86;
711   case COFF::IMAGE_FILE_MACHINE_AMD64:
712     return Triple::x86_64;
713   case COFF::IMAGE_FILE_MACHINE_ARMNT:
714     return Triple::thumb;
715   default:
716     return Triple::UnknownArch;
717   }
718 }
719
720 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
721   Res = PE32Header;
722   return object_error::success;
723 }
724
725 std::error_code
726 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
727   Res = PE32PlusHeader;
728   return object_error::success;
729 }
730
731 std::error_code
732 COFFObjectFile::getDataDirectory(uint32_t Index,
733                                  const data_directory *&Res) const {
734   // Error if if there's no data directory or the index is out of range.
735   if (!DataDirectory)
736     return object_error::parse_failed;
737   assert(PE32Header || PE32PlusHeader);
738   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
739                                : PE32PlusHeader->NumberOfRvaAndSize;
740   if (Index > NumEnt)
741     return object_error::parse_failed;
742   Res = &DataDirectory[Index];
743   return object_error::success;
744 }
745
746 std::error_code COFFObjectFile::getSection(int32_t Index,
747                                            const coff_section *&Result) const {
748   // Check for special index values.
749   if (COFF::isReservedSectionNumber(Index))
750     Result = nullptr;
751   else if (Index > 0 && static_cast<uint32_t>(Index) <= getNumberOfSections())
752     // We already verified the section table data, so no need to check again.
753     Result = SectionTable + (Index - 1);
754   else
755     return object_error::parse_failed;
756   return object_error::success;
757 }
758
759 std::error_code COFFObjectFile::getString(uint32_t Offset,
760                                           StringRef &Result) const {
761   if (StringTableSize <= 4)
762     // Tried to get a string from an empty string table.
763     return object_error::parse_failed;
764   if (Offset >= StringTableSize)
765     return object_error::unexpected_eof;
766   Result = StringRef(StringTable + Offset);
767   return object_error::success;
768 }
769
770 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
771                                               StringRef &Res) const {
772   // Check for string table entry. First 4 bytes are 0.
773   if (Symbol.getStringTableOffset().Zeroes == 0) {
774     uint32_t Offset = Symbol.getStringTableOffset().Offset;
775     if (std::error_code EC = getString(Offset, Res))
776       return EC;
777     return object_error::success;
778   }
779
780   if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
781     // Null terminated, let ::strlen figure out the length.
782     Res = StringRef(Symbol.getShortName());
783   else
784     // Not null terminated, use all 8 bytes.
785     Res = StringRef(Symbol.getShortName(), COFF::NameSize);
786   return object_error::success;
787 }
788
789 ArrayRef<uint8_t>
790 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
791   const uint8_t *Aux = nullptr;
792
793   size_t SymbolSize = getSymbolTableEntrySize();
794   if (Symbol.getNumberOfAuxSymbols() > 0) {
795     // AUX data comes immediately after the symbol in COFF
796     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
797 # ifndef NDEBUG
798     // Verify that the Aux symbol points to a valid entry in the symbol table.
799     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
800     if (Offset < getPointerToSymbolTable() ||
801         Offset >=
802             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
803       report_fatal_error("Aux Symbol data was outside of symbol table.");
804
805     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
806            "Aux Symbol data did not point to the beginning of a symbol");
807 # endif
808   }
809   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
810 }
811
812 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
813                                                StringRef &Res) const {
814   StringRef Name;
815   if (Sec->Name[COFF::NameSize - 1] == 0)
816     // Null terminated, let ::strlen figure out the length.
817     Name = Sec->Name;
818   else
819     // Not null terminated, use all 8 bytes.
820     Name = StringRef(Sec->Name, COFF::NameSize);
821
822   // Check for string table entry. First byte is '/'.
823   if (Name[0] == '/') {
824     uint32_t Offset;
825     if (Name[1] == '/') {
826       if (decodeBase64StringEntry(Name.substr(2), Offset))
827         return object_error::parse_failed;
828     } else {
829       if (Name.substr(1).getAsInteger(10, Offset))
830         return object_error::parse_failed;
831     }
832     if (std::error_code EC = getString(Offset, Name))
833       return EC;
834   }
835
836   Res = Name;
837   return object_error::success;
838 }
839
840 std::error_code
841 COFFObjectFile::getSectionContents(const coff_section *Sec,
842                                    ArrayRef<uint8_t> &Res) const {
843   // The only thing that we need to verify is that the contents is contained
844   // within the file bounds. We don't need to make sure it doesn't cover other
845   // data, as there's nothing that says that is not allowed.
846   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
847   uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
848   if (ConEnd > uintptr_t(Data.getBufferEnd()))
849     return object_error::parse_failed;
850   Res = makeArrayRef(reinterpret_cast<const uint8_t*>(ConStart),
851                      Sec->SizeOfRawData);
852   return object_error::success;
853 }
854
855 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
856   return reinterpret_cast<const coff_relocation*>(Rel.p);
857 }
858
859 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
860   Rel.p = reinterpret_cast<uintptr_t>(
861             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
862 }
863
864 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
865                                                      uint64_t &Res) const {
866   report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
867 }
868
869 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
870                                                     uint64_t &Res) const {
871   Res = toRel(Rel)->VirtualAddress;
872   return object_error::success;
873 }
874
875 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
876   const coff_relocation *R = toRel(Rel);
877   DataRefImpl Ref;
878   if (SymbolTable16)
879     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
880   else if (SymbolTable32)
881     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
882   else
883     llvm_unreachable("no symbol table pointer!");
884   return symbol_iterator(SymbolRef(Ref, this));
885 }
886
887 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
888                                                   uint64_t &Res) const {
889   const coff_relocation* R = toRel(Rel);
890   Res = R->Type;
891   return object_error::success;
892 }
893
894 const coff_section *
895 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
896   return toSec(Section.getRawDataRefImpl());
897 }
898
899 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
900   if (SymbolTable16)
901     return toSymb<coff_symbol16>(Ref);
902   if (SymbolTable32)
903     return toSymb<coff_symbol32>(Ref);
904   llvm_unreachable("no symbol table pointer!");
905 }
906
907 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
908   return getCOFFSymbol(Symbol.getRawDataRefImpl());
909 }
910
911 const coff_relocation *
912 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
913   return toRel(Reloc.getRawDataRefImpl());
914 }
915
916 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
917   case COFF::reloc_type:                                                       \
918     Res = #reloc_type;                                                         \
919     break;
920
921 std::error_code
922 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
923                                       SmallVectorImpl<char> &Result) const {
924   const coff_relocation *Reloc = toRel(Rel);
925   StringRef Res;
926   switch (getMachine()) {
927   case COFF::IMAGE_FILE_MACHINE_AMD64:
928     switch (Reloc->Type) {
929     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
930     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
931     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
932     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
933     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
934     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
935     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
936     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
937     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
938     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
939     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
940     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
941     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
942     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
943     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
944     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
945     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
946     default:
947       Res = "Unknown";
948     }
949     break;
950   case COFF::IMAGE_FILE_MACHINE_ARMNT:
951     switch (Reloc->Type) {
952     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
953     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
954     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
955     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
956     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
957     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
958     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
959     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
960     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
961     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
962     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
963     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
964     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
965     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
966     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
967     default:
968       Res = "Unknown";
969     }
970     break;
971   case COFF::IMAGE_FILE_MACHINE_I386:
972     switch (Reloc->Type) {
973     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
974     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
975     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
976     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
977     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
978     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
979     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
980     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
981     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
982     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
983     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
984     default:
985       Res = "Unknown";
986     }
987     break;
988   default:
989     Res = "Unknown";
990   }
991   Result.append(Res.begin(), Res.end());
992   return object_error::success;
993 }
994
995 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
996
997 std::error_code
998 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
999                                          SmallVectorImpl<char> &Result) const {
1000   const coff_relocation *Reloc = toRel(Rel);
1001   DataRefImpl Sym;
1002   ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1003   if (std::error_code EC = Symb.getError())
1004     return EC;
1005   Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1006   StringRef SymName;
1007   if (std::error_code EC = getSymbolName(Sym, SymName))
1008     return EC;
1009   Result.append(SymName.begin(), SymName.end());
1010   return object_error::success;
1011 }
1012
1013 bool COFFObjectFile::isRelocatableObject() const {
1014   return !DataDirectory;
1015 }
1016
1017 bool ImportDirectoryEntryRef::
1018 operator==(const ImportDirectoryEntryRef &Other) const {
1019   return ImportTable == Other.ImportTable && Index == Other.Index;
1020 }
1021
1022 void ImportDirectoryEntryRef::moveNext() {
1023   ++Index;
1024 }
1025
1026 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1027     const import_directory_table_entry *&Result) const {
1028   Result = ImportTable;
1029   return object_error::success;
1030 }
1031
1032 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1033   uintptr_t IntPtr = 0;
1034   if (std::error_code EC =
1035           OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
1036     return EC;
1037   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1038   return object_error::success;
1039 }
1040
1041 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1042     const import_lookup_table_entry32 *&Result) const {
1043   uintptr_t IntPtr = 0;
1044   if (std::error_code EC =
1045           OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
1046     return EC;
1047   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1048   return object_error::success;
1049 }
1050
1051 bool ExportDirectoryEntryRef::
1052 operator==(const ExportDirectoryEntryRef &Other) const {
1053   return ExportTable == Other.ExportTable && Index == Other.Index;
1054 }
1055
1056 void ExportDirectoryEntryRef::moveNext() {
1057   ++Index;
1058 }
1059
1060 // Returns the name of the current export symbol. If the symbol is exported only
1061 // by ordinal, the empty string is set as a result.
1062 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1063   uintptr_t IntPtr = 0;
1064   if (std::error_code EC =
1065           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1066     return EC;
1067   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1068   return object_error::success;
1069 }
1070
1071 // Returns the starting ordinal number.
1072 std::error_code
1073 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1074   Result = ExportTable->OrdinalBase;
1075   return object_error::success;
1076 }
1077
1078 // Returns the export ordinal of the current export symbol.
1079 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1080   Result = ExportTable->OrdinalBase + Index;
1081   return object_error::success;
1082 }
1083
1084 // Returns the address of the current export symbol.
1085 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1086   uintptr_t IntPtr = 0;
1087   if (std::error_code EC =
1088           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1089     return EC;
1090   const export_address_table_entry *entry =
1091       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1092   Result = entry[Index].ExportRVA;
1093   return object_error::success;
1094 }
1095
1096 // Returns the name of the current export symbol. If the symbol is exported only
1097 // by ordinal, the empty string is set as a result.
1098 std::error_code
1099 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1100   uintptr_t IntPtr = 0;
1101   if (std::error_code EC =
1102           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1103     return EC;
1104   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1105
1106   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1107   int Offset = 0;
1108   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1109        I < E; ++I, ++Offset) {
1110     if (*I != Index)
1111       continue;
1112     if (std::error_code EC =
1113             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1114       return EC;
1115     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1116     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1117       return EC;
1118     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1119     return object_error::success;
1120   }
1121   Result = "";
1122   return object_error::success;
1123 }
1124
1125 ErrorOr<std::unique_ptr<COFFObjectFile>>
1126 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1127   std::error_code EC;
1128   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1129   if (EC)
1130     return EC;
1131   return std::move(Ret);
1132 }