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