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/ADT/iterator_range.h"
20 #include "llvm/Support/COFF.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include <cctype>
24 #include <limits>
25 
26 using namespace llvm;
27 using namespace object;
28 
29 using support::ulittle16_t;
30 using support::ulittle32_t;
31 using support::ulittle64_t;
32 using support::little16_t;
33 
34 // Returns false if size is greater than the buffer size. And sets ec.
checkSize(MemoryBufferRef M,std::error_code & EC,uint64_t Size)35 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
36   if (M.getBufferSize() < Size) {
37     EC = object_error::unexpected_eof;
38     return false;
39   }
40   return true;
41 }
42 
checkOffset(MemoryBufferRef M,uintptr_t Addr,const uint64_t Size)43 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
44                                    const uint64_t Size) {
45   if (Addr + Size < Addr || Addr + Size < Size ||
46       Addr + Size > uintptr_t(M.getBufferEnd()) ||
47       Addr < uintptr_t(M.getBufferStart())) {
48     return object_error::unexpected_eof;
49   }
50   return std::error_code();
51 }
52 
53 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
54 // Returns unexpected_eof if error.
55 template <typename T>
getObject(const T * & Obj,MemoryBufferRef M,const void * Ptr,const uint64_t Size=sizeof (T))56 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
57                                  const void *Ptr,
58                                  const uint64_t Size = sizeof(T)) {
59   uintptr_t Addr = uintptr_t(Ptr);
60   if (std::error_code EC = checkOffset(M, Addr, Size))
61     return EC;
62   Obj = reinterpret_cast<const T *>(Addr);
63   return std::error_code();
64 }
65 
66 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
67 // prefixed slashes.
decodeBase64StringEntry(StringRef Str,uint32_t & Result)68 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
69   assert(Str.size() <= 6 && "String too long, possible overflow.");
70   if (Str.size() > 6)
71     return true;
72 
73   uint64_t Value = 0;
74   while (!Str.empty()) {
75     unsigned CharVal;
76     if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
77       CharVal = Str[0] - 'A';
78     else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
79       CharVal = Str[0] - 'a' + 26;
80     else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
81       CharVal = Str[0] - '0' + 52;
82     else if (Str[0] == '+') // 62
83       CharVal = 62;
84     else if (Str[0] == '/') // 63
85       CharVal = 63;
86     else
87       return true;
88 
89     Value = (Value * 64) + CharVal;
90     Str = Str.substr(1);
91   }
92 
93   if (Value > std::numeric_limits<uint32_t>::max())
94     return true;
95 
96   Result = static_cast<uint32_t>(Value);
97   return false;
98 }
99 
100 template <typename coff_symbol_type>
toSymb(DataRefImpl Ref) const101 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
102   const coff_symbol_type *Addr =
103       reinterpret_cast<const coff_symbol_type *>(Ref.p);
104 
105   assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
106 #ifndef NDEBUG
107   // Verify that the symbol points to a valid entry in the symbol table.
108   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
109 
110   assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
111          "Symbol did not point to the beginning of a symbol");
112 #endif
113 
114   return Addr;
115 }
116 
toSec(DataRefImpl Ref) const117 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
118   const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
119 
120 # ifndef NDEBUG
121   // Verify that the section points to a valid entry in the section table.
122   if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
123     report_fatal_error("Section was outside of section table.");
124 
125   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
126   assert(Offset % sizeof(coff_section) == 0 &&
127          "Section did not point to the beginning of a section");
128 # endif
129 
130   return Addr;
131 }
132 
moveSymbolNext(DataRefImpl & Ref) const133 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
134   auto End = reinterpret_cast<uintptr_t>(StringTable);
135   if (SymbolTable16) {
136     const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
137     Symb += 1 + Symb->NumberOfAuxSymbols;
138     Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
139   } else if (SymbolTable32) {
140     const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
141     Symb += 1 + Symb->NumberOfAuxSymbols;
142     Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
143   } else {
144     llvm_unreachable("no symbol table pointer!");
145   }
146 }
147 
getSymbolName(DataRefImpl Ref) const148 ErrorOr<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
149   COFFSymbolRef Symb = getCOFFSymbol(Ref);
150   StringRef Result;
151   std::error_code EC = getSymbolName(Symb, Result);
152   if (EC)
153     return EC;
154   return Result;
155 }
156 
getSymbolValueImpl(DataRefImpl Ref) const157 uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const {
158   return getCOFFSymbol(Ref).getValue();
159 }
160 
getSymbolAddress(DataRefImpl Ref) const161 ErrorOr<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
162   uint64_t Result = getSymbolValue(Ref);
163   COFFSymbolRef Symb = getCOFFSymbol(Ref);
164   int32_t SectionNumber = Symb.getSectionNumber();
165 
166   if (Symb.isAnyUndefined() || Symb.isCommon() ||
167       COFF::isReservedSectionNumber(SectionNumber))
168     return Result;
169 
170   const coff_section *Section = nullptr;
171   if (std::error_code EC = getSection(SectionNumber, Section))
172     return EC;
173   Result += Section->VirtualAddress;
174 
175   // The section VirtualAddress does not include ImageBase, and we want to
176   // return virtual addresses.
177   Result += getImageBase();
178 
179   return Result;
180 }
181 
getSymbolType(DataRefImpl Ref) const182 SymbolRef::Type COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
183   COFFSymbolRef Symb = getCOFFSymbol(Ref);
184   int32_t SectionNumber = Symb.getSectionNumber();
185 
186   if (Symb.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION)
187     return SymbolRef::ST_Function;
188   if (Symb.isAnyUndefined())
189     return SymbolRef::ST_Unknown;
190   if (Symb.isCommon())
191     return SymbolRef::ST_Data;
192   if (Symb.isFileRecord())
193     return SymbolRef::ST_File;
194 
195   // TODO: perhaps we need a new symbol type ST_Section.
196   if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
197     return SymbolRef::ST_Debug;
198 
199   if (!COFF::isReservedSectionNumber(SectionNumber))
200     return SymbolRef::ST_Data;
201 
202   return SymbolRef::ST_Other;
203 }
204 
getSymbolFlags(DataRefImpl Ref) const205 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
206   COFFSymbolRef Symb = getCOFFSymbol(Ref);
207   uint32_t Result = SymbolRef::SF_None;
208 
209   if (Symb.isExternal() || Symb.isWeakExternal())
210     Result |= SymbolRef::SF_Global;
211 
212   if (Symb.isWeakExternal())
213     Result |= SymbolRef::SF_Weak;
214 
215   if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
216     Result |= SymbolRef::SF_Absolute;
217 
218   if (Symb.isFileRecord())
219     Result |= SymbolRef::SF_FormatSpecific;
220 
221   if (Symb.isSectionDefinition())
222     Result |= SymbolRef::SF_FormatSpecific;
223 
224   if (Symb.isCommon())
225     Result |= SymbolRef::SF_Common;
226 
227   if (Symb.isAnyUndefined())
228     Result |= SymbolRef::SF_Undefined;
229 
230   return Result;
231 }
232 
getCommonSymbolSizeImpl(DataRefImpl Ref) const233 uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
234   COFFSymbolRef Symb = getCOFFSymbol(Ref);
235   return Symb.getValue();
236 }
237 
238 ErrorOr<section_iterator>
getSymbolSection(DataRefImpl Ref) const239 COFFObjectFile::getSymbolSection(DataRefImpl Ref) const {
240   COFFSymbolRef Symb = getCOFFSymbol(Ref);
241   if (COFF::isReservedSectionNumber(Symb.getSectionNumber()))
242     return section_end();
243   const coff_section *Sec = nullptr;
244   if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
245     return EC;
246   DataRefImpl Ret;
247   Ret.p = reinterpret_cast<uintptr_t>(Sec);
248   return section_iterator(SectionRef(Ret, this));
249 }
250 
getSymbolSectionID(SymbolRef Sym) const251 unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
252   COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
253   return Symb.getSectionNumber();
254 }
255 
moveSectionNext(DataRefImpl & Ref) const256 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
257   const coff_section *Sec = toSec(Ref);
258   Sec += 1;
259   Ref.p = reinterpret_cast<uintptr_t>(Sec);
260 }
261 
getSectionName(DataRefImpl Ref,StringRef & Result) const262 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
263                                                StringRef &Result) const {
264   const coff_section *Sec = toSec(Ref);
265   return getSectionName(Sec, Result);
266 }
267 
getSectionAddress(DataRefImpl Ref) const268 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
269   const coff_section *Sec = toSec(Ref);
270   uint64_t Result = Sec->VirtualAddress;
271 
272   // The section VirtualAddress does not include ImageBase, and we want to
273   // return virtual addresses.
274   Result += getImageBase();
275   return Result;
276 }
277 
getSectionSize(DataRefImpl Ref) const278 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
279   return getSectionSize(toSec(Ref));
280 }
281 
getSectionContents(DataRefImpl Ref,StringRef & Result) const282 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
283                                                    StringRef &Result) const {
284   const coff_section *Sec = toSec(Ref);
285   ArrayRef<uint8_t> Res;
286   std::error_code EC = getSectionContents(Sec, Res);
287   Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
288   return EC;
289 }
290 
getSectionAlignment(DataRefImpl Ref) const291 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
292   const coff_section *Sec = toSec(Ref);
293   return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
294 }
295 
isSectionText(DataRefImpl Ref) const296 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
297   const coff_section *Sec = toSec(Ref);
298   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
299 }
300 
isSectionData(DataRefImpl Ref) const301 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
302   const coff_section *Sec = toSec(Ref);
303   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
304 }
305 
isSectionBSS(DataRefImpl Ref) const306 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
307   const coff_section *Sec = toSec(Ref);
308   const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
309                             COFF::IMAGE_SCN_MEM_READ |
310                             COFF::IMAGE_SCN_MEM_WRITE;
311   return (Sec->Characteristics & BssFlags) == BssFlags;
312 }
313 
getSectionID(SectionRef Sec) const314 unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
315   uintptr_t Offset =
316       uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
317   assert((Offset % sizeof(coff_section)) == 0);
318   return (Offset / sizeof(coff_section)) + 1;
319 }
320 
isSectionVirtual(DataRefImpl Ref) const321 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
322   const coff_section *Sec = toSec(Ref);
323   // In COFF, a virtual section won't have any in-file
324   // content, so the file pointer to the content will be zero.
325   return Sec->PointerToRawData == 0;
326 }
327 
getNumberOfRelocations(const coff_section * Sec,MemoryBufferRef M,const uint8_t * base)328 static uint32_t getNumberOfRelocations(const coff_section *Sec,
329                                        MemoryBufferRef M, const uint8_t *base) {
330   // The field for the number of relocations in COFF section table is only
331   // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
332   // NumberOfRelocations field, and the actual relocation count is stored in the
333   // VirtualAddress field in the first relocation entry.
334   if (Sec->hasExtendedRelocations()) {
335     const coff_relocation *FirstReloc;
336     if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
337         base + Sec->PointerToRelocations)))
338       return 0;
339     // -1 to exclude this first relocation entry.
340     return FirstReloc->VirtualAddress - 1;
341   }
342   return Sec->NumberOfRelocations;
343 }
344 
345 static const coff_relocation *
getFirstReloc(const coff_section * Sec,MemoryBufferRef M,const uint8_t * Base)346 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
347   uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
348   if (!NumRelocs)
349     return nullptr;
350   auto begin = reinterpret_cast<const coff_relocation *>(
351       Base + Sec->PointerToRelocations);
352   if (Sec->hasExtendedRelocations()) {
353     // Skip the first relocation entry repurposed to store the number of
354     // relocations.
355     begin++;
356   }
357   if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
358     return nullptr;
359   return begin;
360 }
361 
section_rel_begin(DataRefImpl Ref) const362 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
363   const coff_section *Sec = toSec(Ref);
364   const coff_relocation *begin = getFirstReloc(Sec, Data, base());
365   if (begin && Sec->VirtualAddress != 0)
366     report_fatal_error("Sections with relocations should have an address of 0");
367   DataRefImpl Ret;
368   Ret.p = reinterpret_cast<uintptr_t>(begin);
369   return relocation_iterator(RelocationRef(Ret, this));
370 }
371 
section_rel_end(DataRefImpl Ref) const372 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
373   const coff_section *Sec = toSec(Ref);
374   const coff_relocation *I = getFirstReloc(Sec, Data, base());
375   if (I)
376     I += getNumberOfRelocations(Sec, Data, base());
377   DataRefImpl Ret;
378   Ret.p = reinterpret_cast<uintptr_t>(I);
379   return relocation_iterator(RelocationRef(Ret, this));
380 }
381 
382 // Initialize the pointer to the symbol table.
initSymbolTablePtr()383 std::error_code COFFObjectFile::initSymbolTablePtr() {
384   if (COFFHeader)
385     if (std::error_code EC = getObject(
386             SymbolTable16, Data, base() + getPointerToSymbolTable(),
387             (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
388       return EC;
389 
390   if (COFFBigObjHeader)
391     if (std::error_code EC = getObject(
392             SymbolTable32, Data, base() + getPointerToSymbolTable(),
393             (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
394       return EC;
395 
396   // Find string table. The first four byte of the string table contains the
397   // total size of the string table, including the size field itself. If the
398   // string table is empty, the value of the first four byte would be 4.
399   uint32_t StringTableOffset = getPointerToSymbolTable() +
400                                getNumberOfSymbols() * getSymbolTableEntrySize();
401   const uint8_t *StringTableAddr = base() + StringTableOffset;
402   const ulittle32_t *StringTableSizePtr;
403   if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
404     return EC;
405   StringTableSize = *StringTableSizePtr;
406   if (std::error_code EC =
407           getObject(StringTable, Data, StringTableAddr, StringTableSize))
408     return EC;
409 
410   // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
411   // tools like cvtres write a size of 0 for an empty table instead of 4.
412   if (StringTableSize < 4)
413       StringTableSize = 4;
414 
415   // Check that the string table is null terminated if has any in it.
416   if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
417     return  object_error::parse_failed;
418   return std::error_code();
419 }
420 
getImageBase() const421 uint64_t COFFObjectFile::getImageBase() const {
422   if (PE32Header)
423     return PE32Header->ImageBase;
424   else if (PE32PlusHeader)
425     return PE32PlusHeader->ImageBase;
426   // This actually comes up in practice.
427   return 0;
428 }
429 
430 // Returns the file offset for the given VA.
getVaPtr(uint64_t Addr,uintptr_t & Res) const431 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
432   uint64_t ImageBase = getImageBase();
433   uint64_t Rva = Addr - ImageBase;
434   assert(Rva <= UINT32_MAX);
435   return getRvaPtr((uint32_t)Rva, Res);
436 }
437 
438 // Returns the file offset for the given RVA.
getRvaPtr(uint32_t Addr,uintptr_t & Res) const439 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
440   for (const SectionRef &S : sections()) {
441     const coff_section *Section = getCOFFSection(S);
442     uint32_t SectionStart = Section->VirtualAddress;
443     uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
444     if (SectionStart <= Addr && Addr < SectionEnd) {
445       uint32_t Offset = Addr - SectionStart;
446       Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
447       return std::error_code();
448     }
449   }
450   return object_error::parse_failed;
451 }
452 
453 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
454 // table entry.
getHintName(uint32_t Rva,uint16_t & Hint,StringRef & Name) const455 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
456                                             StringRef &Name) const {
457   uintptr_t IntPtr = 0;
458   if (std::error_code EC = getRvaPtr(Rva, IntPtr))
459     return EC;
460   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
461   Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
462   Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
463   return std::error_code();
464 }
465 
466 // Find the import table.
initImportTablePtr()467 std::error_code COFFObjectFile::initImportTablePtr() {
468   // First, we get the RVA of the import table. If the file lacks a pointer to
469   // the import table, do nothing.
470   const data_directory *DataEntry;
471   if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
472     return std::error_code();
473 
474   // Do nothing if the pointer to import table is NULL.
475   if (DataEntry->RelativeVirtualAddress == 0)
476     return std::error_code();
477 
478   uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
479   // -1 because the last entry is the null entry.
480   NumberOfImportDirectory = DataEntry->Size /
481       sizeof(import_directory_table_entry) - 1;
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 std::error_code();
491 }
492 
493 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
initDelayImportTablePtr()494 std::error_code COFFObjectFile::initDelayImportTablePtr() {
495   const data_directory *DataEntry;
496   if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
497     return std::error_code();
498   if (DataEntry->RelativeVirtualAddress == 0)
499     return std::error_code();
500 
501   uint32_t RVA = DataEntry->RelativeVirtualAddress;
502   NumberOfDelayImportDirectory = DataEntry->Size /
503       sizeof(delay_import_directory_table_entry) - 1;
504 
505   uintptr_t IntPtr = 0;
506   if (std::error_code EC = getRvaPtr(RVA, IntPtr))
507     return EC;
508   DelayImportDirectory = reinterpret_cast<
509       const delay_import_directory_table_entry *>(IntPtr);
510   return std::error_code();
511 }
512 
513 // Find the export table.
initExportTablePtr()514 std::error_code COFFObjectFile::initExportTablePtr() {
515   // First, we get the RVA of the export table. If the file lacks a pointer to
516   // the export table, do nothing.
517   const data_directory *DataEntry;
518   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
519     return std::error_code();
520 
521   // Do nothing if the pointer to export table is NULL.
522   if (DataEntry->RelativeVirtualAddress == 0)
523     return std::error_code();
524 
525   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
526   uintptr_t IntPtr = 0;
527   if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
528     return EC;
529   ExportDirectory =
530       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
531   return std::error_code();
532 }
533 
initBaseRelocPtr()534 std::error_code COFFObjectFile::initBaseRelocPtr() {
535   const data_directory *DataEntry;
536   if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
537     return std::error_code();
538   if (DataEntry->RelativeVirtualAddress == 0)
539     return std::error_code();
540 
541   uintptr_t IntPtr = 0;
542   if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
543     return EC;
544   BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
545       IntPtr);
546   BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
547       IntPtr + DataEntry->Size);
548   return std::error_code();
549 }
550 
COFFObjectFile(MemoryBufferRef Object,std::error_code & EC)551 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
552     : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
553       COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
554       DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
555       SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
556       ImportDirectory(nullptr), NumberOfImportDirectory(0),
557       DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
558       ExportDirectory(nullptr), BaseRelocHeader(nullptr),
559       BaseRelocEnd(nullptr) {
560   // Check that we at least have enough room for a header.
561   if (!checkSize(Data, EC, sizeof(coff_file_header)))
562     return;
563 
564   // The current location in the file where we are looking at.
565   uint64_t CurPtr = 0;
566 
567   // PE header is optional and is present only in executables. If it exists,
568   // it is placed right after COFF header.
569   bool HasPEHeader = false;
570 
571   // Check if this is a PE/COFF file.
572   if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
573     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
574     // PE signature to find 'normal' COFF header.
575     const auto *DH = reinterpret_cast<const dos_header *>(base());
576     if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
577       CurPtr = DH->AddressOfNewExeHeader;
578       // Check the PE magic bytes. ("PE\0\0")
579       if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
580         EC = object_error::parse_failed;
581         return;
582       }
583       CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
584       HasPEHeader = true;
585     }
586   }
587 
588   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
589     return;
590 
591   // It might be a bigobj file, let's check.  Note that COFF bigobj and COFF
592   // import libraries share a common prefix but bigobj is more restrictive.
593   if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
594       COFFHeader->NumberOfSections == uint16_t(0xffff) &&
595       checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
596     if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
597       return;
598 
599     // Verify that we are dealing with bigobj.
600     if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
601         std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
602                     sizeof(COFF::BigObjMagic)) == 0) {
603       COFFHeader = nullptr;
604       CurPtr += sizeof(coff_bigobj_file_header);
605     } else {
606       // It's not a bigobj.
607       COFFBigObjHeader = nullptr;
608     }
609   }
610   if (COFFHeader) {
611     // The prior checkSize call may have failed.  This isn't a hard error
612     // because we were just trying to sniff out bigobj.
613     EC = std::error_code();
614     CurPtr += sizeof(coff_file_header);
615 
616     if (COFFHeader->isImportLibrary())
617       return;
618   }
619 
620   if (HasPEHeader) {
621     const pe32_header *Header;
622     if ((EC = getObject(Header, Data, base() + CurPtr)))
623       return;
624 
625     const uint8_t *DataDirAddr;
626     uint64_t DataDirSize;
627     if (Header->Magic == COFF::PE32Header::PE32) {
628       PE32Header = Header;
629       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
630       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
631     } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
632       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
633       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
634       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
635     } else {
636       // It's neither PE32 nor PE32+.
637       EC = object_error::parse_failed;
638       return;
639     }
640     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
641       return;
642     CurPtr += COFFHeader->SizeOfOptionalHeader;
643   }
644 
645   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
646                       (uint64_t)getNumberOfSections() * sizeof(coff_section))))
647     return;
648 
649   // Initialize the pointer to the symbol table.
650   if (getPointerToSymbolTable() != 0) {
651     if ((EC = initSymbolTablePtr()))
652       return;
653   } else {
654     // We had better not have any symbols if we don't have a symbol table.
655     if (getNumberOfSymbols() != 0) {
656       EC = object_error::parse_failed;
657       return;
658     }
659   }
660 
661   // Initialize the pointer to the beginning of the import table.
662   if ((EC = initImportTablePtr()))
663     return;
664   if ((EC = initDelayImportTablePtr()))
665     return;
666 
667   // Initialize the pointer to the export table.
668   if ((EC = initExportTablePtr()))
669     return;
670 
671   // Initialize the pointer to the base relocation table.
672   if ((EC = initBaseRelocPtr()))
673     return;
674 
675   EC = std::error_code();
676 }
677 
symbol_begin_impl() const678 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
679   DataRefImpl Ret;
680   Ret.p = getSymbolTable();
681   return basic_symbol_iterator(SymbolRef(Ret, this));
682 }
683 
symbol_end_impl() const684 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
685   // The symbol table ends where the string table begins.
686   DataRefImpl Ret;
687   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
688   return basic_symbol_iterator(SymbolRef(Ret, this));
689 }
690 
import_directory_begin() const691 import_directory_iterator COFFObjectFile::import_directory_begin() const {
692   return import_directory_iterator(
693       ImportDirectoryEntryRef(ImportDirectory, 0, this));
694 }
695 
import_directory_end() const696 import_directory_iterator COFFObjectFile::import_directory_end() const {
697   return import_directory_iterator(
698       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
699 }
700 
701 delay_import_directory_iterator
delay_import_directory_begin() const702 COFFObjectFile::delay_import_directory_begin() const {
703   return delay_import_directory_iterator(
704       DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
705 }
706 
707 delay_import_directory_iterator
delay_import_directory_end() const708 COFFObjectFile::delay_import_directory_end() const {
709   return delay_import_directory_iterator(
710       DelayImportDirectoryEntryRef(
711           DelayImportDirectory, NumberOfDelayImportDirectory, this));
712 }
713 
export_directory_begin() const714 export_directory_iterator COFFObjectFile::export_directory_begin() const {
715   return export_directory_iterator(
716       ExportDirectoryEntryRef(ExportDirectory, 0, this));
717 }
718 
export_directory_end() const719 export_directory_iterator COFFObjectFile::export_directory_end() const {
720   if (!ExportDirectory)
721     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
722   ExportDirectoryEntryRef Ref(ExportDirectory,
723                               ExportDirectory->AddressTableEntries, this);
724   return export_directory_iterator(Ref);
725 }
726 
section_begin() const727 section_iterator COFFObjectFile::section_begin() const {
728   DataRefImpl Ret;
729   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
730   return section_iterator(SectionRef(Ret, this));
731 }
732 
section_end() const733 section_iterator COFFObjectFile::section_end() const {
734   DataRefImpl Ret;
735   int NumSections =
736       COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
737   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
738   return section_iterator(SectionRef(Ret, this));
739 }
740 
base_reloc_begin() const741 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
742   return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
743 }
744 
base_reloc_end() const745 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
746   return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
747 }
748 
getBytesInAddress() const749 uint8_t COFFObjectFile::getBytesInAddress() const {
750   return getArch() == Triple::x86_64 ? 8 : 4;
751 }
752 
getFileFormatName() const753 StringRef COFFObjectFile::getFileFormatName() const {
754   switch(getMachine()) {
755   case COFF::IMAGE_FILE_MACHINE_I386:
756     return "COFF-i386";
757   case COFF::IMAGE_FILE_MACHINE_AMD64:
758     return "COFF-x86-64";
759   case COFF::IMAGE_FILE_MACHINE_ARMNT:
760     return "COFF-ARM";
761   case COFF::IMAGE_FILE_MACHINE_ARM64:
762     return "COFF-ARM64";
763   default:
764     return "COFF-<unknown arch>";
765   }
766 }
767 
getArch() const768 unsigned COFFObjectFile::getArch() const {
769   switch (getMachine()) {
770   case COFF::IMAGE_FILE_MACHINE_I386:
771     return Triple::x86;
772   case COFF::IMAGE_FILE_MACHINE_AMD64:
773     return Triple::x86_64;
774   case COFF::IMAGE_FILE_MACHINE_ARMNT:
775     return Triple::thumb;
776   case COFF::IMAGE_FILE_MACHINE_ARM64:
777     return Triple::aarch64;
778   default:
779     return Triple::UnknownArch;
780   }
781 }
782 
783 iterator_range<import_directory_iterator>
import_directories() const784 COFFObjectFile::import_directories() const {
785   return make_range(import_directory_begin(), import_directory_end());
786 }
787 
788 iterator_range<delay_import_directory_iterator>
delay_import_directories() const789 COFFObjectFile::delay_import_directories() const {
790   return make_range(delay_import_directory_begin(),
791                     delay_import_directory_end());
792 }
793 
794 iterator_range<export_directory_iterator>
export_directories() const795 COFFObjectFile::export_directories() const {
796   return make_range(export_directory_begin(), export_directory_end());
797 }
798 
base_relocs() const799 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
800   return make_range(base_reloc_begin(), base_reloc_end());
801 }
802 
getPE32Header(const pe32_header * & Res) const803 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
804   Res = PE32Header;
805   return std::error_code();
806 }
807 
808 std::error_code
getPE32PlusHeader(const pe32plus_header * & Res) const809 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
810   Res = PE32PlusHeader;
811   return std::error_code();
812 }
813 
814 std::error_code
getDataDirectory(uint32_t Index,const data_directory * & Res) const815 COFFObjectFile::getDataDirectory(uint32_t Index,
816                                  const data_directory *&Res) const {
817   // Error if if there's no data directory or the index is out of range.
818   if (!DataDirectory) {
819     Res = nullptr;
820     return object_error::parse_failed;
821   }
822   assert(PE32Header || PE32PlusHeader);
823   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
824                                : PE32PlusHeader->NumberOfRvaAndSize;
825   if (Index >= NumEnt) {
826     Res = nullptr;
827     return object_error::parse_failed;
828   }
829   Res = &DataDirectory[Index];
830   return std::error_code();
831 }
832 
getSection(int32_t Index,const coff_section * & Result) const833 std::error_code COFFObjectFile::getSection(int32_t Index,
834                                            const coff_section *&Result) const {
835   Result = nullptr;
836   if (COFF::isReservedSectionNumber(Index))
837     return std::error_code();
838   if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
839     // We already verified the section table data, so no need to check again.
840     Result = SectionTable + (Index - 1);
841     return std::error_code();
842   }
843   return object_error::parse_failed;
844 }
845 
getString(uint32_t Offset,StringRef & Result) const846 std::error_code COFFObjectFile::getString(uint32_t Offset,
847                                           StringRef &Result) const {
848   if (StringTableSize <= 4)
849     // Tried to get a string from an empty string table.
850     return object_error::parse_failed;
851   if (Offset >= StringTableSize)
852     return object_error::unexpected_eof;
853   Result = StringRef(StringTable + Offset);
854   return std::error_code();
855 }
856 
getSymbolName(COFFSymbolRef Symbol,StringRef & Res) const857 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
858                                               StringRef &Res) const {
859   return getSymbolName(Symbol.getGeneric(), Res);
860 }
861 
getSymbolName(const coff_symbol_generic * Symbol,StringRef & Res) const862 std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
863                                               StringRef &Res) const {
864   // Check for string table entry. First 4 bytes are 0.
865   if (Symbol->Name.Offset.Zeroes == 0) {
866     if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
867       return EC;
868     return std::error_code();
869   }
870 
871   if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
872     // Null terminated, let ::strlen figure out the length.
873     Res = StringRef(Symbol->Name.ShortName);
874   else
875     // Not null terminated, use all 8 bytes.
876     Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
877   return std::error_code();
878 }
879 
880 ArrayRef<uint8_t>
getSymbolAuxData(COFFSymbolRef Symbol) const881 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
882   const uint8_t *Aux = nullptr;
883 
884   size_t SymbolSize = getSymbolTableEntrySize();
885   if (Symbol.getNumberOfAuxSymbols() > 0) {
886     // AUX data comes immediately after the symbol in COFF
887     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
888 # ifndef NDEBUG
889     // Verify that the Aux symbol points to a valid entry in the symbol table.
890     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
891     if (Offset < getPointerToSymbolTable() ||
892         Offset >=
893             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
894       report_fatal_error("Aux Symbol data was outside of symbol table.");
895 
896     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
897            "Aux Symbol data did not point to the beginning of a symbol");
898 # endif
899   }
900   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
901 }
902 
getSectionName(const coff_section * Sec,StringRef & Res) const903 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
904                                                StringRef &Res) const {
905   StringRef Name;
906   if (Sec->Name[COFF::NameSize - 1] == 0)
907     // Null terminated, let ::strlen figure out the length.
908     Name = Sec->Name;
909   else
910     // Not null terminated, use all 8 bytes.
911     Name = StringRef(Sec->Name, COFF::NameSize);
912 
913   // Check for string table entry. First byte is '/'.
914   if (Name.startswith("/")) {
915     uint32_t Offset;
916     if (Name.startswith("//")) {
917       if (decodeBase64StringEntry(Name.substr(2), Offset))
918         return object_error::parse_failed;
919     } else {
920       if (Name.substr(1).getAsInteger(10, Offset))
921         return object_error::parse_failed;
922     }
923     if (std::error_code EC = getString(Offset, Name))
924       return EC;
925   }
926 
927   Res = Name;
928   return std::error_code();
929 }
930 
getSectionSize(const coff_section * Sec) const931 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
932   // SizeOfRawData and VirtualSize change what they represent depending on
933   // whether or not we have an executable image.
934   //
935   // For object files, SizeOfRawData contains the size of section's data;
936   // VirtualSize should be zero but isn't due to buggy COFF writers.
937   //
938   // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
939   // actual section size is in VirtualSize.  It is possible for VirtualSize to
940   // be greater than SizeOfRawData; the contents past that point should be
941   // considered to be zero.
942   if (getDOSHeader())
943     return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
944   return Sec->SizeOfRawData;
945 }
946 
947 std::error_code
getSectionContents(const coff_section * Sec,ArrayRef<uint8_t> & Res) const948 COFFObjectFile::getSectionContents(const coff_section *Sec,
949                                    ArrayRef<uint8_t> &Res) const {
950   // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
951   // don't do anything interesting for them.
952   assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
953          "BSS sections don't have contents!");
954   // The only thing that we need to verify is that the contents is contained
955   // within the file bounds. We don't need to make sure it doesn't cover other
956   // data, as there's nothing that says that is not allowed.
957   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
958   uint32_t SectionSize = getSectionSize(Sec);
959   if (checkOffset(Data, ConStart, SectionSize))
960     return object_error::parse_failed;
961   Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
962   return std::error_code();
963 }
964 
toRel(DataRefImpl Rel) const965 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
966   return reinterpret_cast<const coff_relocation*>(Rel.p);
967 }
968 
moveRelocationNext(DataRefImpl & Rel) const969 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
970   Rel.p = reinterpret_cast<uintptr_t>(
971             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
972 }
973 
getRelocationOffset(DataRefImpl Rel) const974 uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
975   const coff_relocation *R = toRel(Rel);
976   return R->VirtualAddress;
977 }
978 
getRelocationSymbol(DataRefImpl Rel) const979 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
980   const coff_relocation *R = toRel(Rel);
981   DataRefImpl Ref;
982   if (R->SymbolTableIndex >= getNumberOfSymbols())
983     return symbol_end();
984   if (SymbolTable16)
985     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
986   else if (SymbolTable32)
987     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
988   else
989     llvm_unreachable("no symbol table pointer!");
990   return symbol_iterator(SymbolRef(Ref, this));
991 }
992 
getRelocationType(DataRefImpl Rel) const993 uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
994   const coff_relocation* R = toRel(Rel);
995   return R->Type;
996 }
997 
998 const coff_section *
getCOFFSection(const SectionRef & Section) const999 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1000   return toSec(Section.getRawDataRefImpl());
1001 }
1002 
getCOFFSymbol(const DataRefImpl & Ref) const1003 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1004   if (SymbolTable16)
1005     return toSymb<coff_symbol16>(Ref);
1006   if (SymbolTable32)
1007     return toSymb<coff_symbol32>(Ref);
1008   llvm_unreachable("no symbol table pointer!");
1009 }
1010 
getCOFFSymbol(const SymbolRef & Symbol) const1011 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1012   return getCOFFSymbol(Symbol.getRawDataRefImpl());
1013 }
1014 
1015 const coff_relocation *
getCOFFRelocation(const RelocationRef & Reloc) const1016 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1017   return toRel(Reloc.getRawDataRefImpl());
1018 }
1019 
1020 iterator_range<const coff_relocation *>
getRelocations(const coff_section * Sec) const1021 COFFObjectFile::getRelocations(const coff_section *Sec) const {
1022   const coff_relocation *I = getFirstReloc(Sec, Data, base());
1023   const coff_relocation *E = I;
1024   if (I)
1025     E += getNumberOfRelocations(Sec, Data, base());
1026   return make_range(I, E);
1027 }
1028 
1029 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
1030   case COFF::reloc_type:                                                       \
1031     Res = #reloc_type;                                                         \
1032     break;
1033 
getRelocationTypeName(DataRefImpl Rel,SmallVectorImpl<char> & Result) const1034 void COFFObjectFile::getRelocationTypeName(
1035     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
1036   const coff_relocation *Reloc = toRel(Rel);
1037   StringRef Res;
1038   switch (getMachine()) {
1039   case COFF::IMAGE_FILE_MACHINE_AMD64:
1040     switch (Reloc->Type) {
1041     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1042     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1043     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1044     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1045     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1046     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1047     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1048     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1049     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1050     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1051     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1052     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1053     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1054     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1055     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1056     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1057     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1058     default:
1059       Res = "Unknown";
1060     }
1061     break;
1062   case COFF::IMAGE_FILE_MACHINE_ARMNT:
1063     switch (Reloc->Type) {
1064     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1065     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1066     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1067     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1068     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1069     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1070     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1071     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1072     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1073     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1074     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1075     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1076     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1077     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1078     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1079     default:
1080       Res = "Unknown";
1081     }
1082     break;
1083   case COFF::IMAGE_FILE_MACHINE_I386:
1084     switch (Reloc->Type) {
1085     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1086     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1087     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1088     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1089     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1090     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1091     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1092     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1093     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1094     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1095     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1096     default:
1097       Res = "Unknown";
1098     }
1099     break;
1100   default:
1101     Res = "Unknown";
1102   }
1103   Result.append(Res.begin(), Res.end());
1104 }
1105 
1106 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1107 
isRelocatableObject() const1108 bool COFFObjectFile::isRelocatableObject() const {
1109   return !DataDirectory;
1110 }
1111 
1112 bool ImportDirectoryEntryRef::
operator ==(const ImportDirectoryEntryRef & Other) const1113 operator==(const ImportDirectoryEntryRef &Other) const {
1114   return ImportTable == Other.ImportTable && Index == Other.Index;
1115 }
1116 
moveNext()1117 void ImportDirectoryEntryRef::moveNext() {
1118   ++Index;
1119 }
1120 
getImportTableEntry(const import_directory_table_entry * & Result) const1121 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1122     const import_directory_table_entry *&Result) const {
1123   Result = ImportTable + Index;
1124   return std::error_code();
1125 }
1126 
1127 static imported_symbol_iterator
makeImportedSymbolIterator(const COFFObjectFile * Object,uintptr_t Ptr,int Index)1128 makeImportedSymbolIterator(const COFFObjectFile *Object,
1129                            uintptr_t Ptr, int Index) {
1130   if (Object->getBytesInAddress() == 4) {
1131     auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1132     return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1133   }
1134   auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1135   return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1136 }
1137 
1138 static imported_symbol_iterator
importedSymbolBegin(uint32_t RVA,const COFFObjectFile * Object)1139 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1140   uintptr_t IntPtr = 0;
1141   Object->getRvaPtr(RVA, IntPtr);
1142   return makeImportedSymbolIterator(Object, IntPtr, 0);
1143 }
1144 
1145 static imported_symbol_iterator
importedSymbolEnd(uint32_t RVA,const COFFObjectFile * Object)1146 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1147   uintptr_t IntPtr = 0;
1148   Object->getRvaPtr(RVA, IntPtr);
1149   // Forward the pointer to the last entry which is null.
1150   int Index = 0;
1151   if (Object->getBytesInAddress() == 4) {
1152     auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1153     while (*Entry++)
1154       ++Index;
1155   } else {
1156     auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1157     while (*Entry++)
1158       ++Index;
1159   }
1160   return makeImportedSymbolIterator(Object, IntPtr, Index);
1161 }
1162 
1163 imported_symbol_iterator
imported_symbol_begin() const1164 ImportDirectoryEntryRef::imported_symbol_begin() const {
1165   return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1166                              OwningObject);
1167 }
1168 
1169 imported_symbol_iterator
imported_symbol_end() const1170 ImportDirectoryEntryRef::imported_symbol_end() const {
1171   return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1172                            OwningObject);
1173 }
1174 
1175 iterator_range<imported_symbol_iterator>
imported_symbols() const1176 ImportDirectoryEntryRef::imported_symbols() const {
1177   return make_range(imported_symbol_begin(), imported_symbol_end());
1178 }
1179 
getName(StringRef & Result) const1180 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1181   uintptr_t IntPtr = 0;
1182   if (std::error_code EC =
1183           OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1184     return EC;
1185   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1186   return std::error_code();
1187 }
1188 
1189 std::error_code
getImportLookupTableRVA(uint32_t & Result) const1190 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t  &Result) const {
1191   Result = ImportTable[Index].ImportLookupTableRVA;
1192   return std::error_code();
1193 }
1194 
1195 std::error_code
getImportAddressTableRVA(uint32_t & Result) const1196 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1197   Result = ImportTable[Index].ImportAddressTableRVA;
1198   return std::error_code();
1199 }
1200 
getImportLookupEntry(const import_lookup_table_entry32 * & Result) const1201 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1202     const import_lookup_table_entry32 *&Result) const {
1203   uintptr_t IntPtr = 0;
1204   uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1205   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1206     return EC;
1207   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1208   return std::error_code();
1209 }
1210 
1211 bool DelayImportDirectoryEntryRef::
operator ==(const DelayImportDirectoryEntryRef & Other) const1212 operator==(const DelayImportDirectoryEntryRef &Other) const {
1213   return Table == Other.Table && Index == Other.Index;
1214 }
1215 
moveNext()1216 void DelayImportDirectoryEntryRef::moveNext() {
1217   ++Index;
1218 }
1219 
1220 imported_symbol_iterator
imported_symbol_begin() const1221 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1222   return importedSymbolBegin(Table[Index].DelayImportNameTable,
1223                              OwningObject);
1224 }
1225 
1226 imported_symbol_iterator
imported_symbol_end() const1227 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1228   return importedSymbolEnd(Table[Index].DelayImportNameTable,
1229                            OwningObject);
1230 }
1231 
1232 iterator_range<imported_symbol_iterator>
imported_symbols() const1233 DelayImportDirectoryEntryRef::imported_symbols() const {
1234   return make_range(imported_symbol_begin(), imported_symbol_end());
1235 }
1236 
getName(StringRef & Result) const1237 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1238   uintptr_t IntPtr = 0;
1239   if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1240     return EC;
1241   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1242   return std::error_code();
1243 }
1244 
1245 std::error_code DelayImportDirectoryEntryRef::
getDelayImportTable(const delay_import_directory_table_entry * & Result) const1246 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1247   Result = Table;
1248   return std::error_code();
1249 }
1250 
1251 std::error_code DelayImportDirectoryEntryRef::
getImportAddress(int AddrIndex,uint64_t & Result) const1252 getImportAddress(int AddrIndex, uint64_t &Result) const {
1253   uint32_t RVA = Table[Index].DelayImportAddressTable +
1254       AddrIndex * (OwningObject->is64() ? 8 : 4);
1255   uintptr_t IntPtr = 0;
1256   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1257     return EC;
1258   if (OwningObject->is64())
1259     Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1260   else
1261     Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1262   return std::error_code();
1263 }
1264 
1265 bool ExportDirectoryEntryRef::
operator ==(const ExportDirectoryEntryRef & Other) const1266 operator==(const ExportDirectoryEntryRef &Other) const {
1267   return ExportTable == Other.ExportTable && Index == Other.Index;
1268 }
1269 
moveNext()1270 void ExportDirectoryEntryRef::moveNext() {
1271   ++Index;
1272 }
1273 
1274 // Returns the name of the current export symbol. If the symbol is exported only
1275 // by ordinal, the empty string is set as a result.
getDllName(StringRef & Result) const1276 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1277   uintptr_t IntPtr = 0;
1278   if (std::error_code EC =
1279           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1280     return EC;
1281   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1282   return std::error_code();
1283 }
1284 
1285 // Returns the starting ordinal number.
1286 std::error_code
getOrdinalBase(uint32_t & Result) const1287 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1288   Result = ExportTable->OrdinalBase;
1289   return std::error_code();
1290 }
1291 
1292 // Returns the export ordinal of the current export symbol.
getOrdinal(uint32_t & Result) const1293 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1294   Result = ExportTable->OrdinalBase + Index;
1295   return std::error_code();
1296 }
1297 
1298 // Returns the address of the current export symbol.
getExportRVA(uint32_t & Result) const1299 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1300   uintptr_t IntPtr = 0;
1301   if (std::error_code EC =
1302           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1303     return EC;
1304   const export_address_table_entry *entry =
1305       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1306   Result = entry[Index].ExportRVA;
1307   return std::error_code();
1308 }
1309 
1310 // Returns the name of the current export symbol. If the symbol is exported only
1311 // by ordinal, the empty string is set as a result.
1312 std::error_code
getSymbolName(StringRef & Result) const1313 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1314   uintptr_t IntPtr = 0;
1315   if (std::error_code EC =
1316           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1317     return EC;
1318   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1319 
1320   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1321   int Offset = 0;
1322   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1323        I < E; ++I, ++Offset) {
1324     if (*I != Index)
1325       continue;
1326     if (std::error_code EC =
1327             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1328       return EC;
1329     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1330     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1331       return EC;
1332     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1333     return std::error_code();
1334   }
1335   Result = "";
1336   return std::error_code();
1337 }
1338 
1339 bool ImportedSymbolRef::
operator ==(const ImportedSymbolRef & Other) const1340 operator==(const ImportedSymbolRef &Other) const {
1341   return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1342       && Index == Other.Index;
1343 }
1344 
moveNext()1345 void ImportedSymbolRef::moveNext() {
1346   ++Index;
1347 }
1348 
1349 std::error_code
getSymbolName(StringRef & Result) const1350 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1351   uint32_t RVA;
1352   if (Entry32) {
1353     // If a symbol is imported only by ordinal, it has no name.
1354     if (Entry32[Index].isOrdinal())
1355       return std::error_code();
1356     RVA = Entry32[Index].getHintNameRVA();
1357   } else {
1358     if (Entry64[Index].isOrdinal())
1359       return std::error_code();
1360     RVA = Entry64[Index].getHintNameRVA();
1361   }
1362   uintptr_t IntPtr = 0;
1363   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1364     return EC;
1365   // +2 because the first two bytes is hint.
1366   Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1367   return std::error_code();
1368 }
1369 
getOrdinal(uint16_t & Result) const1370 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1371   uint32_t RVA;
1372   if (Entry32) {
1373     if (Entry32[Index].isOrdinal()) {
1374       Result = Entry32[Index].getOrdinal();
1375       return std::error_code();
1376     }
1377     RVA = Entry32[Index].getHintNameRVA();
1378   } else {
1379     if (Entry64[Index].isOrdinal()) {
1380       Result = Entry64[Index].getOrdinal();
1381       return std::error_code();
1382     }
1383     RVA = Entry64[Index].getHintNameRVA();
1384   }
1385   uintptr_t IntPtr = 0;
1386   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1387     return EC;
1388   Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1389   return std::error_code();
1390 }
1391 
1392 ErrorOr<std::unique_ptr<COFFObjectFile>>
createCOFFObjectFile(MemoryBufferRef Object)1393 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1394   std::error_code EC;
1395   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1396   if (EC)
1397     return EC;
1398   return std::move(Ret);
1399 }
1400 
operator ==(const BaseRelocRef & Other) const1401 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1402   return Header == Other.Header && Index == Other.Index;
1403 }
1404 
moveNext()1405 void BaseRelocRef::moveNext() {
1406   // Header->BlockSize is the size of the current block, including the
1407   // size of the header itself.
1408   uint32_t Size = sizeof(*Header) +
1409       sizeof(coff_base_reloc_block_entry) * (Index + 1);
1410   if (Size == Header->BlockSize) {
1411     // .reloc contains a list of base relocation blocks. Each block
1412     // consists of the header followed by entries. The header contains
1413     // how many entories will follow. When we reach the end of the
1414     // current block, proceed to the next block.
1415     Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1416         reinterpret_cast<const uint8_t *>(Header) + Size);
1417     Index = 0;
1418   } else {
1419     ++Index;
1420   }
1421 }
1422 
getType(uint8_t & Type) const1423 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1424   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1425   Type = Entry[Index].getType();
1426   return std::error_code();
1427 }
1428 
getRVA(uint32_t & Result) const1429 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1430   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1431   Result = Header->PageRVA + Entry[Index].getOffset();
1432   return std::error_code();
1433 }
1434