3e668552d9c65d6680bd8f9af539c0561a550ef7
[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 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
264   const coff_section *Sec = toSec(Ref);
265   return Sec->VirtualAddress;
266 }
267
268 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
269   const coff_section *Sec = toSec(Ref);
270   return Sec->SizeOfRawData;
271 }
272
273 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
274                                                    StringRef &Result) const {
275   const coff_section *Sec = toSec(Ref);
276   ArrayRef<uint8_t> Res;
277   std::error_code EC = getSectionContents(Sec, Res);
278   Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
279   return EC;
280 }
281
282 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
283   const coff_section *Sec = toSec(Ref);
284   return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
285 }
286
287 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
288   const coff_section *Sec = toSec(Ref);
289   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
290 }
291
292 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
293   const coff_section *Sec = toSec(Ref);
294   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
295 }
296
297 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
298   const coff_section *Sec = toSec(Ref);
299   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
300 }
301
302 bool COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref) const {
303   // FIXME: Unimplemented
304   return true;
305 }
306
307 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
308   const coff_section *Sec = toSec(Ref);
309   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
310 }
311
312 bool COFFObjectFile::isSectionZeroInit(DataRefImpl Ref) const {
313   // FIXME: Unimplemented.
314   return false;
315 }
316
317 bool COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref) const {
318   // FIXME: Unimplemented.
319   return false;
320 }
321
322 bool COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
323                                            DataRefImpl SymbRef) const {
324   const coff_section *Sec = toSec(SecRef);
325   COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
326   int32_t SecNumber = (Sec - SectionTable) + 1;
327   return SecNumber == Symb.getSectionNumber();
328 }
329
330 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
331   const coff_section *Sec = toSec(Ref);
332   DataRefImpl Ret;
333   if (Sec->NumberOfRelocations == 0) {
334     Ret.p = 0;
335   } else {
336     auto begin = reinterpret_cast<const coff_relocation*>(
337         base() + Sec->PointerToRelocations);
338     if (Sec->hasExtendedRelocations()) {
339       // Skip the first relocation entry repurposed to store the number of
340       // relocations.
341       begin++;
342     }
343     Ret.p = reinterpret_cast<uintptr_t>(begin);
344   }
345   return relocation_iterator(RelocationRef(Ret, this));
346 }
347
348 static uint32_t getNumberOfRelocations(const coff_section *Sec,
349                                        const uint8_t *base) {
350   // The field for the number of relocations in COFF section table is only
351   // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
352   // NumberOfRelocations field, and the actual relocation count is stored in the
353   // VirtualAddress field in the first relocation entry.
354   if (Sec->hasExtendedRelocations()) {
355     auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
356         base + Sec->PointerToRelocations);
357     return FirstReloc->VirtualAddress;
358   }
359   return Sec->NumberOfRelocations;
360 }
361
362 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
363   const coff_section *Sec = toSec(Ref);
364   DataRefImpl Ret;
365   if (Sec->NumberOfRelocations == 0) {
366     Ret.p = 0;
367   } else {
368     auto begin = reinterpret_cast<const coff_relocation*>(
369         base() + Sec->PointerToRelocations);
370     uint32_t NumReloc = getNumberOfRelocations(Sec, base());
371     Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
372   }
373   return relocation_iterator(RelocationRef(Ret, this));
374 }
375
376 // Initialize the pointer to the symbol table.
377 std::error_code COFFObjectFile::initSymbolTablePtr() {
378   if (COFFHeader)
379     if (std::error_code EC =
380             getObject(SymbolTable16, Data, base() + getPointerToSymbolTable(),
381                       getNumberOfSymbols() * getSymbolTableEntrySize()))
382       return EC;
383
384   if (COFFBigObjHeader)
385     if (std::error_code EC =
386             getObject(SymbolTable32, Data, base() + getPointerToSymbolTable(),
387                       getNumberOfSymbols() * getSymbolTableEntrySize()))
388       return EC;
389
390   // Find string table. The first four byte of the string table contains the
391   // total size of the string table, including the size field itself. If the
392   // string table is empty, the value of the first four byte would be 4.
393   const uint8_t *StringTableAddr =
394       base() + getPointerToSymbolTable() +
395       getNumberOfSymbols() * getSymbolTableEntrySize();
396   const ulittle32_t *StringTableSizePtr;
397   if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
398     return EC;
399   StringTableSize = *StringTableSizePtr;
400   if (std::error_code EC =
401           getObject(StringTable, Data, StringTableAddr, StringTableSize))
402     return EC;
403
404   // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
405   // tools like cvtres write a size of 0 for an empty table instead of 4.
406   if (StringTableSize < 4)
407       StringTableSize = 4;
408
409   // Check that the string table is null terminated if has any in it.
410   if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
411     return  object_error::parse_failed;
412   return object_error::success;
413 }
414
415 // Returns the file offset for the given VA.
416 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
417   uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
418                                   : (uint64_t)PE32PlusHeader->ImageBase;
419   uint64_t Rva = Addr - ImageBase;
420   assert(Rva <= UINT32_MAX);
421   return getRvaPtr((uint32_t)Rva, Res);
422 }
423
424 // Returns the file offset for the given RVA.
425 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
426   for (const SectionRef &S : sections()) {
427     const coff_section *Section = getCOFFSection(S);
428     uint32_t SectionStart = Section->VirtualAddress;
429     uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
430     if (SectionStart <= Addr && Addr < SectionEnd) {
431       uint32_t Offset = Addr - SectionStart;
432       Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
433       return object_error::success;
434     }
435   }
436   return object_error::parse_failed;
437 }
438
439 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
440 // table entry.
441 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
442                                             StringRef &Name) const {
443   uintptr_t IntPtr = 0;
444   if (std::error_code EC = getRvaPtr(Rva, IntPtr))
445     return EC;
446   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
447   Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
448   Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
449   return object_error::success;
450 }
451
452 // Find the import table.
453 std::error_code COFFObjectFile::initImportTablePtr() {
454   // First, we get the RVA of the import table. If the file lacks a pointer to
455   // the import table, do nothing.
456   const data_directory *DataEntry;
457   if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
458     return object_error::success;
459
460   // Do nothing if the pointer to import table is NULL.
461   if (DataEntry->RelativeVirtualAddress == 0)
462     return object_error::success;
463
464   uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
465   // -1 because the last entry is the null entry.
466   NumberOfImportDirectory = DataEntry->Size /
467       sizeof(import_directory_table_entry) - 1;
468
469   // Find the section that contains the RVA. This is needed because the RVA is
470   // the import table's memory address which is different from its file offset.
471   uintptr_t IntPtr = 0;
472   if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
473     return EC;
474   ImportDirectory = reinterpret_cast<
475       const import_directory_table_entry *>(IntPtr);
476   return object_error::success;
477 }
478
479 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
480 std::error_code COFFObjectFile::initDelayImportTablePtr() {
481   const data_directory *DataEntry;
482   if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
483     return object_error::success;
484   if (DataEntry->RelativeVirtualAddress == 0)
485     return object_error::success;
486
487   uint32_t RVA = DataEntry->RelativeVirtualAddress;
488   NumberOfDelayImportDirectory = DataEntry->Size /
489       sizeof(delay_import_directory_table_entry) - 1;
490
491   uintptr_t IntPtr = 0;
492   if (std::error_code EC = getRvaPtr(RVA, IntPtr))
493     return EC;
494   DelayImportDirectory = reinterpret_cast<
495       const delay_import_directory_table_entry *>(IntPtr);
496   return object_error::success;
497 }
498
499 // Find the export table.
500 std::error_code COFFObjectFile::initExportTablePtr() {
501   // First, we get the RVA of the export table. If the file lacks a pointer to
502   // the export table, do nothing.
503   const data_directory *DataEntry;
504   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
505     return object_error::success;
506
507   // Do nothing if the pointer to export table is NULL.
508   if (DataEntry->RelativeVirtualAddress == 0)
509     return object_error::success;
510
511   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
512   uintptr_t IntPtr = 0;
513   if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
514     return EC;
515   ExportDirectory =
516       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
517   return object_error::success;
518 }
519
520 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
521     : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
522       COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
523       DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
524       SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
525       ImportDirectory(nullptr), NumberOfImportDirectory(0),
526       DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
527       ExportDirectory(nullptr) {
528   // Check that we at least have enough room for a header.
529   if (!checkSize(Data, EC, sizeof(coff_file_header)))
530     return;
531
532   // The current location in the file where we are looking at.
533   uint64_t CurPtr = 0;
534
535   // PE header is optional and is present only in executables. If it exists,
536   // it is placed right after COFF header.
537   bool HasPEHeader = false;
538
539   // Check if this is a PE/COFF file.
540   if (base()[0] == 0x4d && base()[1] == 0x5a) {
541     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
542     // PE signature to find 'normal' COFF header.
543     if (!checkSize(Data, EC, 0x3c + 8))
544       return;
545     CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
546     // Check the PE magic bytes. ("PE\0\0")
547     if (std::memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) !=
548         0) {
549       EC = object_error::parse_failed;
550       return;
551     }
552     CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
553     HasPEHeader = true;
554   }
555
556   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
557     return;
558
559   // It might be a bigobj file, let's check.  Note that COFF bigobj and COFF
560   // import libraries share a common prefix but bigobj is more restrictive.
561   if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
562       COFFHeader->NumberOfSections == uint16_t(0xffff) &&
563       checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
564     if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
565       return;
566
567     // Verify that we are dealing with bigobj.
568     if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
569         std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
570                     sizeof(COFF::BigObjMagic)) == 0) {
571       COFFHeader = nullptr;
572       CurPtr += sizeof(coff_bigobj_file_header);
573     } else {
574       // It's not a bigobj.
575       COFFBigObjHeader = nullptr;
576     }
577   }
578   if (COFFHeader) {
579     // The prior checkSize call may have failed.  This isn't a hard error
580     // because we were just trying to sniff out bigobj.
581     EC = object_error::success;
582     CurPtr += sizeof(coff_file_header);
583
584     if (COFFHeader->isImportLibrary())
585       return;
586   }
587
588   if (HasPEHeader) {
589     const pe32_header *Header;
590     if ((EC = getObject(Header, Data, base() + CurPtr)))
591       return;
592
593     const uint8_t *DataDirAddr;
594     uint64_t DataDirSize;
595     if (Header->Magic == 0x10b) {
596       PE32Header = Header;
597       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
598       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
599     } else if (Header->Magic == 0x20b) {
600       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
601       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
602       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
603     } else {
604       // It's neither PE32 nor PE32+.
605       EC = object_error::parse_failed;
606       return;
607     }
608     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
609       return;
610     CurPtr += COFFHeader->SizeOfOptionalHeader;
611   }
612
613   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
614                       getNumberOfSections() * sizeof(coff_section))))
615     return;
616
617   // Initialize the pointer to the symbol table.
618   if (getPointerToSymbolTable() != 0)
619     if ((EC = initSymbolTablePtr()))
620       return;
621
622   // Initialize the pointer to the beginning of the import table.
623   if ((EC = initImportTablePtr()))
624     return;
625   if ((EC = initDelayImportTablePtr()))
626     return;
627
628   // Initialize the pointer to the export table.
629   if ((EC = initExportTablePtr()))
630     return;
631
632   EC = object_error::success;
633 }
634
635 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
636   DataRefImpl Ret;
637   Ret.p = getSymbolTable();
638   return basic_symbol_iterator(SymbolRef(Ret, this));
639 }
640
641 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
642   // The symbol table ends where the string table begins.
643   DataRefImpl Ret;
644   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
645   return basic_symbol_iterator(SymbolRef(Ret, this));
646 }
647
648 import_directory_iterator COFFObjectFile::import_directory_begin() const {
649   return import_directory_iterator(
650       ImportDirectoryEntryRef(ImportDirectory, 0, this));
651 }
652
653 import_directory_iterator COFFObjectFile::import_directory_end() const {
654   return import_directory_iterator(
655       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
656 }
657
658 delay_import_directory_iterator
659 COFFObjectFile::delay_import_directory_begin() const {
660   return delay_import_directory_iterator(
661       DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
662 }
663
664 delay_import_directory_iterator
665 COFFObjectFile::delay_import_directory_end() const {
666   return delay_import_directory_iterator(
667       DelayImportDirectoryEntryRef(
668           DelayImportDirectory, NumberOfDelayImportDirectory, this));
669 }
670
671 export_directory_iterator COFFObjectFile::export_directory_begin() const {
672   return export_directory_iterator(
673       ExportDirectoryEntryRef(ExportDirectory, 0, this));
674 }
675
676 export_directory_iterator COFFObjectFile::export_directory_end() const {
677   if (!ExportDirectory)
678     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
679   ExportDirectoryEntryRef Ref(ExportDirectory,
680                               ExportDirectory->AddressTableEntries, this);
681   return export_directory_iterator(Ref);
682 }
683
684 section_iterator COFFObjectFile::section_begin() const {
685   DataRefImpl Ret;
686   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
687   return section_iterator(SectionRef(Ret, this));
688 }
689
690 section_iterator COFFObjectFile::section_end() const {
691   DataRefImpl Ret;
692   int NumSections =
693       COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
694   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
695   return section_iterator(SectionRef(Ret, this));
696 }
697
698 uint8_t COFFObjectFile::getBytesInAddress() const {
699   return getArch() == Triple::x86_64 ? 8 : 4;
700 }
701
702 StringRef COFFObjectFile::getFileFormatName() const {
703   switch(getMachine()) {
704   case COFF::IMAGE_FILE_MACHINE_I386:
705     return "COFF-i386";
706   case COFF::IMAGE_FILE_MACHINE_AMD64:
707     return "COFF-x86-64";
708   case COFF::IMAGE_FILE_MACHINE_ARMNT:
709     return "COFF-ARM";
710   default:
711     return "COFF-<unknown arch>";
712   }
713 }
714
715 unsigned COFFObjectFile::getArch() const {
716   switch (getMachine()) {
717   case COFF::IMAGE_FILE_MACHINE_I386:
718     return Triple::x86;
719   case COFF::IMAGE_FILE_MACHINE_AMD64:
720     return Triple::x86_64;
721   case COFF::IMAGE_FILE_MACHINE_ARMNT:
722     return Triple::thumb;
723   default:
724     return Triple::UnknownArch;
725   }
726 }
727
728 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
729   Res = PE32Header;
730   return object_error::success;
731 }
732
733 std::error_code
734 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
735   Res = PE32PlusHeader;
736   return object_error::success;
737 }
738
739 std::error_code
740 COFFObjectFile::getDataDirectory(uint32_t Index,
741                                  const data_directory *&Res) const {
742   // Error if if there's no data directory or the index is out of range.
743   if (!DataDirectory)
744     return object_error::parse_failed;
745   assert(PE32Header || PE32PlusHeader);
746   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
747                                : PE32PlusHeader->NumberOfRvaAndSize;
748   if (Index > NumEnt)
749     return object_error::parse_failed;
750   Res = &DataDirectory[Index];
751   return object_error::success;
752 }
753
754 std::error_code COFFObjectFile::getSection(int32_t Index,
755                                            const coff_section *&Result) const {
756   // Check for special index values.
757   if (COFF::isReservedSectionNumber(Index))
758     Result = nullptr;
759   else if (Index > 0 && static_cast<uint32_t>(Index) <= getNumberOfSections())
760     // We already verified the section table data, so no need to check again.
761     Result = SectionTable + (Index - 1);
762   else
763     return object_error::parse_failed;
764   return object_error::success;
765 }
766
767 std::error_code COFFObjectFile::getString(uint32_t Offset,
768                                           StringRef &Result) const {
769   if (StringTableSize <= 4)
770     // Tried to get a string from an empty string table.
771     return object_error::parse_failed;
772   if (Offset >= StringTableSize)
773     return object_error::unexpected_eof;
774   Result = StringRef(StringTable + Offset);
775   return object_error::success;
776 }
777
778 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
779                                               StringRef &Res) const {
780   // Check for string table entry. First 4 bytes are 0.
781   if (Symbol.getStringTableOffset().Zeroes == 0) {
782     uint32_t Offset = Symbol.getStringTableOffset().Offset;
783     if (std::error_code EC = getString(Offset, Res))
784       return EC;
785     return object_error::success;
786   }
787
788   if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
789     // Null terminated, let ::strlen figure out the length.
790     Res = StringRef(Symbol.getShortName());
791   else
792     // Not null terminated, use all 8 bytes.
793     Res = StringRef(Symbol.getShortName(), COFF::NameSize);
794   return object_error::success;
795 }
796
797 ArrayRef<uint8_t>
798 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
799   const uint8_t *Aux = nullptr;
800
801   size_t SymbolSize = getSymbolTableEntrySize();
802   if (Symbol.getNumberOfAuxSymbols() > 0) {
803     // AUX data comes immediately after the symbol in COFF
804     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
805 # ifndef NDEBUG
806     // Verify that the Aux symbol points to a valid entry in the symbol table.
807     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
808     if (Offset < getPointerToSymbolTable() ||
809         Offset >=
810             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
811       report_fatal_error("Aux Symbol data was outside of symbol table.");
812
813     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
814            "Aux Symbol data did not point to the beginning of a symbol");
815 # endif
816   }
817   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
818 }
819
820 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
821                                                StringRef &Res) const {
822   StringRef Name;
823   if (Sec->Name[COFF::NameSize - 1] == 0)
824     // Null terminated, let ::strlen figure out the length.
825     Name = Sec->Name;
826   else
827     // Not null terminated, use all 8 bytes.
828     Name = StringRef(Sec->Name, COFF::NameSize);
829
830   // Check for string table entry. First byte is '/'.
831   if (Name[0] == '/') {
832     uint32_t Offset;
833     if (Name[1] == '/') {
834       if (decodeBase64StringEntry(Name.substr(2), Offset))
835         return object_error::parse_failed;
836     } else {
837       if (Name.substr(1).getAsInteger(10, Offset))
838         return object_error::parse_failed;
839     }
840     if (std::error_code EC = getString(Offset, Name))
841       return EC;
842   }
843
844   Res = Name;
845   return object_error::success;
846 }
847
848 std::error_code
849 COFFObjectFile::getSectionContents(const coff_section *Sec,
850                                    ArrayRef<uint8_t> &Res) const {
851   // PointerToRawData and SizeOfRawData won't make sense for BSS sections, don't
852   // do anything interesting for them.
853   assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
854          "BSS sections don't have contents!");
855   // The only thing that we need to verify is that the contents is contained
856   // within the file bounds. We don't need to make sure it doesn't cover other
857   // data, as there's nothing that says that is not allowed.
858   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
859   uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
860   if (ConEnd > uintptr_t(Data.getBufferEnd()))
861     return object_error::parse_failed;
862   Res = makeArrayRef(reinterpret_cast<const uint8_t*>(ConStart),
863                      Sec->SizeOfRawData);
864   return object_error::success;
865 }
866
867 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
868   return reinterpret_cast<const coff_relocation*>(Rel.p);
869 }
870
871 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
872   Rel.p = reinterpret_cast<uintptr_t>(
873             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
874 }
875
876 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
877                                                      uint64_t &Res) const {
878   report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
879 }
880
881 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
882                                                     uint64_t &Res) const {
883   Res = toRel(Rel)->VirtualAddress;
884   return object_error::success;
885 }
886
887 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
888   const coff_relocation *R = toRel(Rel);
889   DataRefImpl Ref;
890   if (SymbolTable16)
891     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
892   else if (SymbolTable32)
893     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
894   else
895     llvm_unreachable("no symbol table pointer!");
896   return symbol_iterator(SymbolRef(Ref, this));
897 }
898
899 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
900                                                   uint64_t &Res) const {
901   const coff_relocation* R = toRel(Rel);
902   Res = R->Type;
903   return object_error::success;
904 }
905
906 const coff_section *
907 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
908   return toSec(Section.getRawDataRefImpl());
909 }
910
911 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
912   if (SymbolTable16)
913     return toSymb<coff_symbol16>(Ref);
914   if (SymbolTable32)
915     return toSymb<coff_symbol32>(Ref);
916   llvm_unreachable("no symbol table pointer!");
917 }
918
919 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
920   return getCOFFSymbol(Symbol.getRawDataRefImpl());
921 }
922
923 const coff_relocation *
924 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
925   return toRel(Reloc.getRawDataRefImpl());
926 }
927
928 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
929   case COFF::reloc_type:                                                       \
930     Res = #reloc_type;                                                         \
931     break;
932
933 std::error_code
934 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
935                                       SmallVectorImpl<char> &Result) const {
936   const coff_relocation *Reloc = toRel(Rel);
937   StringRef Res;
938   switch (getMachine()) {
939   case COFF::IMAGE_FILE_MACHINE_AMD64:
940     switch (Reloc->Type) {
941     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
942     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
943     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
944     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
945     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
946     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
947     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
948     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
949     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
950     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
951     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
952     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
953     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
954     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
955     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
956     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
957     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
958     default:
959       Res = "Unknown";
960     }
961     break;
962   case COFF::IMAGE_FILE_MACHINE_ARMNT:
963     switch (Reloc->Type) {
964     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
965     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
966     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
967     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
968     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
969     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
970     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
971     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
972     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
973     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
974     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
975     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
976     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
977     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
978     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
979     default:
980       Res = "Unknown";
981     }
982     break;
983   case COFF::IMAGE_FILE_MACHINE_I386:
984     switch (Reloc->Type) {
985     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
986     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
987     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
988     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
989     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
990     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
991     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
992     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
993     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
994     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
995     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
996     default:
997       Res = "Unknown";
998     }
999     break;
1000   default:
1001     Res = "Unknown";
1002   }
1003   Result.append(Res.begin(), Res.end());
1004   return object_error::success;
1005 }
1006
1007 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1008
1009 std::error_code
1010 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
1011                                          SmallVectorImpl<char> &Result) const {
1012   const coff_relocation *Reloc = toRel(Rel);
1013   DataRefImpl Sym;
1014   ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1015   if (std::error_code EC = Symb.getError())
1016     return EC;
1017   Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1018   StringRef SymName;
1019   if (std::error_code EC = getSymbolName(Sym, SymName))
1020     return EC;
1021   Result.append(SymName.begin(), SymName.end());
1022   return object_error::success;
1023 }
1024
1025 bool COFFObjectFile::isRelocatableObject() const {
1026   return !DataDirectory;
1027 }
1028
1029 bool ImportDirectoryEntryRef::
1030 operator==(const ImportDirectoryEntryRef &Other) const {
1031   return ImportTable == Other.ImportTable && Index == Other.Index;
1032 }
1033
1034 void ImportDirectoryEntryRef::moveNext() {
1035   ++Index;
1036 }
1037
1038 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1039     const import_directory_table_entry *&Result) const {
1040   Result = ImportTable + Index;
1041   return object_error::success;
1042 }
1043
1044 static imported_symbol_iterator
1045 makeImportedSymbolIterator(const COFFObjectFile *Object,
1046                            uintptr_t Ptr, int Index) {
1047   if (Object->getBytesInAddress() == 4) {
1048     auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1049     return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1050   }
1051   auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1052   return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1053 }
1054
1055 static imported_symbol_iterator
1056 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1057   uintptr_t IntPtr = 0;
1058   Object->getRvaPtr(RVA, IntPtr);
1059   return makeImportedSymbolIterator(Object, IntPtr, 0);
1060 }
1061
1062 static imported_symbol_iterator
1063 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1064   uintptr_t IntPtr = 0;
1065   Object->getRvaPtr(RVA, IntPtr);
1066   // Forward the pointer to the last entry which is null.
1067   int Index = 0;
1068   if (Object->getBytesInAddress() == 4) {
1069     auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1070     while (*Entry++)
1071       ++Index;
1072   } else {
1073     auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1074     while (*Entry++)
1075       ++Index;
1076   }
1077   return makeImportedSymbolIterator(Object, IntPtr, Index);
1078 }
1079
1080 imported_symbol_iterator
1081 ImportDirectoryEntryRef::imported_symbol_begin() const {
1082   return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1083                              OwningObject);
1084 }
1085
1086 imported_symbol_iterator
1087 ImportDirectoryEntryRef::imported_symbol_end() const {
1088   return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1089                            OwningObject);
1090 }
1091
1092 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1093   uintptr_t IntPtr = 0;
1094   if (std::error_code EC =
1095           OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1096     return EC;
1097   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1098   return object_error::success;
1099 }
1100
1101 std::error_code
1102 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t  &Result) const {
1103   Result = ImportTable[Index].ImportLookupTableRVA;
1104   return object_error::success;
1105 }
1106
1107 std::error_code
1108 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1109   Result = ImportTable[Index].ImportAddressTableRVA;
1110   return object_error::success;
1111 }
1112
1113 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1114     const import_lookup_table_entry32 *&Result) const {
1115   uintptr_t IntPtr = 0;
1116   uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1117   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1118     return EC;
1119   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1120   return object_error::success;
1121 }
1122
1123 bool DelayImportDirectoryEntryRef::
1124 operator==(const DelayImportDirectoryEntryRef &Other) const {
1125   return Table == Other.Table && Index == Other.Index;
1126 }
1127
1128 void DelayImportDirectoryEntryRef::moveNext() {
1129   ++Index;
1130 }
1131
1132 imported_symbol_iterator
1133 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1134   return importedSymbolBegin(Table[Index].DelayImportNameTable,
1135                              OwningObject);
1136 }
1137
1138 imported_symbol_iterator
1139 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1140   return importedSymbolEnd(Table[Index].DelayImportNameTable,
1141                            OwningObject);
1142 }
1143
1144 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1145   uintptr_t IntPtr = 0;
1146   if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1147     return EC;
1148   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1149   return object_error::success;
1150 }
1151
1152 std::error_code DelayImportDirectoryEntryRef::
1153 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1154   Result = Table;
1155   return object_error::success;
1156 }
1157
1158 bool ExportDirectoryEntryRef::
1159 operator==(const ExportDirectoryEntryRef &Other) const {
1160   return ExportTable == Other.ExportTable && Index == Other.Index;
1161 }
1162
1163 void ExportDirectoryEntryRef::moveNext() {
1164   ++Index;
1165 }
1166
1167 // Returns the name of the current export symbol. If the symbol is exported only
1168 // by ordinal, the empty string is set as a result.
1169 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1170   uintptr_t IntPtr = 0;
1171   if (std::error_code EC =
1172           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1173     return EC;
1174   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1175   return object_error::success;
1176 }
1177
1178 // Returns the starting ordinal number.
1179 std::error_code
1180 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1181   Result = ExportTable->OrdinalBase;
1182   return object_error::success;
1183 }
1184
1185 // Returns the export ordinal of the current export symbol.
1186 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1187   Result = ExportTable->OrdinalBase + Index;
1188   return object_error::success;
1189 }
1190
1191 // Returns the address of the current export symbol.
1192 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1193   uintptr_t IntPtr = 0;
1194   if (std::error_code EC =
1195           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1196     return EC;
1197   const export_address_table_entry *entry =
1198       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1199   Result = entry[Index].ExportRVA;
1200   return object_error::success;
1201 }
1202
1203 // Returns the name of the current export symbol. If the symbol is exported only
1204 // by ordinal, the empty string is set as a result.
1205 std::error_code
1206 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1207   uintptr_t IntPtr = 0;
1208   if (std::error_code EC =
1209           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1210     return EC;
1211   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1212
1213   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1214   int Offset = 0;
1215   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1216        I < E; ++I, ++Offset) {
1217     if (*I != Index)
1218       continue;
1219     if (std::error_code EC =
1220             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1221       return EC;
1222     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1223     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1224       return EC;
1225     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1226     return object_error::success;
1227   }
1228   Result = "";
1229   return object_error::success;
1230 }
1231
1232 bool ImportedSymbolRef::
1233 operator==(const ImportedSymbolRef &Other) const {
1234   return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1235       && Index == Other.Index;
1236 }
1237
1238 void ImportedSymbolRef::moveNext() {
1239   ++Index;
1240 }
1241
1242 std::error_code
1243 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1244   uint32_t RVA;
1245   if (Entry32) {
1246     // If a symbol is imported only by ordinal, it has no name.
1247     if (Entry32[Index].isOrdinal())
1248       return object_error::success;
1249     RVA = Entry32[Index].getHintNameRVA();
1250   } else {
1251     if (Entry64[Index].isOrdinal())
1252       return object_error::success;
1253     RVA = Entry64[Index].getHintNameRVA();
1254   }
1255   uintptr_t IntPtr = 0;
1256   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1257     return EC;
1258   // +2 because the first two bytes is hint.
1259   Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1260   return object_error::success;
1261 }
1262
1263 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1264   uint32_t RVA;
1265   if (Entry32) {
1266     if (Entry32[Index].isOrdinal()) {
1267       Result = Entry32[Index].getOrdinal();
1268       return object_error::success;
1269     }
1270     RVA = Entry32[Index].getHintNameRVA();
1271   } else {
1272     if (Entry64[Index].isOrdinal()) {
1273       Result = Entry64[Index].getOrdinal();
1274       return object_error::success;
1275     }
1276     RVA = Entry64[Index].getHintNameRVA();
1277   }
1278   uintptr_t IntPtr = 0;
1279   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1280     return EC;
1281   Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1282   return object_error::success;
1283 }
1284
1285 ErrorOr<std::unique_ptr<COFFObjectFile>>
1286 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1287   std::error_code EC;
1288   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1289   if (EC)
1290     return EC;
1291   return std::move(Ret);
1292 }