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