Fix a nomenclature error in llvm-nm.
[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->isFunctionDefinition()) {
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 &Result) const {
257   const coff_symbol *Symb = toSymb(Ref);
258
259   if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
260     Result = UnknownAddressOrSize;
261   else
262     Result = Symb->Value;
263
264   return object_error::success;
265 }
266
267 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
268   const coff_section *Sec = toSec(Ref);
269   Sec += 1;
270   Ref.p = reinterpret_cast<uintptr_t>(Sec);
271 }
272
273 error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
274                                           StringRef &Result) const {
275   const coff_section *Sec = toSec(Ref);
276   return getSectionName(Sec, Result);
277 }
278
279 error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
280                                              uint64_t &Result) const {
281   const coff_section *Sec = toSec(Ref);
282   Result = Sec->VirtualAddress;
283   return object_error::success;
284 }
285
286 error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
287                                           uint64_t &Result) const {
288   const coff_section *Sec = toSec(Ref);
289   Result = Sec->SizeOfRawData;
290   return object_error::success;
291 }
292
293 error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
294                                               StringRef &Result) const {
295   const coff_section *Sec = toSec(Ref);
296   ArrayRef<uint8_t> Res;
297   error_code EC = getSectionContents(Sec, Res);
298   Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
299   return EC;
300 }
301
302 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
303                                                uint64_t &Res) const {
304   const coff_section *Sec = toSec(Ref);
305   if (!Sec)
306     return object_error::parse_failed;
307   Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
308   return object_error::success;
309 }
310
311 error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
312                                          bool &Result) const {
313   const coff_section *Sec = toSec(Ref);
314   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
315   return object_error::success;
316 }
317
318 error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
319                                          bool &Result) const {
320   const coff_section *Sec = toSec(Ref);
321   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
322   return object_error::success;
323 }
324
325 error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
326                                         bool &Result) const {
327   const coff_section *Sec = toSec(Ref);
328   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
329   return object_error::success;
330 }
331
332 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
333                                                          bool &Result) const {
334   // FIXME: Unimplemented
335   Result = true;
336   return object_error::success;
337 }
338
339 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
340                                            bool &Result) const {
341   const coff_section *Sec = toSec(Ref);
342   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
343   return object_error::success;
344 }
345
346 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
347                                              bool &Result) const {
348   // FIXME: Unimplemented.
349   Result = false;
350   return object_error::success;
351 }
352
353 error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
354                                                 bool &Result) const {
355   // FIXME: Unimplemented.
356   Result = false;
357   return object_error::success;
358 }
359
360 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
361                                                  DataRefImpl SymbRef,
362                                                  bool &Result) const {
363   const coff_section *Sec = toSec(SecRef);
364   const coff_symbol *Symb = toSymb(SymbRef);
365   const coff_section *SymbSec = 0;
366   if (error_code EC = getSection(Symb->SectionNumber, SymbSec)) return EC;
367   if (SymbSec == Sec)
368     Result = true;
369   else
370     Result = false;
371   return object_error::success;
372 }
373
374 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
375   const coff_section *Sec = toSec(Ref);
376   DataRefImpl Ret;
377   if (Sec->NumberOfRelocations == 0) {
378     Ret.p = 0;
379   } else {
380     auto begin = reinterpret_cast<const coff_relocation*>(
381         base() + Sec->PointerToRelocations);
382     if (Sec->hasExtendedRelocations()) {
383       // Skip the first relocation entry repurposed to store the number of
384       // relocations.
385       begin++;
386     }
387     Ret.p = reinterpret_cast<uintptr_t>(begin);
388   }
389   return relocation_iterator(RelocationRef(Ret, this));
390 }
391
392 static uint32_t getNumberOfRelocations(const coff_section *Sec,
393                                        const uint8_t *base) {
394   // The field for the number of relocations in COFF section table is only
395   // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
396   // NumberOfRelocations field, and the actual relocation count is stored in the
397   // VirtualAddress field in the first relocation entry.
398   if (Sec->hasExtendedRelocations()) {
399     auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
400         base + Sec->PointerToRelocations);
401     return FirstReloc->VirtualAddress;
402   }
403   return Sec->NumberOfRelocations;
404 }
405
406 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
407   const coff_section *Sec = toSec(Ref);
408   DataRefImpl Ret;
409   if (Sec->NumberOfRelocations == 0) {
410     Ret.p = 0;
411   } else {
412     auto begin = reinterpret_cast<const coff_relocation*>(
413         base() + Sec->PointerToRelocations);
414     uint32_t NumReloc = getNumberOfRelocations(Sec, base());
415     Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
416   }
417   return relocation_iterator(RelocationRef(Ret, this));
418 }
419
420 bool COFFObjectFile::section_rel_empty(DataRefImpl Ref) const {
421   const coff_section *Sec = toSec(Ref);
422   return Sec->NumberOfRelocations == 0;
423 }
424
425 // Initialize the pointer to the symbol table.
426 error_code COFFObjectFile::initSymbolTablePtr() {
427   if (error_code EC = getObject(
428           SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
429           COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
430     return EC;
431
432   // Find string table. The first four byte of the string table contains the
433   // total size of the string table, including the size field itself. If the
434   // string table is empty, the value of the first four byte would be 4.
435   const uint8_t *StringTableAddr =
436       base() + COFFHeader->PointerToSymbolTable +
437       COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
438   const ulittle32_t *StringTableSizePtr;
439   if (error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
440     return EC;
441   StringTableSize = *StringTableSizePtr;
442   if (error_code EC =
443       getObject(StringTable, Data, StringTableAddr, StringTableSize))
444     return EC;
445
446   // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
447   // tools like cvtres write a size of 0 for an empty table instead of 4.
448   if (StringTableSize < 4)
449       StringTableSize = 4;
450
451   // Check that the string table is null terminated if has any in it.
452   if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
453     return  object_error::parse_failed;
454   return object_error::success;
455 }
456
457 // Returns the file offset for the given VA.
458 error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
459   uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
460                                   : (uint64_t)PE32PlusHeader->ImageBase;
461   uint64_t Rva = Addr - ImageBase;
462   assert(Rva <= UINT32_MAX);
463   return getRvaPtr((uint32_t)Rva, Res);
464 }
465
466 // Returns the file offset for the given RVA.
467 error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
468   for (const SectionRef &S : sections()) {
469     const coff_section *Section = getCOFFSection(S);
470     uint32_t SectionStart = Section->VirtualAddress;
471     uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
472     if (SectionStart <= Addr && Addr < SectionEnd) {
473       uint32_t Offset = Addr - SectionStart;
474       Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
475       return object_error::success;
476     }
477   }
478   return object_error::parse_failed;
479 }
480
481 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
482 // table entry.
483 error_code COFFObjectFile::
484 getHintName(uint32_t Rva, uint16_t &Hint, StringRef &Name) const {
485   uintptr_t IntPtr = 0;
486   if (error_code EC = getRvaPtr(Rva, IntPtr))
487     return EC;
488   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
489   Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
490   Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
491   return object_error::success;
492 }
493
494 // Find the import table.
495 error_code COFFObjectFile::initImportTablePtr() {
496   // First, we get the RVA of the import table. If the file lacks a pointer to
497   // the import table, do nothing.
498   const data_directory *DataEntry;
499   if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
500     return object_error::success;
501
502   // Do nothing if the pointer to import table is NULL.
503   if (DataEntry->RelativeVirtualAddress == 0)
504     return object_error::success;
505
506   uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
507   NumberOfImportDirectory = DataEntry->Size /
508       sizeof(import_directory_table_entry);
509
510   // Find the section that contains the RVA. This is needed because the RVA is
511   // the import table's memory address which is different from its file offset.
512   uintptr_t IntPtr = 0;
513   if (error_code EC = getRvaPtr(ImportTableRva, IntPtr))
514     return EC;
515   ImportDirectory = reinterpret_cast<
516       const import_directory_table_entry *>(IntPtr);
517   return object_error::success;
518 }
519
520 // Find the export table.
521 error_code COFFObjectFile::initExportTablePtr() {
522   // First, we get the RVA of the export table. If the file lacks a pointer to
523   // the export table, do nothing.
524   const data_directory *DataEntry;
525   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
526     return object_error::success;
527
528   // Do nothing if the pointer to export table is NULL.
529   if (DataEntry->RelativeVirtualAddress == 0)
530     return object_error::success;
531
532   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
533   uintptr_t IntPtr = 0;
534   if (error_code EC = getRvaPtr(ExportTableRva, IntPtr))
535     return EC;
536   ExportDirectory =
537       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
538   return object_error::success;
539 }
540
541 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &EC,
542                                bool BufferOwned)
543     : ObjectFile(Binary::ID_COFF, Object, BufferOwned), COFFHeader(0),
544       PE32Header(0), PE32PlusHeader(0), DataDirectory(0), SectionTable(0),
545       SymbolTable(0), StringTable(0), StringTableSize(0), ImportDirectory(0),
546       NumberOfImportDirectory(0), ExportDirectory(0) {
547   // Check that we at least have enough room for a header.
548   if (!checkSize(Data, EC, sizeof(coff_file_header))) return;
549
550   // The current location in the file where we are looking at.
551   uint64_t CurPtr = 0;
552
553   // PE header is optional and is present only in executables. If it exists,
554   // it is placed right after COFF header.
555   bool HasPEHeader = false;
556
557   // Check if this is a PE/COFF file.
558   if (base()[0] == 0x4d && base()[1] == 0x5a) {
559     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
560     // PE signature to find 'normal' COFF header.
561     if (!checkSize(Data, EC, 0x3c + 8)) return;
562     CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
563     // Check the PE magic bytes. ("PE\0\0")
564     if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
565       EC = object_error::parse_failed;
566       return;
567     }
568     CurPtr += 4; // Skip the PE magic bytes.
569     HasPEHeader = true;
570   }
571
572   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
573     return;
574   CurPtr += sizeof(coff_file_header);
575
576   if (HasPEHeader) {
577     const pe32_header *Header;
578     if ((EC = getObject(Header, Data, base() + CurPtr)))
579       return;
580
581     const uint8_t *DataDirAddr;
582     uint64_t DataDirSize;
583     if (Header->Magic == 0x10b) {
584       PE32Header = Header;
585       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
586       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
587     } else if (Header->Magic == 0x20b) {
588       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
589       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
590       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
591     } else {
592       // It's neither PE32 nor PE32+.
593       EC = object_error::parse_failed;
594       return;
595     }
596     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
597       return;
598     CurPtr += COFFHeader->SizeOfOptionalHeader;
599   }
600
601   if (COFFHeader->isImportLibrary())
602     return;
603
604   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
605                       COFFHeader->NumberOfSections * sizeof(coff_section))))
606     return;
607
608   // Initialize the pointer to the symbol table.
609   if (COFFHeader->PointerToSymbolTable != 0)
610     if ((EC = initSymbolTablePtr()))
611       return;
612
613   // Initialize the pointer to the beginning of the import table.
614   if ((EC = initImportTablePtr()))
615     return;
616
617   // Initialize the pointer to the export table.
618   if ((EC = initExportTablePtr()))
619     return;
620
621   EC = object_error::success;
622 }
623
624 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
625   DataRefImpl Ret;
626   Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
627   return basic_symbol_iterator(SymbolRef(Ret, this));
628 }
629
630 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
631   // The symbol table ends where the string table begins.
632   DataRefImpl Ret;
633   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
634   return basic_symbol_iterator(SymbolRef(Ret, this));
635 }
636
637 library_iterator COFFObjectFile::needed_library_begin() const {
638   // TODO: implement
639   report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
640 }
641
642 library_iterator COFFObjectFile::needed_library_end() const {
643   // TODO: implement
644   report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
645 }
646
647 StringRef COFFObjectFile::getLoadName() const {
648   // COFF does not have this field.
649   return "";
650 }
651
652 import_directory_iterator COFFObjectFile::import_directory_begin() const {
653   return import_directory_iterator(
654       ImportDirectoryEntryRef(ImportDirectory, 0, this));
655 }
656
657 import_directory_iterator COFFObjectFile::import_directory_end() const {
658   return import_directory_iterator(
659       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
660 }
661
662 export_directory_iterator COFFObjectFile::export_directory_begin() const {
663   return export_directory_iterator(
664       ExportDirectoryEntryRef(ExportDirectory, 0, this));
665 }
666
667 export_directory_iterator COFFObjectFile::export_directory_end() const {
668   if (ExportDirectory == 0)
669     return export_directory_iterator(ExportDirectoryEntryRef(0, 0, this));
670   ExportDirectoryEntryRef Ref(ExportDirectory,
671                               ExportDirectory->AddressTableEntries, this);
672   return export_directory_iterator(Ref);
673 }
674
675 section_iterator COFFObjectFile::section_begin() const {
676   DataRefImpl Ret;
677   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
678   return section_iterator(SectionRef(Ret, this));
679 }
680
681 section_iterator COFFObjectFile::section_end() const {
682   DataRefImpl Ret;
683   int NumSections = COFFHeader->isImportLibrary()
684       ? 0 : COFFHeader->NumberOfSections;
685   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
686   return section_iterator(SectionRef(Ret, this));
687 }
688
689 uint8_t COFFObjectFile::getBytesInAddress() const {
690   return getArch() == Triple::x86_64 ? 8 : 4;
691 }
692
693 StringRef COFFObjectFile::getFileFormatName() const {
694   switch(COFFHeader->Machine) {
695   case COFF::IMAGE_FILE_MACHINE_I386:
696     return "COFF-i386";
697   case COFF::IMAGE_FILE_MACHINE_AMD64:
698     return "COFF-x86-64";
699   case COFF::IMAGE_FILE_MACHINE_ARMNT:
700     return "COFF-ARM";
701   default:
702     return "COFF-<unknown arch>";
703   }
704 }
705
706 unsigned COFFObjectFile::getArch() const {
707   switch(COFFHeader->Machine) {
708   case COFF::IMAGE_FILE_MACHINE_I386:
709     return Triple::x86;
710   case COFF::IMAGE_FILE_MACHINE_AMD64:
711     return Triple::x86_64;
712   case COFF::IMAGE_FILE_MACHINE_ARMNT:
713     return Triple::thumb;
714   default:
715     return Triple::UnknownArch;
716   }
717 }
718
719 // This method is kept here because lld uses this. As soon as we make
720 // lld to use getCOFFHeader, this method will be removed.
721 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
722   return getCOFFHeader(Res);
723 }
724
725 error_code COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
726   Res = COFFHeader;
727   return object_error::success;
728 }
729
730 error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
731   Res = PE32Header;
732   return object_error::success;
733 }
734
735 error_code
736 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
737   Res = PE32PlusHeader;
738   return object_error::success;
739 }
740
741 error_code COFFObjectFile::getDataDirectory(uint32_t Index,
742                                             const data_directory *&Res) const {
743   // Error if if there's no data directory or the index is out of range.
744   if (!DataDirectory)
745     return object_error::parse_failed;
746   assert(PE32Header || PE32PlusHeader);
747   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
748                                : PE32PlusHeader->NumberOfRvaAndSize;
749   if (Index > NumEnt)
750     return object_error::parse_failed;
751   Res = &DataDirectory[Index];
752   return object_error::success;
753 }
754
755 error_code COFFObjectFile::getSection(int32_t Index,
756                                       const coff_section *&Result) const {
757   // Check for special index values.
758   if (COFF::isReservedSectionNumber(Index))
759     Result = NULL;
760   else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
761     // We already verified the section table data, so no need to check again.
762     Result = SectionTable + (Index - 1);
763   else
764     return object_error::parse_failed;
765   return object_error::success;
766 }
767
768 error_code COFFObjectFile::getString(uint32_t Offset,
769                                      StringRef &Result) const {
770   if (StringTableSize <= 4)
771     // Tried to get a string from an empty string table.
772     return object_error::parse_failed;
773   if (Offset >= StringTableSize)
774     return object_error::unexpected_eof;
775   Result = StringRef(StringTable + Offset);
776   return object_error::success;
777 }
778
779 error_code COFFObjectFile::getSymbol(uint32_t Index,
780                                      const coff_symbol *&Result) const {
781   if (Index < COFFHeader->NumberOfSymbols)
782     Result = SymbolTable + Index;
783   else
784     return object_error::parse_failed;
785   return object_error::success;
786 }
787
788 error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
789                                          StringRef &Res) const {
790   // Check for string table entry. First 4 bytes are 0.
791   if (Symbol->Name.Offset.Zeroes == 0) {
792     uint32_t Offset = Symbol->Name.Offset.Offset;
793     if (error_code EC = getString(Offset, Res))
794       return EC;
795     return object_error::success;
796   }
797
798   if (Symbol->Name.ShortName[7] == 0)
799     // Null terminated, let ::strlen figure out the length.
800     Res = StringRef(Symbol->Name.ShortName);
801   else
802     // Not null terminated, use all 8 bytes.
803     Res = StringRef(Symbol->Name.ShortName, 8);
804   return object_error::success;
805 }
806
807 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
808                                   const coff_symbol *Symbol) const {
809   const uint8_t *Aux = NULL;
810
811   if (Symbol->NumberOfAuxSymbols > 0) {
812   // AUX data comes immediately after the symbol in COFF
813     Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
814 # ifndef NDEBUG
815     // Verify that the Aux symbol points to a valid entry in the symbol table.
816     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
817     if (Offset < COFFHeader->PointerToSymbolTable
818         || Offset >= COFFHeader->PointerToSymbolTable
819            + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
820       report_fatal_error("Aux Symbol data was outside of symbol table.");
821
822     assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
823          == 0 && "Aux Symbol data did not point to the beginning of a symbol");
824 # endif
825   }
826   return ArrayRef<uint8_t>(Aux,
827                            Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
828 }
829
830 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
831                                           StringRef &Res) const {
832   StringRef Name;
833   if (Sec->Name[7] == 0)
834     // Null terminated, let ::strlen figure out the length.
835     Name = Sec->Name;
836   else
837     // Not null terminated, use all 8 bytes.
838     Name = StringRef(Sec->Name, 8);
839
840   // Check for string table entry. First byte is '/'.
841   if (Name[0] == '/') {
842     uint32_t Offset;
843     if (Name[1] == '/') {
844       if (decodeBase64StringEntry(Name.substr(2), Offset))
845         return object_error::parse_failed;
846     } else {
847       if (Name.substr(1).getAsInteger(10, Offset))
848         return object_error::parse_failed;
849     }
850     if (error_code EC = getString(Offset, Name))
851       return EC;
852   }
853
854   Res = Name;
855   return object_error::success;
856 }
857
858 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
859                                               ArrayRef<uint8_t> &Res) const {
860   // The only thing that we need to verify is that the contents is contained
861   // within the file bounds. We don't need to make sure it doesn't cover other
862   // data, as there's nothing that says that is not allowed.
863   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
864   uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
865   if (ConEnd > uintptr_t(Data->getBufferEnd()))
866     return object_error::parse_failed;
867   Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
868                           Sec->SizeOfRawData);
869   return object_error::success;
870 }
871
872 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
873   return reinterpret_cast<const coff_relocation*>(Rel.p);
874 }
875
876 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
877   Rel.p = reinterpret_cast<uintptr_t>(
878             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
879 }
880
881 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
882                                                 uint64_t &Res) const {
883   report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
884 }
885
886 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
887                                                uint64_t &Res) const {
888   Res = toRel(Rel)->VirtualAddress;
889   return object_error::success;
890 }
891
892 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
893   const coff_relocation* R = toRel(Rel);
894   DataRefImpl Ref;
895   Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
896   return symbol_iterator(SymbolRef(Ref, this));
897 }
898
899 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
900                                              uint64_t &Res) const {
901   const coff_relocation* R = toRel(Rel);
902   Res = R->Type;
903   return object_error::success;
904 }
905
906 const coff_section *
907 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
908   return toSec(Section.getRawDataRefImpl());
909 }
910
911 const coff_symbol *
912 COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
913   return toSymb(Symbol.getRawDataRefImpl());
914 }
915
916 const coff_relocation *
917 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
918   return toRel(Reloc.getRawDataRefImpl());
919 }
920
921 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
922   case COFF::reloc_type:                                                       \
923     Res = #reloc_type;                                                         \
924     break;
925
926 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
927                                           SmallVectorImpl<char> &Result) const {
928   const coff_relocation *Reloc = toRel(Rel);
929   StringRef Res;
930   switch (COFFHeader->Machine) {
931   case COFF::IMAGE_FILE_MACHINE_AMD64:
932     switch (Reloc->Type) {
933     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
934     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
935     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
936     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
937     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
938     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
939     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
940     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
941     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
942     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
943     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
944     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
945     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
946     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
947     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
948     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
949     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
950     default:
951       Res = "Unknown";
952     }
953     break;
954   case COFF::IMAGE_FILE_MACHINE_I386:
955     switch (Reloc->Type) {
956     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
957     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
958     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
959     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
960     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
961     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
962     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
963     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
964     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
965     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
966     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
967     default:
968       Res = "Unknown";
969     }
970     break;
971   default:
972     Res = "Unknown";
973   }
974   Result.append(Res.begin(), Res.end());
975   return object_error::success;
976 }
977
978 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
979
980 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
981                                           SmallVectorImpl<char> &Result) const {
982   const coff_relocation *Reloc = toRel(Rel);
983   const coff_symbol *Symb = 0;
984   if (error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb)) return EC;
985   DataRefImpl Sym;
986   Sym.p = reinterpret_cast<uintptr_t>(Symb);
987   StringRef SymName;
988   if (error_code EC = getSymbolName(Sym, SymName)) return EC;
989   Result.append(SymName.begin(), SymName.end());
990   return object_error::success;
991 }
992
993 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
994                                           LibraryRef &Result) const {
995   report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
996 }
997
998 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
999                                           StringRef &Result) const {
1000   report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
1001 }
1002
1003 bool ImportDirectoryEntryRef::
1004 operator==(const ImportDirectoryEntryRef &Other) const {
1005   return ImportTable == Other.ImportTable && Index == Other.Index;
1006 }
1007
1008 void ImportDirectoryEntryRef::moveNext() {
1009   ++Index;
1010 }
1011
1012 error_code ImportDirectoryEntryRef::
1013 getImportTableEntry(const import_directory_table_entry *&Result) const {
1014   Result = ImportTable;
1015   return object_error::success;
1016 }
1017
1018 error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1019   uintptr_t IntPtr = 0;
1020   if (error_code EC = OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
1021     return EC;
1022   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1023   return object_error::success;
1024 }
1025
1026 error_code ImportDirectoryEntryRef::getImportLookupEntry(
1027     const import_lookup_table_entry32 *&Result) const {
1028   uintptr_t IntPtr = 0;
1029   if (error_code EC =
1030           OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
1031     return EC;
1032   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1033   return object_error::success;
1034 }
1035
1036 bool ExportDirectoryEntryRef::
1037 operator==(const ExportDirectoryEntryRef &Other) const {
1038   return ExportTable == Other.ExportTable && Index == Other.Index;
1039 }
1040
1041 void ExportDirectoryEntryRef::moveNext() {
1042   ++Index;
1043 }
1044
1045 // Returns the name of the current export symbol. If the symbol is exported only
1046 // by ordinal, the empty string is set as a result.
1047 error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1048   uintptr_t IntPtr = 0;
1049   if (error_code EC = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1050     return EC;
1051   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1052   return object_error::success;
1053 }
1054
1055 // Returns the starting ordinal number.
1056 error_code ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1057   Result = ExportTable->OrdinalBase;
1058   return object_error::success;
1059 }
1060
1061 // Returns the export ordinal of the current export symbol.
1062 error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1063   Result = ExportTable->OrdinalBase + Index;
1064   return object_error::success;
1065 }
1066
1067 // Returns the address of the current export symbol.
1068 error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1069   uintptr_t IntPtr = 0;
1070   if (error_code EC = OwningObject->getRvaPtr(
1071           ExportTable->ExportAddressTableRVA, IntPtr))
1072     return EC;
1073   const export_address_table_entry *entry =
1074       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1075   Result = entry[Index].ExportRVA;
1076   return object_error::success;
1077 }
1078
1079 // Returns the name of the current export symbol. If the symbol is exported only
1080 // by ordinal, the empty string is set as a result.
1081 error_code ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1082   uintptr_t IntPtr = 0;
1083   if (error_code EC = OwningObject->getRvaPtr(
1084           ExportTable->OrdinalTableRVA, IntPtr))
1085     return EC;
1086   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1087
1088   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1089   int Offset = 0;
1090   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1091        I < E; ++I, ++Offset) {
1092     if (*I != Index)
1093       continue;
1094     if (error_code EC = OwningObject->getRvaPtr(
1095             ExportTable->NamePointerRVA, IntPtr))
1096       return EC;
1097     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1098     if (error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1099       return EC;
1100     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1101     return object_error::success;
1102   }
1103   Result = "";
1104   return object_error::success;
1105 }
1106
1107 ErrorOr<ObjectFile *> ObjectFile::createCOFFObjectFile(MemoryBuffer *Object,
1108                                                        bool BufferOwned) {
1109   error_code EC;
1110   std::unique_ptr<COFFObjectFile> Ret(
1111       new COFFObjectFile(Object, EC, BufferOwned));
1112   if (EC)
1113     return EC;
1114   return Ret.release();
1115 }