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