This patch adds a new flag "-coff-imports" to llvm-readobj.
[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   // -1 because the last entry is the null entry.
495   NumberOfImportDirectory = DataEntry->Size /
496       sizeof(import_directory_table_entry) - 1;
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   // PointerToRawData and SizeOfRawData won't make sense for BSS sections, don't
845   // do anything interesting for them.
846   assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
847          "BSS sections don't have contents!");
848   // The only thing that we need to verify is that the contents is contained
849   // within the file bounds. We don't need to make sure it doesn't cover other
850   // data, as there's nothing that says that is not allowed.
851   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
852   uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
853   if (ConEnd > uintptr_t(Data.getBufferEnd()))
854     return object_error::parse_failed;
855   Res = makeArrayRef(reinterpret_cast<const uint8_t*>(ConStart),
856                      Sec->SizeOfRawData);
857   return object_error::success;
858 }
859
860 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
861   return reinterpret_cast<const coff_relocation*>(Rel.p);
862 }
863
864 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
865   Rel.p = reinterpret_cast<uintptr_t>(
866             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
867 }
868
869 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
870                                                      uint64_t &Res) const {
871   report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
872 }
873
874 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
875                                                     uint64_t &Res) const {
876   Res = toRel(Rel)->VirtualAddress;
877   return object_error::success;
878 }
879
880 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
881   const coff_relocation *R = toRel(Rel);
882   DataRefImpl Ref;
883   if (SymbolTable16)
884     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
885   else if (SymbolTable32)
886     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
887   else
888     llvm_unreachable("no symbol table pointer!");
889   return symbol_iterator(SymbolRef(Ref, this));
890 }
891
892 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
893                                                   uint64_t &Res) const {
894   const coff_relocation* R = toRel(Rel);
895   Res = R->Type;
896   return object_error::success;
897 }
898
899 const coff_section *
900 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
901   return toSec(Section.getRawDataRefImpl());
902 }
903
904 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
905   if (SymbolTable16)
906     return toSymb<coff_symbol16>(Ref);
907   if (SymbolTable32)
908     return toSymb<coff_symbol32>(Ref);
909   llvm_unreachable("no symbol table pointer!");
910 }
911
912 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
913   return getCOFFSymbol(Symbol.getRawDataRefImpl());
914 }
915
916 const coff_relocation *
917 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
918   return toRel(Reloc.getRawDataRefImpl());
919 }
920
921 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
922   case COFF::reloc_type:                                                       \
923     Res = #reloc_type;                                                         \
924     break;
925
926 std::error_code
927 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
928                                       SmallVectorImpl<char> &Result) const {
929   const coff_relocation *Reloc = toRel(Rel);
930   StringRef Res;
931   switch (getMachine()) {
932   case COFF::IMAGE_FILE_MACHINE_AMD64:
933     switch (Reloc->Type) {
934     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
935     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
936     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
937     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
938     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
939     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
940     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
941     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
942     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
943     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
944     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
945     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
946     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
947     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
948     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
949     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
950     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
951     default:
952       Res = "Unknown";
953     }
954     break;
955   case COFF::IMAGE_FILE_MACHINE_ARMNT:
956     switch (Reloc->Type) {
957     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
958     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
959     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
960     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
961     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
962     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
963     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
964     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
965     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
966     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
967     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
968     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
969     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
970     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
971     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
972     default:
973       Res = "Unknown";
974     }
975     break;
976   case COFF::IMAGE_FILE_MACHINE_I386:
977     switch (Reloc->Type) {
978     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
979     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
980     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
981     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
982     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
983     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
984     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
985     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
986     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
987     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
988     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
989     default:
990       Res = "Unknown";
991     }
992     break;
993   default:
994     Res = "Unknown";
995   }
996   Result.append(Res.begin(), Res.end());
997   return object_error::success;
998 }
999
1000 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1001
1002 std::error_code
1003 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
1004                                          SmallVectorImpl<char> &Result) const {
1005   const coff_relocation *Reloc = toRel(Rel);
1006   DataRefImpl Sym;
1007   ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1008   if (std::error_code EC = Symb.getError())
1009     return EC;
1010   Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1011   StringRef SymName;
1012   if (std::error_code EC = getSymbolName(Sym, SymName))
1013     return EC;
1014   Result.append(SymName.begin(), SymName.end());
1015   return object_error::success;
1016 }
1017
1018 bool COFFObjectFile::isRelocatableObject() const {
1019   return !DataDirectory;
1020 }
1021
1022 bool ImportDirectoryEntryRef::
1023 operator==(const ImportDirectoryEntryRef &Other) const {
1024   return ImportTable == Other.ImportTable && Index == Other.Index;
1025 }
1026
1027 void ImportDirectoryEntryRef::moveNext() {
1028   ++Index;
1029 }
1030
1031 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1032     const import_directory_table_entry *&Result) const {
1033   Result = ImportTable + Index;
1034   return object_error::success;
1035 }
1036
1037 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1038   uintptr_t IntPtr = 0;
1039   if (std::error_code EC =
1040           OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1041     return EC;
1042   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1043   return object_error::success;
1044 }
1045
1046 std::error_code
1047 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t  &Result) const {
1048   Result = ImportTable[Index].ImportLookupTableRVA;
1049   return object_error::success;
1050 }
1051
1052 std::error_code
1053 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1054   Result = ImportTable[Index].ImportAddressTableRVA;
1055   return object_error::success;
1056 }
1057
1058 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1059     const import_lookup_table_entry32 *&Result) const {
1060   uintptr_t IntPtr = 0;
1061   uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1062   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1063     return EC;
1064   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1065   return object_error::success;
1066 }
1067
1068 bool ExportDirectoryEntryRef::
1069 operator==(const ExportDirectoryEntryRef &Other) const {
1070   return ExportTable == Other.ExportTable && Index == Other.Index;
1071 }
1072
1073 void ExportDirectoryEntryRef::moveNext() {
1074   ++Index;
1075 }
1076
1077 // Returns the name of the current export symbol. If the symbol is exported only
1078 // by ordinal, the empty string is set as a result.
1079 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1080   uintptr_t IntPtr = 0;
1081   if (std::error_code EC =
1082           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1083     return EC;
1084   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1085   return object_error::success;
1086 }
1087
1088 // Returns the starting ordinal number.
1089 std::error_code
1090 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1091   Result = ExportTable->OrdinalBase;
1092   return object_error::success;
1093 }
1094
1095 // Returns the export ordinal of the current export symbol.
1096 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1097   Result = ExportTable->OrdinalBase + Index;
1098   return object_error::success;
1099 }
1100
1101 // Returns the address of the current export symbol.
1102 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1103   uintptr_t IntPtr = 0;
1104   if (std::error_code EC =
1105           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1106     return EC;
1107   const export_address_table_entry *entry =
1108       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1109   Result = entry[Index].ExportRVA;
1110   return object_error::success;
1111 }
1112
1113 // Returns the name of the current export symbol. If the symbol is exported only
1114 // by ordinal, the empty string is set as a result.
1115 std::error_code
1116 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1117   uintptr_t IntPtr = 0;
1118   if (std::error_code EC =
1119           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1120     return EC;
1121   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1122
1123   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1124   int Offset = 0;
1125   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1126        I < E; ++I, ++Offset) {
1127     if (*I != Index)
1128       continue;
1129     if (std::error_code EC =
1130             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1131       return EC;
1132     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1133     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1134       return EC;
1135     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1136     return object_error::success;
1137   }
1138   Result = "";
1139   return object_error::success;
1140 }
1141
1142 ErrorOr<std::unique_ptr<COFFObjectFile>>
1143 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1144   std::error_code EC;
1145   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1146   if (EC)
1147     return EC;
1148   return std::move(Ret);
1149 }