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