Object: Add support for bigobj
[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 template <typename coff_symbol_type>
772 std::error_code
773 COFFObjectFile::getSymbol(uint32_t Index,
774                           const coff_symbol_type *&Result) const {
775   if (Index < getNumberOfSymbols())
776     Result = reinterpret_cast<coff_symbol_type *>(getSymbolTable()) + Index;
777   else
778     return object_error::parse_failed;
779   return object_error::success;
780 }
781
782 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
783                                               StringRef &Res) const {
784   // Check for string table entry. First 4 bytes are 0.
785   if (Symbol.getStringTableOffset().Zeroes == 0) {
786     uint32_t Offset = Symbol.getStringTableOffset().Offset;
787     if (std::error_code EC = getString(Offset, Res))
788       return EC;
789     return object_error::success;
790   }
791
792   if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
793     // Null terminated, let ::strlen figure out the length.
794     Res = StringRef(Symbol.getShortName());
795   else
796     // Not null terminated, use all 8 bytes.
797     Res = StringRef(Symbol.getShortName(), COFF::NameSize);
798   return object_error::success;
799 }
800
801 ArrayRef<uint8_t>
802 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
803   const uint8_t *Aux = nullptr;
804
805   size_t SymbolSize = getSymbolTableEntrySize();
806   if (Symbol.getNumberOfAuxSymbols() > 0) {
807     // AUX data comes immediately after the symbol in COFF
808     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
809 # ifndef NDEBUG
810     // Verify that the Aux symbol points to a valid entry in the symbol table.
811     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
812     if (Offset < getPointerToSymbolTable() ||
813         Offset >=
814             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
815       report_fatal_error("Aux Symbol data was outside of symbol table.");
816
817     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
818            "Aux Symbol data did not point to the beginning of a symbol");
819 # endif
820   }
821   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
822 }
823
824 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
825                                                StringRef &Res) const {
826   StringRef Name;
827   if (Sec->Name[COFF::NameSize - 1] == 0)
828     // Null terminated, let ::strlen figure out the length.
829     Name = Sec->Name;
830   else
831     // Not null terminated, use all 8 bytes.
832     Name = StringRef(Sec->Name, COFF::NameSize);
833
834   // Check for string table entry. First byte is '/'.
835   if (Name[0] == '/') {
836     uint32_t Offset;
837     if (Name[1] == '/') {
838       if (decodeBase64StringEntry(Name.substr(2), Offset))
839         return object_error::parse_failed;
840     } else {
841       if (Name.substr(1).getAsInteger(10, Offset))
842         return object_error::parse_failed;
843     }
844     if (std::error_code EC = getString(Offset, Name))
845       return EC;
846   }
847
848   Res = Name;
849   return object_error::success;
850 }
851
852 std::error_code
853 COFFObjectFile::getSectionContents(const coff_section *Sec,
854                                    ArrayRef<uint8_t> &Res) const {
855   // The only thing that we need to verify is that the contents is contained
856   // within the file bounds. We don't need to make sure it doesn't cover other
857   // data, as there's nothing that says that is not allowed.
858   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
859   uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
860   if (ConEnd > uintptr_t(Data.getBufferEnd()))
861     return object_error::parse_failed;
862   Res = makeArrayRef(reinterpret_cast<const uint8_t*>(ConStart),
863                      Sec->SizeOfRawData);
864   return object_error::success;
865 }
866
867 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
868   return reinterpret_cast<const coff_relocation*>(Rel.p);
869 }
870
871 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
872   Rel.p = reinterpret_cast<uintptr_t>(
873             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
874 }
875
876 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
877                                                      uint64_t &Res) const {
878   report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
879 }
880
881 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
882                                                     uint64_t &Res) const {
883   Res = toRel(Rel)->VirtualAddress;
884   return object_error::success;
885 }
886
887 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
888   const coff_relocation *R = toRel(Rel);
889   DataRefImpl Ref;
890   if (SymbolTable16)
891     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
892   else if (SymbolTable32)
893     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
894   else
895     llvm_unreachable("no symbol table pointer!");
896   return symbol_iterator(SymbolRef(Ref, this));
897 }
898
899 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
900                                                   uint64_t &Res) const {
901   const coff_relocation* R = toRel(Rel);
902   Res = R->Type;
903   return object_error::success;
904 }
905
906 const coff_section *
907 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
908   return toSec(Section.getRawDataRefImpl());
909 }
910
911 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
912   if (SymbolTable16)
913     return toSymb<coff_symbol16>(Ref);
914   if (SymbolTable32)
915     return toSymb<coff_symbol32>(Ref);
916   llvm_unreachable("no symbol table pointer!");
917 }
918
919 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
920   return getCOFFSymbol(Symbol.getRawDataRefImpl());
921 }
922
923 const coff_relocation *
924 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
925   return toRel(Reloc.getRawDataRefImpl());
926 }
927
928 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
929   case COFF::reloc_type:                                                       \
930     Res = #reloc_type;                                                         \
931     break;
932
933 std::error_code
934 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
935                                       SmallVectorImpl<char> &Result) const {
936   const coff_relocation *Reloc = toRel(Rel);
937   StringRef Res;
938   switch (getMachine()) {
939   case COFF::IMAGE_FILE_MACHINE_AMD64:
940     switch (Reloc->Type) {
941     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
942     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
943     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
944     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
945     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
946     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
947     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
948     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
949     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
950     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
951     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
952     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
953     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
954     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
955     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
956     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
957     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
958     default:
959       Res = "Unknown";
960     }
961     break;
962   case COFF::IMAGE_FILE_MACHINE_ARMNT:
963     switch (Reloc->Type) {
964     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
965     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
966     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
967     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
968     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
969     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
970     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
971     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
972     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
973     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
974     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
975     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
976     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
977     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
978     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
979     default:
980       Res = "Unknown";
981     }
982     break;
983   case COFF::IMAGE_FILE_MACHINE_I386:
984     switch (Reloc->Type) {
985     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
986     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
987     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
988     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
989     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
990     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
991     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
992     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
993     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
994     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
995     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
996     default:
997       Res = "Unknown";
998     }
999     break;
1000   default:
1001     Res = "Unknown";
1002   }
1003   Result.append(Res.begin(), Res.end());
1004   return object_error::success;
1005 }
1006
1007 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1008
1009 std::error_code
1010 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
1011                                          SmallVectorImpl<char> &Result) const {
1012   const coff_relocation *Reloc = toRel(Rel);
1013   DataRefImpl Sym;
1014   ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1015   if (std::error_code EC = Symb.getError())
1016     return EC;
1017   Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1018   StringRef SymName;
1019   if (std::error_code EC = getSymbolName(Sym, SymName))
1020     return EC;
1021   Result.append(SymName.begin(), SymName.end());
1022   return object_error::success;
1023 }
1024
1025 bool COFFObjectFile::isRelocatableObject() const {
1026   return !DataDirectory;
1027 }
1028
1029 bool ImportDirectoryEntryRef::
1030 operator==(const ImportDirectoryEntryRef &Other) const {
1031   return ImportTable == Other.ImportTable && Index == Other.Index;
1032 }
1033
1034 void ImportDirectoryEntryRef::moveNext() {
1035   ++Index;
1036 }
1037
1038 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1039     const import_directory_table_entry *&Result) const {
1040   Result = ImportTable;
1041   return object_error::success;
1042 }
1043
1044 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1045   uintptr_t IntPtr = 0;
1046   if (std::error_code EC =
1047           OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
1048     return EC;
1049   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1050   return object_error::success;
1051 }
1052
1053 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1054     const import_lookup_table_entry32 *&Result) const {
1055   uintptr_t IntPtr = 0;
1056   if (std::error_code EC =
1057           OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
1058     return EC;
1059   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1060   return object_error::success;
1061 }
1062
1063 bool ExportDirectoryEntryRef::
1064 operator==(const ExportDirectoryEntryRef &Other) const {
1065   return ExportTable == Other.ExportTable && Index == Other.Index;
1066 }
1067
1068 void ExportDirectoryEntryRef::moveNext() {
1069   ++Index;
1070 }
1071
1072 // Returns the name of the current export symbol. If the symbol is exported only
1073 // by ordinal, the empty string is set as a result.
1074 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1075   uintptr_t IntPtr = 0;
1076   if (std::error_code EC =
1077           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1078     return EC;
1079   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1080   return object_error::success;
1081 }
1082
1083 // Returns the starting ordinal number.
1084 std::error_code
1085 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1086   Result = ExportTable->OrdinalBase;
1087   return object_error::success;
1088 }
1089
1090 // Returns the export ordinal of the current export symbol.
1091 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1092   Result = ExportTable->OrdinalBase + Index;
1093   return object_error::success;
1094 }
1095
1096 // Returns the address of the current export symbol.
1097 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1098   uintptr_t IntPtr = 0;
1099   if (std::error_code EC =
1100           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1101     return EC;
1102   const export_address_table_entry *entry =
1103       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1104   Result = entry[Index].ExportRVA;
1105   return object_error::success;
1106 }
1107
1108 // Returns the name of the current export symbol. If the symbol is exported only
1109 // by ordinal, the empty string is set as a result.
1110 std::error_code
1111 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1112   uintptr_t IntPtr = 0;
1113   if (std::error_code EC =
1114           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1115     return EC;
1116   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1117
1118   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1119   int Offset = 0;
1120   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1121        I < E; ++I, ++Offset) {
1122     if (*I != Index)
1123       continue;
1124     if (std::error_code EC =
1125             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1126       return EC;
1127     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1128     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1129       return EC;
1130     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1131     return object_error::success;
1132   }
1133   Result = "";
1134   return object_error::success;
1135 }
1136
1137 ErrorOr<std::unique_ptr<COFFObjectFile>>
1138 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1139   std::error_code EC;
1140   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1141   if (EC)
1142     return EC;
1143   return std::move(Ret);
1144 }