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