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