Object/COFF: Support large relocation table.
[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 // Initialize the pointer to the symbol table.
414 error_code COFFObjectFile::initSymbolTablePtr() {
415   if (error_code EC = getObject(
416           SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
417           COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
418     return EC;
419
420   // Find string table. The first four byte of the string table contains the
421   // total size of the string table, including the size field itself. If the
422   // string table is empty, the value of the first four byte would be 4.
423   const uint8_t *StringTableAddr =
424       base() + COFFHeader->PointerToSymbolTable +
425       COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
426   const ulittle32_t *StringTableSizePtr;
427   if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
428     return EC;
429   StringTableSize = *StringTableSizePtr;
430   if (error_code EC =
431       getObject(StringTable, Data, StringTableAddr, StringTableSize))
432     return EC;
433
434   // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
435   // tools like cvtres write a size of 0 for an empty table instead of 4.
436   if (StringTableSize < 4)
437       StringTableSize = 4;
438
439   // Check that the string table is null terminated if has any in it.
440   if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
441     return  object_error::parse_failed;
442   return object_error::success;
443 }
444
445 // Returns the file offset for the given VA.
446 error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
447   uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
448                                   : (uint64_t)PE32PlusHeader->ImageBase;
449   uint64_t Rva = Addr - ImageBase;
450   assert(Rva <= UINT32_MAX);
451   return getRvaPtr((uint32_t)Rva, Res);
452 }
453
454 // Returns the file offset for the given RVA.
455 error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
456   for (const SectionRef &S : sections()) {
457     const coff_section *Section = getCOFFSection(S);
458     uint32_t SectionStart = Section->VirtualAddress;
459     uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
460     if (SectionStart <= Addr && Addr < SectionEnd) {
461       uint32_t Offset = Addr - SectionStart;
462       Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
463       return object_error::success;
464     }
465   }
466   return object_error::parse_failed;
467 }
468
469 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
470 // table entry.
471 error_code COFFObjectFile::
472 getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const {
473   uintptr_t IntPtr = 0;
474   if (error_code EC = getRvaPtr(Rva, IntPtr))
475     return EC;
476   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
477   Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
478   Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
479   return object_error::success;
480 }
481
482 // Find the import table.
483 error_code COFFObjectFile::initImportTablePtr() {
484   // First, we get the RVA of the import table. If the file lacks a pointer to
485   // the import table, do nothing.
486   const data_directory *DataEntry;
487   if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
488     return object_error::success;
489
490   // Do nothing if the pointer to import table is NULL.
491   if (DataEntry->RelativeVirtualAddress == 0)
492     return object_error::success;
493
494   uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
495   NumberOfImportDirectory = DataEntry->Size /
496       sizeof(import_directory_table_entry);
497
498   // Find the section that contains the RVA. This is needed because the RVA is
499   // the import table's memory address which is different from its file offset.
500   uintptr_t IntPtr = 0;
501   if (error_code EC = getRvaPtr(ImportTableRva, IntPtr))
502     return EC;
503   ImportDirectory = reinterpret_cast<
504       const import_directory_table_entry *>(IntPtr);
505   return object_error::success;
506 }
507
508 // Find the export table.
509 error_code COFFObjectFile::initExportTablePtr() {
510   // First, we get the RVA of the export table. If the file lacks a pointer to
511   // the export table, do nothing.
512   const data_directory *DataEntry;
513   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
514     return object_error::success;
515
516   // Do nothing if the pointer to export table is NULL.
517   if (DataEntry->RelativeVirtualAddress == 0)
518     return object_error::success;
519
520   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
521   uintptr_t IntPtr = 0;
522   if (error_code EC = getRvaPtr(ExportTableRva, IntPtr))
523     return EC;
524   ExportDirectory =
525       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
526   return object_error::success;
527 }
528
529 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC,
530                                bool BufferOwned)
531     : ObjectFile(Binary::ID_COFF, Object, BufferOwned), COFFHeader(0),
532       PE32Header(0), PE32PlusHeader(0), DataDirectory(0), SectionTable(0),
533       SymbolTable(0), StringTable(0), StringTableSize(0), ImportDirectory(0),
534       NumberOfImportDirectory(0), ExportDirectory(0) {
535   // Check that we at least have enough room for a header.
536   if (!checkSize(Data, EC, sizeof(coff_file_header))) return;
537
538   // The current location in the file where we are looking at.
539   uint64_t CurPtr = 0;
540
541   // PE header is optional and is present only in executables. If it exists,
542   // it is placed right after COFF header.
543   bool HasPEHeader = false;
544
545   // Check if this is a PE/COFF file.
546   if (base()[0] == 0x4d && base()[1] == 0x5a) {
547     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
548     // PE signature to find 'normal' COFF header.
549     if (!checkSize(Data, EC, 0x3c + 8)) return;
550     CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
551     // Check the PE magic bytes. ("PE\0\0")
552     if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
553       EC = object_error::parse_failed;
554       return;
555     }
556     CurPtr += 4; // Skip the PE magic bytes.
557     HasPEHeader = true;
558   }
559
560   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
561     return;
562   CurPtr += sizeof(coff_file_header);
563
564   if (HasPEHeader) {
565     const pe32_header *Header;
566     if ((EC = getObject(Header, Data, base() + CurPtr)))
567       return;
568
569     const uint8_t *DataDirAddr;
570     uint64_t DataDirSize;
571     if (Header->Magic == 0x10b) {
572       PE32Header = Header;
573       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
574       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
575     } else if (Header->Magic == 0x20b) {
576       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
577       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
578       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
579     } else {
580       // It's neither PE32 nor PE32+.
581       EC = object_error::parse_failed;
582       return;
583     }
584     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
585       return;
586     CurPtr += COFFHeader->SizeOfOptionalHeader;
587   }
588
589   if (COFFHeader->isImportLibrary())
590     return;
591
592   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
593                       COFFHeader->NumberOfSections * sizeof(coff_section))))
594     return;
595
596   // Initialize the pointer to the symbol table.
597   if (COFFHeader->PointerToSymbolTable != 0)
598     if ((EC = initSymbolTablePtr()))
599       return;
600
601   // Initialize the pointer to the beginning of the import table.
602   if ((EC = initImportTablePtr()))
603     return;
604
605   // Initialize the pointer to the export table.
606   if ((EC = initExportTablePtr()))
607     return;
608
609   EC = object_error::success;
610 }
611
612 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
613   DataRefImpl Ret;
614   Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
615   return basic_symbol_iterator(SymbolRef(Ret, this));
616 }
617
618 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
619   // The symbol table ends where the string table begins.
620   DataRefImpl Ret;
621   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
622   return basic_symbol_iterator(SymbolRef(Ret, this));
623 }
624
625 library_iterator COFFObjectFile::needed_library_begin() const {
626   // TODO: implement
627   report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
628 }
629
630 library_iterator COFFObjectFile::needed_library_end() const {
631   // TODO: implement
632   report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
633 }
634
635 StringRef COFFObjectFile::getLoadName() const {
636   // COFF does not have this field.
637   return "";
638 }
639
640 import_directory_iterator COFFObjectFile::import_directory_begin() const {
641   return import_directory_iterator(
642       ImportDirectoryEntryRef(ImportDirectory, 0, this));
643 }
644
645 import_directory_iterator COFFObjectFile::import_directory_end() const {
646   return import_directory_iterator(
647       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
648 }
649
650 export_directory_iterator COFFObjectFile::export_directory_begin() const {
651   return export_directory_iterator(
652       ExportDirectoryEntryRef(ExportDirectory, 0, this));
653 }
654
655 export_directory_iterator COFFObjectFile::export_directory_end() const {
656   if (ExportDirectory == 0)
657     return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this));
658   ExportDirectoryEntryRef Ref(ExportDirectory,
659                               ExportDirectory->AddressTableEntries, this);
660   return export_directory_iterator(Ref);
661 }
662
663 section_iterator COFFObjectFile::section_begin() const {
664   DataRefImpl Ret;
665   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
666   return section_iterator(SectionRef(Ret, this));
667 }
668
669 section_iterator COFFObjectFile::section_end() const {
670   DataRefImpl Ret;
671   int NumSections = COFFHeader->isImportLibrary()
672       ? 0 : COFFHeader->NumberOfSections;
673   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
674   return section_iterator(SectionRef(Ret, this));
675 }
676
677 uint8_t COFFObjectFile::getBytesInAddress() const {
678   return getArch() == Triple::x86_64 ? 8 : 4;
679 }
680
681 StringRef COFFObjectFile::getFileFormatName() const {
682   switch(COFFHeader->Machine) {
683   case COFF::IMAGE_FILE_MACHINE_I386:
684     return "COFF-i386";
685   case COFF::IMAGE_FILE_MACHINE_AMD64:
686     return "COFF-x86-64";
687   case COFF::IMAGE_FILE_MACHINE_ARMNT:
688     return "COFF-ARM";
689   default:
690     return "COFF-<unknown arch>";
691   }
692 }
693
694 unsigned COFFObjectFile::getArch() const {
695   switch(COFFHeader->Machine) {
696   case COFF::IMAGE_FILE_MACHINE_I386:
697     return Triple::x86;
698   case COFF::IMAGE_FILE_MACHINE_AMD64:
699     return Triple::x86_64;
700   case COFF::IMAGE_FILE_MACHINE_ARMNT:
701     return Triple::thumb;
702   default:
703     return Triple::UnknownArch;
704   }
705 }
706
707 // This method is kept here because lld uses this. As soon as we make
708 // lld to use getCOFFHeader, this method will be removed.
709 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
710   return getCOFFHeader(Res);
711 }
712
713 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
714   Res = COFFHeader;
715   return object_error::success;
716 }
717
718 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
719   Res = PE32Header;
720   return object_error::success;
721 }
722
723 error_code
724 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
725   Res = PE32PlusHeader;
726   return object_error::success;
727 }
728
729 error_code COFFObjectFile::getDataDirectory(uint32_t Index,
730                                             const data_directory *&Res) const {
731   // Error if if there's no data directory or the index is out of range.
732   if (!DataDirectory)
733     return object_error::parse_failed;
734   assert(PE32Header || PE32PlusHeader);
735   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
736                                : PE32PlusHeader->NumberOfRvaAndSize;
737   if (Index > NumEnt)
738     return object_error::parse_failed;
739   Res = &DataDirectory[Index];
740   return object_error::success;
741 }
742
743 error_code COFFObjectFile::getSection(int32_t Index,
744                                       const coff_section *&Result) const {
745   // Check for special index values.
746   if (COFF::isReservedSectionNumber(Index))
747     Result = NULL;
748   else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
749     // We already verified the section table data, so no need to check again.
750     Result = SectionTable + (Index - 1);
751   else
752     return object_error::parse_failed;
753   return object_error::success;
754 }
755
756 error_code COFFObjectFile::getString(uint32_t Offset,
757                                      StringRef &Result) const {
758   if (StringTableSize <= 4)
759     // Tried to get a string from an empty string table.
760     return object_error::parse_failed;
761   if (Offset >= StringTableSize)
762     return object_error::unexpected_eof;
763   Result = StringRef(StringTable + Offset);
764   return object_error::success;
765 }
766
767 error_code COFFObjectFile::getSymbol(uint32_t Index,
768                                      const coff_symbol *&Result) const {
769   if (Index < COFFHeader->NumberOfSymbols)
770     Result = SymbolTable + Index;
771   else
772     return object_error::parse_failed;
773   return object_error::success;
774 }
775
776 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
777                                          StringRef &Res) const {
778   // Check for string table entry. First 4 bytes are 0.
779   if (Symbol->Name.Offset.Zeroes == 0) {
780     uint32_t Offset = Symbol->Name.Offset.Offset;
781     if (error_code EC = getString(Offset, Res))
782       return EC;
783     return object_error::success;
784   }
785
786   if (Symbol->Name.ShortName[7] == 0)
787     // Null terminated, let ::strlen figure out the length.
788     Res = StringRef(Symbol->Name.ShortName);
789   else
790     // Not null terminated, use all 8 bytes.
791     Res = StringRef(Symbol->Name.ShortName, 8);
792   return object_error::success;
793 }
794
795 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
796                                   const coff_symbol *Symbol) const {
797   const uint8_t *Aux = NULL;
798
799   if (Symbol->NumberOfAuxSymbols > 0) {
800   // AUX data comes immediately after the symbol in COFF
801     Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
802 # ifndef NDEBUG
803     // Verify that the Aux symbol points to a valid entry in the symbol table.
804     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
805     if (Offset < COFFHeader->PointerToSymbolTable
806         || Offset >= COFFHeader->PointerToSymbolTable
807            + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
808       report_fatal_error("Aux Symbol data was outside of symbol table.");
809
810     assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
811          == 0 && "Aux Symbol data did not point to the beginning of a symbol");
812 # endif
813   }
814   return ArrayRef<uint8_t>(Aux,
815                            Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
816 }
817
818 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
819                                           StringRef &Res) const {
820   StringRef Name;
821   if (Sec->Name[7] == 0)
822     // Null terminated, let ::strlen figure out the length.
823     Name = Sec->Name;
824   else
825     // Not null terminated, use all 8 bytes.
826     Name = StringRef(Sec->Name, 8);
827
828   // Check for string table entry. First byte is '/'.
829   if (Name[0] == '/') {
830     uint32_t Offset;
831     if (Name[1] == '/') {
832       if (decodeBase64StringEntry(Name.substr(2), Offset))
833         return object_error::parse_failed;
834     } else {
835       if (Name.substr(1).getAsInteger(10, Offset))
836         return object_error::parse_failed;
837     }
838     if (error_code EC = getString(Offset, Name))
839       return EC;
840   }
841
842   Res = Name;
843   return object_error::success;
844 }
845
846 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
847                                               ArrayRef<uint8_t> &Res) const {
848   // The only thing that we need to verify is that the contents is contained
849   // within the file bounds. We don't need to make sure it doesn't cover other
850   // data, as there's nothing that says that is not allowed.
851   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
852   uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
853   if (ConEnd > uintptr_t(Data->getBufferEnd()))
854     return object_error::parse_failed;
855   Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
856                           Sec->SizeOfRawData);
857   return object_error::success;
858 }
859
860 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
861   return reinterpret_cast<const coff_relocation*>(Rel.p);
862 }
863
864 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
865   Rel.p = reinterpret_cast<uintptr_t>(
866             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
867 }
868
869 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
870                                                 uint64_t &Res) const {
871   report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
872 }
873
874 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
875                                                uint64_t &Res) const {
876   Res = toRel(Rel)->VirtualAddress;
877   return object_error::success;
878 }
879
880 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
881   const coff_relocation* R = toRel(Rel);
882   DataRefImpl Ref;
883   Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
884   return symbol_iterator(SymbolRef(Ref, this));
885 }
886
887 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
888                                              uint64_t &Res) const {
889   const coff_relocation* R = toRel(Rel);
890   Res = R->Type;
891   return object_error::success;
892 }
893
894 const coff_section *
895 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
896   return toSec(Section.getRawDataRefImpl());
897 }
898
899 const coff_symbol *
900 COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
901   return toSymb(Symbol.getRawDataRefImpl());
902 }
903
904 const coff_relocation *
905 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
906   return toRel(Reloc.getRawDataRefImpl());
907 }
908
909 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
910   case COFF::reloc_type:                                                       \
911     Res = #reloc_type;                                                         \
912     break;
913
914 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
915                                           SmallVectorImpl<char> &Result) const {
916   const coff_relocation *Reloc = toRel(Rel);
917   StringRef Res;
918   switch (COFFHeader->Machine) {
919   case COFF::IMAGE_FILE_MACHINE_AMD64:
920     switch (Reloc->Type) {
921     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
922     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
923     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
924     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
925     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
926     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
927     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
928     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
929     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
930     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
931     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
932     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
933     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
934     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
935     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
936     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
937     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
938     default:
939       Res = "Unknown";
940     }
941     break;
942   case COFF::IMAGE_FILE_MACHINE_I386:
943     switch (Reloc->Type) {
944     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
945     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
946     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
947     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
948     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
949     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
950     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
951     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
952     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
953     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
954     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
955     default:
956       Res = "Unknown";
957     }
958     break;
959   default:
960     Res = "Unknown";
961   }
962   Result.append(Res.begin(), Res.end());
963   return object_error::success;
964 }
965
966 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
967
968 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
969                                           SmallVectorImpl<char> &Result) const {
970   const coff_relocation *Reloc = toRel(Rel);
971   const coff_symbol *Symb = 0;
972   if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
973   DataRefImpl Sym;
974   Sym.p = reinterpret_cast<uintptr_t>(Symb);
975   StringRef SymName;
976   if (error_code EC = getSymbolName(Sym, SymName)) return EC;
977   Result.append(SymName.begin(), SymName.end());
978   return object_error::success;
979 }
980
981 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
982                                           LibraryRef &Result) const {
983   report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
984 }
985
986 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
987                                           StringRef &Result) const {
988   report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
989 }
990
991 bool ImportDirectoryEntryRef::
992 operator==(const ImportDirectoryEntryRef &Other) const {
993   return ImportTable == Other.ImportTable && Index == Other.Index;
994 }
995
996 void ImportDirectoryEntryRef::moveNext() {
997   ++Index;
998 }
999
1000 error_code ImportDirectoryEntryRef::
1001 getImportTableEntry(const import_directory_table_entry *&Result) const {
1002   Result = ImportTable;
1003   return object_error::success;
1004 }
1005
1006 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1007   uintptr_t IntPtr = 0;
1008   if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
1009     return EC;
1010   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1011   return object_error::success;
1012 }
1013
1014 error_code ImportDirectoryEntryRef::getImportLookupEntry(
1015     const import_lookup_table_entry32 *&Result) const {
1016   uintptr_t IntPtr = 0;
1017   if (error_code EC =
1018           OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
1019     return EC;
1020   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1021   return object_error::success;
1022 }
1023
1024 bool ExportDirectoryEntryRef::
1025 operator==(const ExportDirectoryEntryRef &Other) const {
1026   return ExportTable == Other.ExportTable && Index == Other.Index;
1027 }
1028
1029 void ExportDirectoryEntryRef::moveNext() {
1030   ++Index;
1031 }
1032
1033 // Returns the name of the current export symbol. If the symbol is exported only
1034 // by ordinal, the empty string is set as a result.
1035 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1036   uintptr_t IntPtr = 0;
1037   if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1038     return EC;
1039   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1040   return object_error::success;
1041 }
1042
1043 // Returns the starting ordinal number.
1044 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1045   Result = ExportTable->OrdinalBase;
1046   return object_error::success;
1047 }
1048
1049 // Returns the export ordinal of the current export symbol.
1050 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1051   Result = ExportTable->OrdinalBase + Index;
1052   return object_error::success;
1053 }
1054
1055 // Returns the address of the current export symbol.
1056 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1057   uintptr_t IntPtr = 0;
1058   if (error_code EC = OwningObject->getRvaPtr(
1059           ExportTable->ExportAddressTableRVA, IntPtr))
1060     return EC;
1061   const export_address_table_entry *entry =
1062       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1063   Result = entry[Index].ExportRVA;
1064   return object_error::success;
1065 }
1066
1067 // Returns the name of the current export symbol. If the symbol is exported only
1068 // by ordinal, the empty string is set as a result.
1069 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1070   uintptr_t IntPtr = 0;
1071   if (error_code EC = OwningObject->getRvaPtr(
1072           ExportTable->OrdinalTableRVA, IntPtr))
1073     return EC;
1074   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1075
1076   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1077   int Offset = 0;
1078   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1079        I < E; ++I, ++Offset) {
1080     if (*I != Index)
1081       continue;
1082     if (error_code EC = OwningObject->getRvaPtr(
1083             ExportTable->NamePointerRVA, IntPtr))
1084       return EC;
1085     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1086     if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1087       return EC;
1088     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1089     return object_error::success;
1090   }
1091   Result = "";
1092   return object_error::success;
1093 }
1094
1095 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object,
1096                                                        bool BufferOwned) {
1097   error_code EC;
1098   std::unique_ptr<COFFObjectFile> Ret(
1099       new COFFObjectFile(Object, EC, BufferOwned));
1100   if (EC)
1101     return EC;
1102   return Ret.release();
1103 }