Simplify the handling of iterators in 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 symbol_iterator COFFObjectFile::begin_dynamic_symbols() const {
554   // TODO: implement
555   report_fatal_error("Dynamic symbols unimplemented in COFFObjectFile");
556 }
557
558 symbol_iterator COFFObjectFile::end_dynamic_symbols() const {
559   // TODO: implement
560   report_fatal_error("Dynamic symbols unimplemented in COFFObjectFile");
561 }
562
563 library_iterator COFFObjectFile::begin_libraries_needed() const {
564   // TODO: implement
565   report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
566 }
567
568 library_iterator COFFObjectFile::end_libraries_needed() const {
569   // TODO: implement
570   report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
571 }
572
573 StringRef COFFObjectFile::getLoadName() const {
574   // COFF does not have this field.
575   return "";
576 }
577
578 import_directory_iterator COFFObjectFile::import_directory_begin() const {
579   return import_directory_iterator(
580       ImportDirectoryEntryRef(ImportDirectory, 0, this));
581 }
582
583 import_directory_iterator COFFObjectFile::import_directory_end() const {
584   return import_directory_iterator(
585       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
586 }
587
588 export_directory_iterator COFFObjectFile::export_directory_begin() const {
589   return export_directory_iterator(
590       ExportDirectoryEntryRef(ExportDirectory, 0, this));
591 }
592
593 export_directory_iterator COFFObjectFile::export_directory_end() const {
594   if (ExportDirectory == 0)
595     return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this));
596   ExportDirectoryEntryRef Ref(ExportDirectory,
597                               ExportDirectory->AddressTableEntries, this);
598   return export_directory_iterator(Ref);
599 }
600
601 section_iterator COFFObjectFile::begin_sections() const {
602   DataRefImpl Ret;
603   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
604   return section_iterator(SectionRef(Ret, this));
605 }
606
607 section_iterator COFFObjectFile::end_sections() const {
608   DataRefImpl Ret;
609   int NumSections = COFFHeader->isImportLibrary()
610       ? 0 : COFFHeader->NumberOfSections;
611   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
612   return section_iterator(SectionRef(Ret, this));
613 }
614
615 uint8_t COFFObjectFile::getBytesInAddress() const {
616   return getArch() == Triple::x86_64 ? 8 : 4;
617 }
618
619 StringRef COFFObjectFile::getFileFormatName() const {
620   switch(COFFHeader->Machine) {
621   case COFF::IMAGE_FILE_MACHINE_I386:
622     return "COFF-i386";
623   case COFF::IMAGE_FILE_MACHINE_AMD64:
624     return "COFF-x86-64";
625   default:
626     return "COFF-<unknown arch>";
627   }
628 }
629
630 unsigned COFFObjectFile::getArch() const {
631   switch(COFFHeader->Machine) {
632   case COFF::IMAGE_FILE_MACHINE_I386:
633     return Triple::x86;
634   case COFF::IMAGE_FILE_MACHINE_AMD64:
635     return Triple::x86_64;
636   default:
637     return Triple::UnknownArch;
638   }
639 }
640
641 // This method is kept here because lld uses this. As soon as we make
642 // lld to use getCOFFHeader, this method will be removed.
643 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
644   return getCOFFHeader(Res);
645 }
646
647 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
648   Res = COFFHeader;
649   return object_error::success;
650 }
651
652 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
653   Res = PE32Header;
654   return object_error::success;
655 }
656
657 error_code
658 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
659   Res = PE32PlusHeader;
660   return object_error::success;
661 }
662
663 error_code COFFObjectFile::getDataDirectory(uint32_t Index,
664                                             const data_directory *&Res) const {
665   // Error if if there's no data directory or the index is out of range.
666   if (!DataDirectory)
667     return object_error::parse_failed;
668   assert(PE32Header || PE32PlusHeader);
669   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
670                                : PE32PlusHeader->NumberOfRvaAndSize;
671   if (Index > NumEnt)
672     return object_error::parse_failed;
673   Res = &DataDirectory[Index];
674   return object_error::success;
675 }
676
677 error_code COFFObjectFile::getSection(int32_t Index,
678                                       const coff_section *&Result) const {
679   // Check for special index values.
680   if (Index == COFF::IMAGE_SYM_UNDEFINED ||
681       Index == COFF::IMAGE_SYM_ABSOLUTE ||
682       Index == COFF::IMAGE_SYM_DEBUG)
683     Result = NULL;
684   else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
685     // We already verified the section table data, so no need to check again.
686     Result = SectionTable + (Index - 1);
687   else
688     return object_error::parse_failed;
689   return object_error::success;
690 }
691
692 error_code COFFObjectFile::getString(uint32_t Offset,
693                                      StringRef &Result) const {
694   if (StringTableSize <= 4)
695     // Tried to get a string from an empty string table.
696     return object_error::parse_failed;
697   if (Offset >= StringTableSize)
698     return object_error::unexpected_eof;
699   Result = StringRef(StringTable + Offset);
700   return object_error::success;
701 }
702
703 error_code COFFObjectFile::getSymbol(uint32_t Index,
704                                      const coff_symbol *&Result) const {
705   if (Index < COFFHeader->NumberOfSymbols)
706     Result = SymbolTable + Index;
707   else
708     return object_error::parse_failed;
709   return object_error::success;
710 }
711
712 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
713                                          StringRef &Res) const {
714   // Check for string table entry. First 4 bytes are 0.
715   if (Symbol->Name.Offset.Zeroes == 0) {
716     uint32_t Offset = Symbol->Name.Offset.Offset;
717     if (error_code EC = getString(Offset, Res))
718       return EC;
719     return object_error::success;
720   }
721
722   if (Symbol->Name.ShortName[7] == 0)
723     // Null terminated, let ::strlen figure out the length.
724     Res = StringRef(Symbol->Name.ShortName);
725   else
726     // Not null terminated, use all 8 bytes.
727     Res = StringRef(Symbol->Name.ShortName, 8);
728   return object_error::success;
729 }
730
731 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
732                                   const coff_symbol *Symbol) const {
733   const uint8_t *Aux = NULL;
734
735   if (Symbol->NumberOfAuxSymbols > 0) {
736   // AUX data comes immediately after the symbol in COFF
737     Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
738 # ifndef NDEBUG
739     // Verify that the Aux symbol points to a valid entry in the symbol table.
740     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
741     if (Offset < COFFHeader->PointerToSymbolTable
742         || Offset >= COFFHeader->PointerToSymbolTable
743            + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
744       report_fatal_error("Aux Symbol data was outside of symbol table.");
745
746     assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
747          == 0 && "Aux Symbol data did not point to the beginning of a symbol");
748 # endif
749   }
750   return ArrayRef<uint8_t>(Aux,
751                            Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
752 }
753
754 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
755                                           StringRef &Res) const {
756   StringRef Name;
757   if (Sec->Name[7] == 0)
758     // Null terminated, let ::strlen figure out the length.
759     Name = Sec->Name;
760   else
761     // Not null terminated, use all 8 bytes.
762     Name = StringRef(Sec->Name, 8);
763
764   // Check for string table entry. First byte is '/'.
765   if (Name[0] == '/') {
766     uint32_t Offset;
767     if (Name.substr(1).getAsInteger(10, Offset))
768       return object_error::parse_failed;
769     if (error_code EC = getString(Offset, Name))
770       return EC;
771   }
772
773   Res = Name;
774   return object_error::success;
775 }
776
777 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
778                                               ArrayRef<uint8_t> &Res) const {
779   // The only thing that we need to verify is that the contents is contained
780   // within the file bounds. We don't need to make sure it doesn't cover other
781   // data, as there's nothing that says that is not allowed.
782   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
783   uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
784   if (ConEnd > uintptr_t(Data->getBufferEnd()))
785     return object_error::parse_failed;
786   Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
787                           Sec->SizeOfRawData);
788   return object_error::success;
789 }
790
791 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
792   return reinterpret_cast<const coff_relocation*>(Rel.p);
793 }
794
795 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
796   Rel.p = reinterpret_cast<uintptr_t>(
797             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
798 }
799
800 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
801                                                 uint64_t &Res) const {
802   report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
803 }
804
805 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
806                                                uint64_t &Res) const {
807   Res = toRel(Rel)->VirtualAddress;
808   return object_error::success;
809 }
810
811 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
812   const coff_relocation* R = toRel(Rel);
813   DataRefImpl Ref;
814   Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
815   return symbol_iterator(SymbolRef(Ref, this));
816 }
817
818 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
819                                              uint64_t &Res) const {
820   const coff_relocation* R = toRel(Rel);
821   Res = R->Type;
822   return object_error::success;
823 }
824
825 const coff_section *COFFObjectFile::getCOFFSection(section_iterator &It) const {
826   return toSec(It->getRawDataRefImpl());
827 }
828
829 const coff_symbol *COFFObjectFile::getCOFFSymbol(symbol_iterator &It) const {
830   return toSymb(It->getRawDataRefImpl());
831 }
832
833 const coff_relocation *COFFObjectFile::getCOFFRelocation(
834                                              relocation_iterator &It) const {
835   return toRel(It->getRawDataRefImpl());
836 }
837
838 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(enum) \
839   case COFF::enum: Res = #enum; break;
840
841 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
842                                           SmallVectorImpl<char> &Result) const {
843   const coff_relocation *Reloc = toRel(Rel);
844   StringRef Res;
845   switch (COFFHeader->Machine) {
846   case COFF::IMAGE_FILE_MACHINE_AMD64:
847     switch (Reloc->Type) {
848     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
849     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
850     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
851     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
852     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
853     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
854     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
855     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
856     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
857     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
858     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
859     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
860     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
861     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
862     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
863     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
864     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
865     default:
866       Res = "Unknown";
867     }
868     break;
869   case COFF::IMAGE_FILE_MACHINE_I386:
870     switch (Reloc->Type) {
871     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
872     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
873     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
874     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
875     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
876     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
877     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
878     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
879     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
880     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
881     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
882     default:
883       Res = "Unknown";
884     }
885     break;
886   default:
887     Res = "Unknown";
888   }
889   Result.append(Res.begin(), Res.end());
890   return object_error::success;
891 }
892
893 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
894
895 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
896                                           SmallVectorImpl<char> &Result) const {
897   const coff_relocation *Reloc = toRel(Rel);
898   const coff_symbol *Symb = 0;
899   if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
900   DataRefImpl Sym;
901   Sym.p = reinterpret_cast<uintptr_t>(Symb);
902   StringRef SymName;
903   if (error_code EC = getSymbolName(Sym, SymName)) return EC;
904   Result.append(SymName.begin(), SymName.end());
905   return object_error::success;
906 }
907
908 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
909                                           LibraryRef &Result) const {
910   report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
911 }
912
913 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
914                                           StringRef &Result) const {
915   report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
916 }
917
918 bool ImportDirectoryEntryRef::
919 operator==(const ImportDirectoryEntryRef &Other) const {
920   return ImportTable == Other.ImportTable && Index == Other.Index;
921 }
922
923 void ImportDirectoryEntryRef::moveNext() {
924   ++Index;
925 }
926
927 error_code ImportDirectoryEntryRef::
928 getImportTableEntry(const import_directory_table_entry *&Result) const {
929   Result = ImportTable;
930   return object_error::success;
931 }
932
933 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
934   uintptr_t IntPtr = 0;
935   if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
936     return EC;
937   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
938   return object_error::success;
939 }
940
941 error_code ImportDirectoryEntryRef::getImportLookupEntry(
942     const import_lookup_table_entry32 *&Result) const {
943   uintptr_t IntPtr = 0;
944   if (error_code EC =
945           OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
946     return EC;
947   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
948   return object_error::success;
949 }
950
951 bool ExportDirectoryEntryRef::
952 operator==(const ExportDirectoryEntryRef &Other) const {
953   return ExportTable == Other.ExportTable && Index == Other.Index;
954 }
955
956 void ExportDirectoryEntryRef::moveNext() {
957   ++Index;
958 }
959
960 // Returns the name of the current export symbol. If the symbol is exported only
961 // by ordinal, the empty string is set as a result.
962 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
963   uintptr_t IntPtr = 0;
964   if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
965     return EC;
966   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
967   return object_error::success;
968 }
969
970 // Returns the starting ordinal number.
971 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
972   Result = ExportTable->OrdinalBase;
973   return object_error::success;
974 }
975
976 // Returns the export ordinal of the current export symbol.
977 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
978   Result = ExportTable->OrdinalBase + Index;
979   return object_error::success;
980 }
981
982 // Returns the address of the current export symbol.
983 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
984   uintptr_t IntPtr = 0;
985   if (error_code EC = OwningObject->getRvaPtr(
986           ExportTable->ExportAddressTableRVA, IntPtr))
987     return EC;
988   const export_address_table_entry *entry =
989       reinterpret_cast<const export_address_table_entry *>(IntPtr);
990   Result = entry[Index].ExportRVA;
991   return object_error::success;
992 }
993
994 // Returns the name of the current export symbol. If the symbol is exported only
995 // by ordinal, the empty string is set as a result.
996 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
997   uintptr_t IntPtr = 0;
998   if (error_code EC = OwningObject->getRvaPtr(
999           ExportTable->OrdinalTableRVA, IntPtr))
1000     return EC;
1001   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1002
1003   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1004   int Offset = 0;
1005   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1006        I < E; ++I, ++Offset) {
1007     if (*I != Index)
1008       continue;
1009     if (error_code EC = OwningObject->getRvaPtr(
1010             ExportTable->NamePointerRVA, IntPtr))
1011       return EC;
1012     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1013     if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1014       return EC;
1015     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1016     return object_error::success;
1017   }
1018   Result = "";
1019   return object_error::success;
1020 }
1021
1022 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object,
1023                                                        bool BufferOwned) {
1024   error_code EC;
1025   OwningPtr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC, BufferOwned));
1026   if (EC)
1027     return EC;
1028   return Ret.take();
1029 }