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