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