llvm-readobj: print COFF imported symbols
[oota-llvm.git] / lib / Object / COFFObjectFile.cpp
1 //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the COFFObjectFile class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Object/COFF.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Support/COFF.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <cctype>
23 #include <limits>
24
25 using namespace llvm;
26 using namespace object;
27
28 using support::ulittle16_t;
29 using support::ulittle32_t;
30 using support::ulittle64_t;
31 using support::little16_t;
32
33 // Returns false if size is greater than the buffer size. And sets ec.
34 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
35   if (M.getBufferSize() < Size) {
36     EC = object_error::unexpected_eof;
37     return false;
38   }
39   return true;
40 }
41
42 // 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   // -1 because the last entry is the null entry.
496   NumberOfImportDirectory = DataEntry->Size /
497       sizeof(import_directory_table_entry) - 1;
498
499   // Find the section that contains the RVA. This is needed because the RVA is
500   // the import table's memory address which is different from its file offset.
501   uintptr_t IntPtr = 0;
502   if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
503     return EC;
504   ImportDirectory = reinterpret_cast<
505       const import_directory_table_entry *>(IntPtr);
506   return object_error::success;
507 }
508
509 // Find the export table.
510 std::error_code COFFObjectFile::initExportTablePtr() {
511   // First, we get the RVA of the export table. If the file lacks a pointer to
512   // the export table, do nothing.
513   const data_directory *DataEntry;
514   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
515     return object_error::success;
516
517   // Do nothing if the pointer to export table is NULL.
518   if (DataEntry->RelativeVirtualAddress == 0)
519     return object_error::success;
520
521   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
522   uintptr_t IntPtr = 0;
523   if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
524     return EC;
525   ExportDirectory =
526       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
527   return object_error::success;
528 }
529
530 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
531     : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
532       COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
533       DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
534       SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
535       ImportDirectory(nullptr), NumberOfImportDirectory(0),
536       ExportDirectory(nullptr) {
537   // Check that we at least have enough room for a header.
538   if (!checkSize(Data, EC, sizeof(coff_file_header)))
539     return;
540
541   // The current location in the file where we are looking at.
542   uint64_t CurPtr = 0;
543
544   // PE header is optional and is present only in executables. If it exists,
545   // it is placed right after COFF header.
546   bool HasPEHeader = false;
547
548   // Check if this is a PE/COFF file.
549   if (base()[0] == 0x4d && base()[1] == 0x5a) {
550     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
551     // PE signature to find 'normal' COFF header.
552     if (!checkSize(Data, EC, 0x3c + 8))
553       return;
554     CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
555     // Check the PE magic bytes. ("PE\0\0")
556     if (std::memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) !=
557         0) {
558       EC = object_error::parse_failed;
559       return;
560     }
561     CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
562     HasPEHeader = true;
563   }
564
565   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
566     return;
567
568   // It might be a bigobj file, let's check.  Note that COFF bigobj and COFF
569   // import libraries share a common prefix but bigobj is more restrictive.
570   if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
571       COFFHeader->NumberOfSections == uint16_t(0xffff) &&
572       checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
573     if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
574       return;
575
576     // Verify that we are dealing with bigobj.
577     if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
578         std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
579                     sizeof(COFF::BigObjMagic)) == 0) {
580       COFFHeader = nullptr;
581       CurPtr += sizeof(coff_bigobj_file_header);
582     } else {
583       // It's not a bigobj.
584       COFFBigObjHeader = nullptr;
585     }
586   }
587   if (COFFHeader) {
588     // The prior checkSize call may have failed.  This isn't a hard error
589     // because we were just trying to sniff out bigobj.
590     EC = object_error::success;
591     CurPtr += sizeof(coff_file_header);
592
593     if (COFFHeader->isImportLibrary())
594       return;
595   }
596
597   if (HasPEHeader) {
598     const pe32_header *Header;
599     if ((EC = getObject(Header, Data, base() + CurPtr)))
600       return;
601
602     const uint8_t *DataDirAddr;
603     uint64_t DataDirSize;
604     if (Header->Magic == 0x10b) {
605       PE32Header = Header;
606       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
607       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
608     } else if (Header->Magic == 0x20b) {
609       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
610       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
611       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
612     } else {
613       // It's neither PE32 nor PE32+.
614       EC = object_error::parse_failed;
615       return;
616     }
617     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
618       return;
619     CurPtr += COFFHeader->SizeOfOptionalHeader;
620   }
621
622   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
623                       getNumberOfSections() * sizeof(coff_section))))
624     return;
625
626   // Initialize the pointer to the symbol table.
627   if (getPointerToSymbolTable() != 0)
628     if ((EC = initSymbolTablePtr()))
629       return;
630
631   // Initialize the pointer to the beginning of the import table.
632   if ((EC = initImportTablePtr()))
633     return;
634
635   // Initialize the pointer to the export table.
636   if ((EC = initExportTablePtr()))
637     return;
638
639   EC = object_error::success;
640 }
641
642 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
643   DataRefImpl Ret;
644   Ret.p = getSymbolTable();
645   return basic_symbol_iterator(SymbolRef(Ret, this));
646 }
647
648 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
649   // The symbol table ends where the string table begins.
650   DataRefImpl Ret;
651   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
652   return basic_symbol_iterator(SymbolRef(Ret, this));
653 }
654
655 import_directory_iterator COFFObjectFile::import_directory_begin() const {
656   return import_directory_iterator(
657       ImportDirectoryEntryRef(ImportDirectory, 0, this));
658 }
659
660 import_directory_iterator COFFObjectFile::import_directory_end() const {
661   return import_directory_iterator(
662       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
663 }
664
665 export_directory_iterator COFFObjectFile::export_directory_begin() const {
666   return export_directory_iterator(
667       ExportDirectoryEntryRef(ExportDirectory, 0, this));
668 }
669
670 export_directory_iterator COFFObjectFile::export_directory_end() const {
671   if (!ExportDirectory)
672     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
673   ExportDirectoryEntryRef Ref(ExportDirectory,
674                               ExportDirectory->AddressTableEntries, this);
675   return export_directory_iterator(Ref);
676 }
677
678 section_iterator COFFObjectFile::section_begin() const {
679   DataRefImpl Ret;
680   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
681   return section_iterator(SectionRef(Ret, this));
682 }
683
684 section_iterator COFFObjectFile::section_end() const {
685   DataRefImpl Ret;
686   int NumSections =
687       COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
688   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
689   return section_iterator(SectionRef(Ret, this));
690 }
691
692 uint8_t COFFObjectFile::getBytesInAddress() const {
693   return getArch() == Triple::x86_64 ? 8 : 4;
694 }
695
696 StringRef COFFObjectFile::getFileFormatName() const {
697   switch(getMachine()) {
698   case COFF::IMAGE_FILE_MACHINE_I386:
699     return "COFF-i386";
700   case COFF::IMAGE_FILE_MACHINE_AMD64:
701     return "COFF-x86-64";
702   case COFF::IMAGE_FILE_MACHINE_ARMNT:
703     return "COFF-ARM";
704   default:
705     return "COFF-<unknown arch>";
706   }
707 }
708
709 unsigned COFFObjectFile::getArch() const {
710   switch (getMachine()) {
711   case COFF::IMAGE_FILE_MACHINE_I386:
712     return Triple::x86;
713   case COFF::IMAGE_FILE_MACHINE_AMD64:
714     return Triple::x86_64;
715   case COFF::IMAGE_FILE_MACHINE_ARMNT:
716     return Triple::thumb;
717   default:
718     return Triple::UnknownArch;
719   }
720 }
721
722 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
723   Res = PE32Header;
724   return object_error::success;
725 }
726
727 std::error_code
728 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
729   Res = PE32PlusHeader;
730   return object_error::success;
731 }
732
733 std::error_code
734 COFFObjectFile::getDataDirectory(uint32_t Index,
735                                  const data_directory *&Res) const {
736   // Error if if there's no data directory or the index is out of range.
737   if (!DataDirectory)
738     return object_error::parse_failed;
739   assert(PE32Header || PE32PlusHeader);
740   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
741                                : PE32PlusHeader->NumberOfRvaAndSize;
742   if (Index > NumEnt)
743     return object_error::parse_failed;
744   Res = &DataDirectory[Index];
745   return object_error::success;
746 }
747
748 std::error_code COFFObjectFile::getSection(int32_t Index,
749                                            const coff_section *&Result) const {
750   // Check for special index values.
751   if (COFF::isReservedSectionNumber(Index))
752     Result = nullptr;
753   else if (Index > 0 && static_cast<uint32_t>(Index) <= getNumberOfSections())
754     // We already verified the section table data, so no need to check again.
755     Result = SectionTable + (Index - 1);
756   else
757     return object_error::parse_failed;
758   return object_error::success;
759 }
760
761 std::error_code COFFObjectFile::getString(uint32_t Offset,
762                                           StringRef &Result) const {
763   if (StringTableSize <= 4)
764     // Tried to get a string from an empty string table.
765     return object_error::parse_failed;
766   if (Offset >= StringTableSize)
767     return object_error::unexpected_eof;
768   Result = StringRef(StringTable + Offset);
769   return object_error::success;
770 }
771
772 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
773                                               StringRef &Res) const {
774   // Check for string table entry. First 4 bytes are 0.
775   if (Symbol.getStringTableOffset().Zeroes == 0) {
776     uint32_t Offset = Symbol.getStringTableOffset().Offset;
777     if (std::error_code EC = getString(Offset, Res))
778       return EC;
779     return object_error::success;
780   }
781
782   if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
783     // Null terminated, let ::strlen figure out the length.
784     Res = StringRef(Symbol.getShortName());
785   else
786     // Not null terminated, use all 8 bytes.
787     Res = StringRef(Symbol.getShortName(), COFF::NameSize);
788   return object_error::success;
789 }
790
791 ArrayRef<uint8_t>
792 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
793   const uint8_t *Aux = nullptr;
794
795   size_t SymbolSize = getSymbolTableEntrySize();
796   if (Symbol.getNumberOfAuxSymbols() > 0) {
797     // AUX data comes immediately after the symbol in COFF
798     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
799 # ifndef NDEBUG
800     // Verify that the Aux symbol points to a valid entry in the symbol table.
801     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
802     if (Offset < getPointerToSymbolTable() ||
803         Offset >=
804             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
805       report_fatal_error("Aux Symbol data was outside of symbol table.");
806
807     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
808            "Aux Symbol data did not point to the beginning of a symbol");
809 # endif
810   }
811   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
812 }
813
814 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
815                                                StringRef &Res) const {
816   StringRef Name;
817   if (Sec->Name[COFF::NameSize - 1] == 0)
818     // Null terminated, let ::strlen figure out the length.
819     Name = Sec->Name;
820   else
821     // Not null terminated, use all 8 bytes.
822     Name = StringRef(Sec->Name, COFF::NameSize);
823
824   // Check for string table entry. First byte is '/'.
825   if (Name[0] == '/') {
826     uint32_t Offset;
827     if (Name[1] == '/') {
828       if (decodeBase64StringEntry(Name.substr(2), Offset))
829         return object_error::parse_failed;
830     } else {
831       if (Name.substr(1).getAsInteger(10, Offset))
832         return object_error::parse_failed;
833     }
834     if (std::error_code EC = getString(Offset, Name))
835       return EC;
836   }
837
838   Res = Name;
839   return object_error::success;
840 }
841
842 std::error_code
843 COFFObjectFile::getSectionContents(const coff_section *Sec,
844                                    ArrayRef<uint8_t> &Res) const {
845   // PointerToRawData and SizeOfRawData won't make sense for BSS sections, don't
846   // do anything interesting for them.
847   assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
848          "BSS sections don't have contents!");
849   // The only thing that we need to verify is that the contents is contained
850   // within the file bounds. We don't need to make sure it doesn't cover other
851   // data, as there's nothing that says that is not allowed.
852   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
853   uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
854   if (ConEnd > uintptr_t(Data.getBufferEnd()))
855     return object_error::parse_failed;
856   Res = makeArrayRef(reinterpret_cast<const uint8_t*>(ConStart),
857                      Sec->SizeOfRawData);
858   return object_error::success;
859 }
860
861 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
862   return reinterpret_cast<const coff_relocation*>(Rel.p);
863 }
864
865 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
866   Rel.p = reinterpret_cast<uintptr_t>(
867             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
868 }
869
870 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
871                                                      uint64_t &Res) const {
872   report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
873 }
874
875 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
876                                                     uint64_t &Res) const {
877   Res = toRel(Rel)->VirtualAddress;
878   return object_error::success;
879 }
880
881 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
882   const coff_relocation *R = toRel(Rel);
883   DataRefImpl Ref;
884   if (SymbolTable16)
885     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
886   else if (SymbolTable32)
887     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
888   else
889     llvm_unreachable("no symbol table pointer!");
890   return symbol_iterator(SymbolRef(Ref, this));
891 }
892
893 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
894                                                   uint64_t &Res) const {
895   const coff_relocation* R = toRel(Rel);
896   Res = R->Type;
897   return object_error::success;
898 }
899
900 const coff_section *
901 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
902   return toSec(Section.getRawDataRefImpl());
903 }
904
905 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
906   if (SymbolTable16)
907     return toSymb<coff_symbol16>(Ref);
908   if (SymbolTable32)
909     return toSymb<coff_symbol32>(Ref);
910   llvm_unreachable("no symbol table pointer!");
911 }
912
913 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
914   return getCOFFSymbol(Symbol.getRawDataRefImpl());
915 }
916
917 const coff_relocation *
918 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
919   return toRel(Reloc.getRawDataRefImpl());
920 }
921
922 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
923   case COFF::reloc_type:                                                       \
924     Res = #reloc_type;                                                         \
925     break;
926
927 std::error_code
928 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
929                                       SmallVectorImpl<char> &Result) const {
930   const coff_relocation *Reloc = toRel(Rel);
931   StringRef Res;
932   switch (getMachine()) {
933   case COFF::IMAGE_FILE_MACHINE_AMD64:
934     switch (Reloc->Type) {
935     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
936     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
937     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
938     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
939     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
940     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
941     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
942     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
943     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
944     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
945     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
946     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
947     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
948     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
949     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
950     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
951     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
952     default:
953       Res = "Unknown";
954     }
955     break;
956   case COFF::IMAGE_FILE_MACHINE_ARMNT:
957     switch (Reloc->Type) {
958     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
959     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
960     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
961     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
962     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
963     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
964     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
965     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
966     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
967     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
968     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
969     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
970     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
971     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
972     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
973     default:
974       Res = "Unknown";
975     }
976     break;
977   case COFF::IMAGE_FILE_MACHINE_I386:
978     switch (Reloc->Type) {
979     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
980     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
981     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
982     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
983     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
984     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
985     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
986     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
987     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
988     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
989     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
990     default:
991       Res = "Unknown";
992     }
993     break;
994   default:
995     Res = "Unknown";
996   }
997   Result.append(Res.begin(), Res.end());
998   return object_error::success;
999 }
1000
1001 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1002
1003 std::error_code
1004 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
1005                                          SmallVectorImpl<char> &Result) const {
1006   const coff_relocation *Reloc = toRel(Rel);
1007   DataRefImpl Sym;
1008   ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1009   if (std::error_code EC = Symb.getError())
1010     return EC;
1011   Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1012   StringRef SymName;
1013   if (std::error_code EC = getSymbolName(Sym, SymName))
1014     return EC;
1015   Result.append(SymName.begin(), SymName.end());
1016   return object_error::success;
1017 }
1018
1019 bool COFFObjectFile::isRelocatableObject() const {
1020   return !DataDirectory;
1021 }
1022
1023 bool ImportDirectoryEntryRef::
1024 operator==(const ImportDirectoryEntryRef &Other) const {
1025   return ImportTable == Other.ImportTable && Index == Other.Index;
1026 }
1027
1028 void ImportDirectoryEntryRef::moveNext() {
1029   ++Index;
1030 }
1031
1032 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1033     const import_directory_table_entry *&Result) const {
1034   Result = ImportTable + Index;
1035   return object_error::success;
1036 }
1037
1038 static imported_symbol_iterator
1039 makeImportedSymbolIterator(const COFFObjectFile *OwningObject,
1040                            uintptr_t Ptr, int Index) {
1041   if (OwningObject->getBytesInAddress() == 4) {
1042     auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1043     return imported_symbol_iterator(ImportedSymbolRef(P, Index, OwningObject));
1044   }
1045   auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1046   return imported_symbol_iterator(ImportedSymbolRef(P, Index, OwningObject));
1047 }
1048
1049 imported_symbol_iterator
1050 ImportDirectoryEntryRef::imported_symbol_begin() const {
1051   uintptr_t IntPtr = 0;
1052   OwningObject->getRvaPtr(ImportTable[Index].ImportLookupTableRVA, IntPtr);
1053   return makeImportedSymbolIterator(OwningObject, IntPtr, 0);
1054 }
1055
1056 imported_symbol_iterator
1057 ImportDirectoryEntryRef::imported_symbol_end() const {
1058   uintptr_t IntPtr = 0;
1059   OwningObject->getRvaPtr(ImportTable[Index].ImportLookupTableRVA, IntPtr);
1060   // Forward the pointer to the last entry which is null.
1061   int Index = 0;
1062   if (OwningObject->getBytesInAddress() == 4) {
1063     auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1064     while (*Entry++)
1065       ++Index;
1066   } else {
1067     auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1068     while (*Entry++)
1069       ++Index;
1070   }
1071   return makeImportedSymbolIterator(OwningObject, IntPtr, Index);
1072 }
1073
1074 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1075   uintptr_t IntPtr = 0;
1076   if (std::error_code EC =
1077           OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1078     return EC;
1079   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1080   return object_error::success;
1081 }
1082
1083 std::error_code
1084 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t  &Result) const {
1085   Result = ImportTable[Index].ImportLookupTableRVA;
1086   return object_error::success;
1087 }
1088
1089 std::error_code
1090 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1091   Result = ImportTable[Index].ImportAddressTableRVA;
1092   return object_error::success;
1093 }
1094
1095 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1096     const import_lookup_table_entry32 *&Result) const {
1097   uintptr_t IntPtr = 0;
1098   uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1099   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1100     return EC;
1101   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1102   return object_error::success;
1103 }
1104
1105 bool ExportDirectoryEntryRef::
1106 operator==(const ExportDirectoryEntryRef &Other) const {
1107   return ExportTable == Other.ExportTable && Index == Other.Index;
1108 }
1109
1110 void ExportDirectoryEntryRef::moveNext() {
1111   ++Index;
1112 }
1113
1114 // Returns the name of the current export symbol. If the symbol is exported only
1115 // by ordinal, the empty string is set as a result.
1116 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1117   uintptr_t IntPtr = 0;
1118   if (std::error_code EC =
1119           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1120     return EC;
1121   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1122   return object_error::success;
1123 }
1124
1125 // Returns the starting ordinal number.
1126 std::error_code
1127 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1128   Result = ExportTable->OrdinalBase;
1129   return object_error::success;
1130 }
1131
1132 // Returns the export ordinal of the current export symbol.
1133 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1134   Result = ExportTable->OrdinalBase + Index;
1135   return object_error::success;
1136 }
1137
1138 // Returns the address of the current export symbol.
1139 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1140   uintptr_t IntPtr = 0;
1141   if (std::error_code EC =
1142           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1143     return EC;
1144   const export_address_table_entry *entry =
1145       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1146   Result = entry[Index].ExportRVA;
1147   return object_error::success;
1148 }
1149
1150 // Returns the name of the current export symbol. If the symbol is exported only
1151 // by ordinal, the empty string is set as a result.
1152 std::error_code
1153 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1154   uintptr_t IntPtr = 0;
1155   if (std::error_code EC =
1156           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1157     return EC;
1158   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1159
1160   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1161   int Offset = 0;
1162   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1163        I < E; ++I, ++Offset) {
1164     if (*I != Index)
1165       continue;
1166     if (std::error_code EC =
1167             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1168       return EC;
1169     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1170     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1171       return EC;
1172     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1173     return object_error::success;
1174   }
1175   Result = "";
1176   return object_error::success;
1177 }
1178
1179 bool ImportedSymbolRef::
1180 operator==(const ImportedSymbolRef &Other) const {
1181   return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1182       && Index == Other.Index;
1183 }
1184
1185 void ImportedSymbolRef::moveNext() {
1186   ++Index;
1187 }
1188
1189 std::error_code
1190 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1191   uint32_t RVA;
1192   if (Entry32) {
1193     // If a symbol is imported only by ordinal, it has no name.
1194     if (Entry32[Index].isOrdinal())
1195       return object_error::success;
1196     RVA = Entry32[Index].getHintNameRVA();
1197   } else {
1198     if (Entry64[Index].isOrdinal())
1199       return object_error::success;
1200     RVA = Entry64[Index].getHintNameRVA();
1201   }
1202   uintptr_t IntPtr = 0;
1203   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1204     return EC;
1205   // +2 because the first two bytes is hint.
1206   Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1207   return object_error::success;
1208 }
1209
1210 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1211   uint32_t RVA;
1212   if (Entry32) {
1213     if (Entry32[Index].isOrdinal()) {
1214       Result = Entry32[Index].getOrdinal();
1215       return object_error::success;
1216     }
1217     RVA = Entry32[Index].getHintNameRVA();
1218   } else {
1219     if (Entry64[Index].isOrdinal()) {
1220       Result = Entry64[Index].getOrdinal();
1221       return object_error::success;
1222     }
1223     RVA = Entry64[Index].getHintNameRVA();
1224   }
1225   uintptr_t IntPtr = 0;
1226   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1227     return EC;
1228   Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1229   return object_error::success;
1230 }
1231
1232 ErrorOr<std::unique_ptr<COFFObjectFile>>
1233 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1234   std::error_code EC;
1235   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1236   if (EC)
1237     return EC;
1238   return std::move(Ret);
1239 }