1 //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the COFFObjectFile class.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Object/COFF.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Support/COFF.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <cctype>
23 #include <limits>
24 
25 using namespace llvm;
26 using namespace object;
27 
28 using support::ulittle16_t;
29 using support::ulittle32_t;
30 using support::ulittle64_t;
31 using support::little16_t;
32 
33 // Returns false if size is greater than the buffer size. And sets ec.
checkSize(MemoryBufferRef M,std::error_code & EC,uint64_t Size)34 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
35   if (M.getBufferSize() < Size) {
36     EC = object_error::unexpected_eof;
37     return false;
38   }
39   return true;
40 }
41 
checkOffset(MemoryBufferRef M,uintptr_t Addr,const uint64_t Size)42 static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
43                                    const uint64_t Size) {
44   if (Addr + Size < Addr || Addr + Size < Size ||
45       Addr + Size > uintptr_t(M.getBufferEnd()) ||
46       Addr < uintptr_t(M.getBufferStart())) {
47     return object_error::unexpected_eof;
48   }
49   return object_error::success;
50 }
51 
52 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
53 // Returns unexpected_eof if error.
54 template <typename T>
getObject(const T * & Obj,MemoryBufferRef M,const void * Ptr,const uint64_t Size=sizeof (T))55 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
56                                  const void *Ptr,
57                                  const uint64_t Size = sizeof(T)) {
58   uintptr_t Addr = uintptr_t(Ptr);
59   if (std::error_code EC = checkOffset(M, Addr, Size))
60     return EC;
61   Obj = reinterpret_cast<const T *>(Addr);
62   return object_error::success;
63 }
64 
65 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
66 // prefixed slashes.
decodeBase64StringEntry(StringRef Str,uint32_t & Result)67 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
68   assert(Str.size() <= 6 && "String too long, possible overflow.");
69   if (Str.size() > 6)
70     return true;
71 
72   uint64_t Value = 0;
73   while (!Str.empty()) {
74     unsigned CharVal;
75     if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
76       CharVal = Str[0] - 'A';
77     else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
78       CharVal = Str[0] - 'a' + 26;
79     else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
80       CharVal = Str[0] - '0' + 52;
81     else if (Str[0] == '+') // 62
82       CharVal = 62;
83     else if (Str[0] == '/') // 63
84       CharVal = 63;
85     else
86       return true;
87 
88     Value = (Value * 64) + CharVal;
89     Str = Str.substr(1);
90   }
91 
92   if (Value > std::numeric_limits<uint32_t>::max())
93     return true;
94 
95   Result = static_cast<uint32_t>(Value);
96   return false;
97 }
98 
99 template <typename coff_symbol_type>
toSymb(DataRefImpl Ref) const100 const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
101   const coff_symbol_type *Addr =
102       reinterpret_cast<const coff_symbol_type *>(Ref.p);
103 
104   assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
105 #ifndef NDEBUG
106   // Verify that the symbol points to a valid entry in the symbol table.
107   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
108 
109   assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
110          "Symbol did not point to the beginning of a symbol");
111 #endif
112 
113   return Addr;
114 }
115 
toSec(DataRefImpl Ref) const116 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
117   const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
118 
119 # ifndef NDEBUG
120   // Verify that the section points to a valid entry in the section table.
121   if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
122     report_fatal_error("Section was outside of section table.");
123 
124   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
125   assert(Offset % sizeof(coff_section) == 0 &&
126          "Section did not point to the beginning of a section");
127 # endif
128 
129   return Addr;
130 }
131 
moveSymbolNext(DataRefImpl & Ref) const132 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
133   auto End = reinterpret_cast<uintptr_t>(StringTable);
134   if (SymbolTable16) {
135     const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
136     Symb += 1 + Symb->NumberOfAuxSymbols;
137     Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
138   } else if (SymbolTable32) {
139     const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
140     Symb += 1 + Symb->NumberOfAuxSymbols;
141     Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
142   } else {
143     llvm_unreachable("no symbol table pointer!");
144   }
145 }
146 
getSymbolName(DataRefImpl Ref,StringRef & Result) const147 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
148                                               StringRef &Result) const {
149   COFFSymbolRef Symb = getCOFFSymbol(Ref);
150   return getSymbolName(Symb, Result);
151 }
152 
getSymbolAddress(DataRefImpl Ref,uint64_t & Result) const153 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
154                                                  uint64_t &Result) const {
155   COFFSymbolRef Symb = getCOFFSymbol(Ref);
156 
157   if (Symb.isAnyUndefined()) {
158     Result = UnknownAddressOrSize;
159     return object_error::success;
160   }
161   if (Symb.isCommon()) {
162     Result = UnknownAddressOrSize;
163     return object_error::success;
164   }
165   int32_t SectionNumber = Symb.getSectionNumber();
166   if (!COFF::isReservedSectionNumber(SectionNumber)) {
167     const coff_section *Section = nullptr;
168     if (std::error_code EC = getSection(SectionNumber, Section))
169       return EC;
170 
171     Result = Section->VirtualAddress + Symb.getValue();
172     return object_error::success;
173   }
174 
175   Result = Symb.getValue();
176   return object_error::success;
177 }
178 
getSymbolType(DataRefImpl Ref,SymbolRef::Type & Result) const179 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
180                                               SymbolRef::Type &Result) const {
181   COFFSymbolRef Symb = getCOFFSymbol(Ref);
182   int32_t SectionNumber = Symb.getSectionNumber();
183   Result = SymbolRef::ST_Other;
184 
185   if (Symb.isAnyUndefined()) {
186     Result = SymbolRef::ST_Unknown;
187   } else if (Symb.isFunctionDefinition()) {
188     Result = SymbolRef::ST_Function;
189   } else if (Symb.isCommon()) {
190     Result = SymbolRef::ST_Data;
191   } else if (Symb.isFileRecord()) {
192     Result = SymbolRef::ST_File;
193   } else if (SectionNumber == COFF::IMAGE_SYM_DEBUG ||
194              Symb.isSectionDefinition()) {
195     // TODO: perhaps we need a new symbol type ST_Section.
196     Result = SymbolRef::ST_Debug;
197   } else if (!COFF::isReservedSectionNumber(SectionNumber)) {
198     const coff_section *Section = nullptr;
199     if (std::error_code EC = getSection(SectionNumber, Section))
200       return EC;
201     uint32_t Characteristics = Section->Characteristics;
202     if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
203       Result = SymbolRef::ST_Function;
204     else if (Characteristics & (COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
205                                 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA))
206       Result = SymbolRef::ST_Data;
207   }
208   return object_error::success;
209 }
210 
getSymbolFlags(DataRefImpl Ref) const211 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
212   COFFSymbolRef Symb = getCOFFSymbol(Ref);
213   uint32_t Result = SymbolRef::SF_None;
214 
215   if (Symb.isExternal() || Symb.isWeakExternal())
216     Result |= SymbolRef::SF_Global;
217 
218   if (Symb.isWeakExternal())
219     Result |= SymbolRef::SF_Weak;
220 
221   if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
222     Result |= SymbolRef::SF_Absolute;
223 
224   if (Symb.isFileRecord())
225     Result |= SymbolRef::SF_FormatSpecific;
226 
227   if (Symb.isSectionDefinition())
228     Result |= SymbolRef::SF_FormatSpecific;
229 
230   if (Symb.isCommon())
231     Result |= SymbolRef::SF_Common;
232 
233   if (Symb.isAnyUndefined())
234     Result |= SymbolRef::SF_Undefined;
235 
236   return Result;
237 }
238 
getSymbolSize(DataRefImpl Ref,uint64_t & Result) const239 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
240                                               uint64_t &Result) const {
241   COFFSymbolRef Symb = getCOFFSymbol(Ref);
242 
243   if (Symb.isAnyUndefined()) {
244     Result = UnknownAddressOrSize;
245     return object_error::success;
246   }
247   if (Symb.isCommon()) {
248     Result = Symb.getValue();
249     return object_error::success;
250   }
251 
252   // Let's attempt to get the size of the symbol by looking at the address of
253   // the symbol after the symbol in question.
254   uint64_t SymbAddr;
255   if (std::error_code EC = getSymbolAddress(Ref, SymbAddr))
256     return EC;
257   int32_t SectionNumber = Symb.getSectionNumber();
258   if (COFF::isReservedSectionNumber(SectionNumber)) {
259     // Absolute and debug symbols aren't sorted in any interesting way.
260     Result = 0;
261     return object_error::success;
262   }
263   const section_iterator SecEnd = section_end();
264   uint64_t AfterAddr = UnknownAddressOrSize;
265   for (const symbol_iterator SymbI : symbols()) {
266     section_iterator SecI = SecEnd;
267     if (std::error_code EC = SymbI->getSection(SecI))
268       return EC;
269     // Check the symbol's section, skip it if it's in the wrong section.
270     // First, make sure it is in any section.
271     if (SecI == SecEnd)
272       continue;
273     // Second, make sure it is in the same section as the symbol in question.
274     if (!sectionContainsSymbol(SecI->getRawDataRefImpl(), Ref))
275       continue;
276     uint64_t Addr;
277     if (std::error_code EC = SymbI->getAddress(Addr))
278       return EC;
279     // We want to compare our symbol in question with the closest possible
280     // symbol that comes after.
281     if (AfterAddr > Addr && Addr > SymbAddr)
282       AfterAddr = Addr;
283   }
284   if (AfterAddr == UnknownAddressOrSize) {
285     // No symbol comes after this one, assume that everything after our symbol
286     // is part of it.
287     const coff_section *Section = nullptr;
288     if (std::error_code EC = getSection(SectionNumber, Section))
289       return EC;
290     Result = Section->SizeOfRawData - Symb.getValue();
291   } else {
292     // Take the difference between our symbol and the symbol that comes after
293     // our symbol.
294     Result = AfterAddr - SymbAddr;
295   }
296 
297   return object_error::success;
298 }
299 
300 std::error_code
getSymbolSection(DataRefImpl Ref,section_iterator & Result) const301 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
302                                  section_iterator &Result) const {
303   COFFSymbolRef Symb = getCOFFSymbol(Ref);
304   if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
305     Result = section_end();
306   } else {
307     const coff_section *Sec = nullptr;
308     if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
309       return EC;
310     DataRefImpl Ref;
311     Ref.p = reinterpret_cast<uintptr_t>(Sec);
312     Result = section_iterator(SectionRef(Ref, this));
313   }
314   return object_error::success;
315 }
316 
moveSectionNext(DataRefImpl & Ref) const317 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
318   const coff_section *Sec = toSec(Ref);
319   Sec += 1;
320   Ref.p = reinterpret_cast<uintptr_t>(Sec);
321 }
322 
getSectionName(DataRefImpl Ref,StringRef & Result) const323 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
324                                                StringRef &Result) const {
325   const coff_section *Sec = toSec(Ref);
326   return getSectionName(Sec, Result);
327 }
328 
getSectionAddress(DataRefImpl Ref) const329 uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
330   const coff_section *Sec = toSec(Ref);
331   return Sec->VirtualAddress;
332 }
333 
getSectionSize(DataRefImpl Ref) const334 uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
335   return getSectionSize(toSec(Ref));
336 }
337 
getSectionContents(DataRefImpl Ref,StringRef & Result) const338 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
339                                                    StringRef &Result) const {
340   const coff_section *Sec = toSec(Ref);
341   ArrayRef<uint8_t> Res;
342   std::error_code EC = getSectionContents(Sec, Res);
343   Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
344   return EC;
345 }
346 
getSectionAlignment(DataRefImpl Ref) const347 uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
348   const coff_section *Sec = toSec(Ref);
349   return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
350 }
351 
isSectionText(DataRefImpl Ref) const352 bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
353   const coff_section *Sec = toSec(Ref);
354   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
355 }
356 
isSectionData(DataRefImpl Ref) const357 bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
358   const coff_section *Sec = toSec(Ref);
359   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
360 }
361 
isSectionBSS(DataRefImpl Ref) const362 bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
363   const coff_section *Sec = toSec(Ref);
364   const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
365                             COFF::IMAGE_SCN_MEM_READ |
366                             COFF::IMAGE_SCN_MEM_WRITE;
367   return (Sec->Characteristics & BssFlags) == BssFlags;
368 }
369 
isSectionVirtual(DataRefImpl Ref) const370 bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
371   const coff_section *Sec = toSec(Ref);
372   // In COFF, a virtual section won't have any in-file
373   // content, so the file pointer to the content will be zero.
374   return Sec->PointerToRawData == 0;
375 }
376 
sectionContainsSymbol(DataRefImpl SecRef,DataRefImpl SymbRef) const377 bool COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
378                                            DataRefImpl SymbRef) const {
379   const coff_section *Sec = toSec(SecRef);
380   COFFSymbolRef Symb = getCOFFSymbol(SymbRef);
381   int32_t SecNumber = (Sec - SectionTable) + 1;
382   return SecNumber == Symb.getSectionNumber();
383 }
384 
getNumberOfRelocations(const coff_section * Sec,MemoryBufferRef M,const uint8_t * base)385 static uint32_t getNumberOfRelocations(const coff_section *Sec,
386                                        MemoryBufferRef M, const uint8_t *base) {
387   // The field for the number of relocations in COFF section table is only
388   // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
389   // NumberOfRelocations field, and the actual relocation count is stored in the
390   // VirtualAddress field in the first relocation entry.
391   if (Sec->hasExtendedRelocations()) {
392     const coff_relocation *FirstReloc;
393     if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
394         base + Sec->PointerToRelocations)))
395       return 0;
396     // -1 to exclude this first relocation entry.
397     return FirstReloc->VirtualAddress - 1;
398   }
399   return Sec->NumberOfRelocations;
400 }
401 
402 static const coff_relocation *
getFirstReloc(const coff_section * Sec,MemoryBufferRef M,const uint8_t * Base)403 getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
404   uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
405   if (!NumRelocs)
406     return nullptr;
407   auto begin = reinterpret_cast<const coff_relocation *>(
408       Base + Sec->PointerToRelocations);
409   if (Sec->hasExtendedRelocations()) {
410     // Skip the first relocation entry repurposed to store the number of
411     // relocations.
412     begin++;
413   }
414   if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
415     return nullptr;
416   return begin;
417 }
418 
section_rel_begin(DataRefImpl Ref) const419 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
420   const coff_section *Sec = toSec(Ref);
421   const coff_relocation *begin = getFirstReloc(Sec, Data, base());
422   DataRefImpl Ret;
423   Ret.p = reinterpret_cast<uintptr_t>(begin);
424   return relocation_iterator(RelocationRef(Ret, this));
425 }
426 
section_rel_end(DataRefImpl Ref) const427 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
428   const coff_section *Sec = toSec(Ref);
429   const coff_relocation *I = getFirstReloc(Sec, Data, base());
430   if (I)
431     I += getNumberOfRelocations(Sec, Data, base());
432   DataRefImpl Ret;
433   Ret.p = reinterpret_cast<uintptr_t>(I);
434   return relocation_iterator(RelocationRef(Ret, this));
435 }
436 
437 // Initialize the pointer to the symbol table.
initSymbolTablePtr()438 std::error_code COFFObjectFile::initSymbolTablePtr() {
439   if (COFFHeader)
440     if (std::error_code EC = getObject(
441             SymbolTable16, Data, base() + getPointerToSymbolTable(),
442             (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
443       return EC;
444 
445   if (COFFBigObjHeader)
446     if (std::error_code EC = getObject(
447             SymbolTable32, Data, base() + getPointerToSymbolTable(),
448             (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
449       return EC;
450 
451   // Find string table. The first four byte of the string table contains the
452   // total size of the string table, including the size field itself. If the
453   // string table is empty, the value of the first four byte would be 4.
454   uint32_t StringTableOffset = getPointerToSymbolTable() +
455                                getNumberOfSymbols() * getSymbolTableEntrySize();
456   const uint8_t *StringTableAddr = base() + StringTableOffset;
457   const ulittle32_t *StringTableSizePtr;
458   if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
459     return EC;
460   StringTableSize = *StringTableSizePtr;
461   if (std::error_code EC =
462           getObject(StringTable, Data, StringTableAddr, StringTableSize))
463     return EC;
464 
465   // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
466   // tools like cvtres write a size of 0 for an empty table instead of 4.
467   if (StringTableSize < 4)
468       StringTableSize = 4;
469 
470   // Check that the string table is null terminated if has any in it.
471   if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
472     return  object_error::parse_failed;
473   return object_error::success;
474 }
475 
476 // Returns the file offset for the given VA.
getVaPtr(uint64_t Addr,uintptr_t & Res) const477 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
478   uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
479                                   : (uint64_t)PE32PlusHeader->ImageBase;
480   uint64_t Rva = Addr - ImageBase;
481   assert(Rva <= UINT32_MAX);
482   return getRvaPtr((uint32_t)Rva, Res);
483 }
484 
485 // Returns the file offset for the given RVA.
getRvaPtr(uint32_t Addr,uintptr_t & Res) const486 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
487   for (const SectionRef &S : sections()) {
488     const coff_section *Section = getCOFFSection(S);
489     uint32_t SectionStart = Section->VirtualAddress;
490     uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
491     if (SectionStart <= Addr && Addr < SectionEnd) {
492       uint32_t Offset = Addr - SectionStart;
493       Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
494       return object_error::success;
495     }
496   }
497   return object_error::parse_failed;
498 }
499 
500 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
501 // table entry.
getHintName(uint32_t Rva,uint16_t & Hint,StringRef & Name) const502 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
503                                             StringRef &Name) const {
504   uintptr_t IntPtr = 0;
505   if (std::error_code EC = getRvaPtr(Rva, IntPtr))
506     return EC;
507   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
508   Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
509   Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
510   return object_error::success;
511 }
512 
513 // Find the import table.
initImportTablePtr()514 std::error_code COFFObjectFile::initImportTablePtr() {
515   // First, we get the RVA of the import table. If the file lacks a pointer to
516   // the import table, do nothing.
517   const data_directory *DataEntry;
518   if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
519     return object_error::success;
520 
521   // Do nothing if the pointer to import table is NULL.
522   if (DataEntry->RelativeVirtualAddress == 0)
523     return object_error::success;
524 
525   uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
526   // -1 because the last entry is the null entry.
527   NumberOfImportDirectory = DataEntry->Size /
528       sizeof(import_directory_table_entry) - 1;
529 
530   // Find the section that contains the RVA. This is needed because the RVA is
531   // the import table's memory address which is different from its file offset.
532   uintptr_t IntPtr = 0;
533   if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
534     return EC;
535   ImportDirectory = reinterpret_cast<
536       const import_directory_table_entry *>(IntPtr);
537   return object_error::success;
538 }
539 
540 // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
initDelayImportTablePtr()541 std::error_code COFFObjectFile::initDelayImportTablePtr() {
542   const data_directory *DataEntry;
543   if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
544     return object_error::success;
545   if (DataEntry->RelativeVirtualAddress == 0)
546     return object_error::success;
547 
548   uint32_t RVA = DataEntry->RelativeVirtualAddress;
549   NumberOfDelayImportDirectory = DataEntry->Size /
550       sizeof(delay_import_directory_table_entry) - 1;
551 
552   uintptr_t IntPtr = 0;
553   if (std::error_code EC = getRvaPtr(RVA, IntPtr))
554     return EC;
555   DelayImportDirectory = reinterpret_cast<
556       const delay_import_directory_table_entry *>(IntPtr);
557   return object_error::success;
558 }
559 
560 // Find the export table.
initExportTablePtr()561 std::error_code COFFObjectFile::initExportTablePtr() {
562   // First, we get the RVA of the export table. If the file lacks a pointer to
563   // the export table, do nothing.
564   const data_directory *DataEntry;
565   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
566     return object_error::success;
567 
568   // Do nothing if the pointer to export table is NULL.
569   if (DataEntry->RelativeVirtualAddress == 0)
570     return object_error::success;
571 
572   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
573   uintptr_t IntPtr = 0;
574   if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
575     return EC;
576   ExportDirectory =
577       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
578   return object_error::success;
579 }
580 
initBaseRelocPtr()581 std::error_code COFFObjectFile::initBaseRelocPtr() {
582   const data_directory *DataEntry;
583   if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
584     return object_error::success;
585   if (DataEntry->RelativeVirtualAddress == 0)
586     return object_error::success;
587 
588   uintptr_t IntPtr = 0;
589   if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
590     return EC;
591   BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
592       IntPtr);
593   BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
594       IntPtr + DataEntry->Size);
595   return object_error::success;
596 }
597 
COFFObjectFile(MemoryBufferRef Object,std::error_code & EC)598 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
599     : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
600       COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
601       DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
602       SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
603       ImportDirectory(nullptr), NumberOfImportDirectory(0),
604       DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
605       ExportDirectory(nullptr), BaseRelocHeader(nullptr),
606       BaseRelocEnd(nullptr) {
607   // Check that we at least have enough room for a header.
608   if (!checkSize(Data, EC, sizeof(coff_file_header)))
609     return;
610 
611   // The current location in the file where we are looking at.
612   uint64_t CurPtr = 0;
613 
614   // PE header is optional and is present only in executables. If it exists,
615   // it is placed right after COFF header.
616   bool HasPEHeader = false;
617 
618   // Check if this is a PE/COFF file.
619   if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
620     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
621     // PE signature to find 'normal' COFF header.
622     const auto *DH = reinterpret_cast<const dos_header *>(base());
623     if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
624       CurPtr = DH->AddressOfNewExeHeader;
625       // Check the PE magic bytes. ("PE\0\0")
626       if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
627         EC = object_error::parse_failed;
628         return;
629       }
630       CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
631       HasPEHeader = true;
632     }
633   }
634 
635   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
636     return;
637 
638   // It might be a bigobj file, let's check.  Note that COFF bigobj and COFF
639   // import libraries share a common prefix but bigobj is more restrictive.
640   if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
641       COFFHeader->NumberOfSections == uint16_t(0xffff) &&
642       checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
643     if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
644       return;
645 
646     // Verify that we are dealing with bigobj.
647     if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
648         std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
649                     sizeof(COFF::BigObjMagic)) == 0) {
650       COFFHeader = nullptr;
651       CurPtr += sizeof(coff_bigobj_file_header);
652     } else {
653       // It's not a bigobj.
654       COFFBigObjHeader = nullptr;
655     }
656   }
657   if (COFFHeader) {
658     // The prior checkSize call may have failed.  This isn't a hard error
659     // because we were just trying to sniff out bigobj.
660     EC = object_error::success;
661     CurPtr += sizeof(coff_file_header);
662 
663     if (COFFHeader->isImportLibrary())
664       return;
665   }
666 
667   if (HasPEHeader) {
668     const pe32_header *Header;
669     if ((EC = getObject(Header, Data, base() + CurPtr)))
670       return;
671 
672     const uint8_t *DataDirAddr;
673     uint64_t DataDirSize;
674     if (Header->Magic == COFF::PE32Header::PE32) {
675       PE32Header = Header;
676       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
677       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
678     } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
679       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
680       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
681       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
682     } else {
683       // It's neither PE32 nor PE32+.
684       EC = object_error::parse_failed;
685       return;
686     }
687     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
688       return;
689     CurPtr += COFFHeader->SizeOfOptionalHeader;
690   }
691 
692   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
693                       (uint64_t)getNumberOfSections() * sizeof(coff_section))))
694     return;
695 
696   // Initialize the pointer to the symbol table.
697   if (getPointerToSymbolTable() != 0) {
698     if ((EC = initSymbolTablePtr()))
699       return;
700   } else {
701     // We had better not have any symbols if we don't have a symbol table.
702     if (getNumberOfSymbols() != 0) {
703       EC = object_error::parse_failed;
704       return;
705     }
706   }
707 
708   // Initialize the pointer to the beginning of the import table.
709   if ((EC = initImportTablePtr()))
710     return;
711   if ((EC = initDelayImportTablePtr()))
712     return;
713 
714   // Initialize the pointer to the export table.
715   if ((EC = initExportTablePtr()))
716     return;
717 
718   // Initialize the pointer to the base relocation table.
719   if ((EC = initBaseRelocPtr()))
720     return;
721 
722   EC = object_error::success;
723 }
724 
symbol_begin_impl() const725 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
726   DataRefImpl Ret;
727   Ret.p = getSymbolTable();
728   return basic_symbol_iterator(SymbolRef(Ret, this));
729 }
730 
symbol_end_impl() const731 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
732   // The symbol table ends where the string table begins.
733   DataRefImpl Ret;
734   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
735   return basic_symbol_iterator(SymbolRef(Ret, this));
736 }
737 
import_directory_begin() const738 import_directory_iterator COFFObjectFile::import_directory_begin() const {
739   return import_directory_iterator(
740       ImportDirectoryEntryRef(ImportDirectory, 0, this));
741 }
742 
import_directory_end() const743 import_directory_iterator COFFObjectFile::import_directory_end() const {
744   return import_directory_iterator(
745       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
746 }
747 
748 delay_import_directory_iterator
delay_import_directory_begin() const749 COFFObjectFile::delay_import_directory_begin() const {
750   return delay_import_directory_iterator(
751       DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
752 }
753 
754 delay_import_directory_iterator
delay_import_directory_end() const755 COFFObjectFile::delay_import_directory_end() const {
756   return delay_import_directory_iterator(
757       DelayImportDirectoryEntryRef(
758           DelayImportDirectory, NumberOfDelayImportDirectory, this));
759 }
760 
export_directory_begin() const761 export_directory_iterator COFFObjectFile::export_directory_begin() const {
762   return export_directory_iterator(
763       ExportDirectoryEntryRef(ExportDirectory, 0, this));
764 }
765 
export_directory_end() const766 export_directory_iterator COFFObjectFile::export_directory_end() const {
767   if (!ExportDirectory)
768     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
769   ExportDirectoryEntryRef Ref(ExportDirectory,
770                               ExportDirectory->AddressTableEntries, this);
771   return export_directory_iterator(Ref);
772 }
773 
section_begin() const774 section_iterator COFFObjectFile::section_begin() const {
775   DataRefImpl Ret;
776   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
777   return section_iterator(SectionRef(Ret, this));
778 }
779 
section_end() const780 section_iterator COFFObjectFile::section_end() const {
781   DataRefImpl Ret;
782   int NumSections =
783       COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
784   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
785   return section_iterator(SectionRef(Ret, this));
786 }
787 
base_reloc_begin() const788 base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
789   return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
790 }
791 
base_reloc_end() const792 base_reloc_iterator COFFObjectFile::base_reloc_end() const {
793   return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
794 }
795 
getBytesInAddress() const796 uint8_t COFFObjectFile::getBytesInAddress() const {
797   return getArch() == Triple::x86_64 ? 8 : 4;
798 }
799 
getFileFormatName() const800 StringRef COFFObjectFile::getFileFormatName() const {
801   switch(getMachine()) {
802   case COFF::IMAGE_FILE_MACHINE_I386:
803     return "COFF-i386";
804   case COFF::IMAGE_FILE_MACHINE_AMD64:
805     return "COFF-x86-64";
806   case COFF::IMAGE_FILE_MACHINE_ARMNT:
807     return "COFF-ARM";
808   default:
809     return "COFF-<unknown arch>";
810   }
811 }
812 
getArch() const813 unsigned COFFObjectFile::getArch() const {
814   switch (getMachine()) {
815   case COFF::IMAGE_FILE_MACHINE_I386:
816     return Triple::x86;
817   case COFF::IMAGE_FILE_MACHINE_AMD64:
818     return Triple::x86_64;
819   case COFF::IMAGE_FILE_MACHINE_ARMNT:
820     return Triple::thumb;
821   default:
822     return Triple::UnknownArch;
823   }
824 }
825 
826 iterator_range<import_directory_iterator>
import_directories() const827 COFFObjectFile::import_directories() const {
828   return make_range(import_directory_begin(), import_directory_end());
829 }
830 
831 iterator_range<delay_import_directory_iterator>
delay_import_directories() const832 COFFObjectFile::delay_import_directories() const {
833   return make_range(delay_import_directory_begin(),
834                     delay_import_directory_end());
835 }
836 
837 iterator_range<export_directory_iterator>
export_directories() const838 COFFObjectFile::export_directories() const {
839   return make_range(export_directory_begin(), export_directory_end());
840 }
841 
base_relocs() const842 iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
843   return make_range(base_reloc_begin(), base_reloc_end());
844 }
845 
getPE32Header(const pe32_header * & Res) const846 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
847   Res = PE32Header;
848   return object_error::success;
849 }
850 
851 std::error_code
getPE32PlusHeader(const pe32plus_header * & Res) const852 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
853   Res = PE32PlusHeader;
854   return object_error::success;
855 }
856 
857 std::error_code
getDataDirectory(uint32_t Index,const data_directory * & Res) const858 COFFObjectFile::getDataDirectory(uint32_t Index,
859                                  const data_directory *&Res) const {
860   // Error if if there's no data directory or the index is out of range.
861   if (!DataDirectory) {
862     Res = nullptr;
863     return object_error::parse_failed;
864   }
865   assert(PE32Header || PE32PlusHeader);
866   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
867                                : PE32PlusHeader->NumberOfRvaAndSize;
868   if (Index >= NumEnt) {
869     Res = nullptr;
870     return object_error::parse_failed;
871   }
872   Res = &DataDirectory[Index];
873   return object_error::success;
874 }
875 
getSection(int32_t Index,const coff_section * & Result) const876 std::error_code COFFObjectFile::getSection(int32_t Index,
877                                            const coff_section *&Result) const {
878   Result = nullptr;
879   if (COFF::isReservedSectionNumber(Index))
880     return object_error::success;
881   if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
882     // We already verified the section table data, so no need to check again.
883     Result = SectionTable + (Index - 1);
884     return object_error::success;
885   }
886   return object_error::parse_failed;
887 }
888 
getString(uint32_t Offset,StringRef & Result) const889 std::error_code COFFObjectFile::getString(uint32_t Offset,
890                                           StringRef &Result) const {
891   if (StringTableSize <= 4)
892     // Tried to get a string from an empty string table.
893     return object_error::parse_failed;
894   if (Offset >= StringTableSize)
895     return object_error::unexpected_eof;
896   Result = StringRef(StringTable + Offset);
897   return object_error::success;
898 }
899 
getSymbolName(COFFSymbolRef Symbol,StringRef & Res) const900 std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
901                                               StringRef &Res) const {
902   // Check for string table entry. First 4 bytes are 0.
903   if (Symbol.getStringTableOffset().Zeroes == 0) {
904     uint32_t Offset = Symbol.getStringTableOffset().Offset;
905     if (std::error_code EC = getString(Offset, Res))
906       return EC;
907     return object_error::success;
908   }
909 
910   if (Symbol.getShortName()[COFF::NameSize - 1] == 0)
911     // Null terminated, let ::strlen figure out the length.
912     Res = StringRef(Symbol.getShortName());
913   else
914     // Not null terminated, use all 8 bytes.
915     Res = StringRef(Symbol.getShortName(), COFF::NameSize);
916   return object_error::success;
917 }
918 
919 ArrayRef<uint8_t>
getSymbolAuxData(COFFSymbolRef Symbol) const920 COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
921   const uint8_t *Aux = nullptr;
922 
923   size_t SymbolSize = getSymbolTableEntrySize();
924   if (Symbol.getNumberOfAuxSymbols() > 0) {
925     // AUX data comes immediately after the symbol in COFF
926     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
927 # ifndef NDEBUG
928     // Verify that the Aux symbol points to a valid entry in the symbol table.
929     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
930     if (Offset < getPointerToSymbolTable() ||
931         Offset >=
932             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
933       report_fatal_error("Aux Symbol data was outside of symbol table.");
934 
935     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
936            "Aux Symbol data did not point to the beginning of a symbol");
937 # endif
938   }
939   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
940 }
941 
getSectionName(const coff_section * Sec,StringRef & Res) const942 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
943                                                StringRef &Res) const {
944   StringRef Name;
945   if (Sec->Name[COFF::NameSize - 1] == 0)
946     // Null terminated, let ::strlen figure out the length.
947     Name = Sec->Name;
948   else
949     // Not null terminated, use all 8 bytes.
950     Name = StringRef(Sec->Name, COFF::NameSize);
951 
952   // Check for string table entry. First byte is '/'.
953   if (Name.startswith("/")) {
954     uint32_t Offset;
955     if (Name.startswith("//")) {
956       if (decodeBase64StringEntry(Name.substr(2), Offset))
957         return object_error::parse_failed;
958     } else {
959       if (Name.substr(1).getAsInteger(10, Offset))
960         return object_error::parse_failed;
961     }
962     if (std::error_code EC = getString(Offset, Name))
963       return EC;
964   }
965 
966   Res = Name;
967   return object_error::success;
968 }
969 
getSectionSize(const coff_section * Sec) const970 uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
971   // SizeOfRawData and VirtualSize change what they represent depending on
972   // whether or not we have an executable image.
973   //
974   // For object files, SizeOfRawData contains the size of section's data;
975   // VirtualSize is always zero.
976   //
977   // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
978   // actual section size is in VirtualSize.  It is possible for VirtualSize to
979   // be greater than SizeOfRawData; the contents past that point should be
980   // considered to be zero.
981   uint32_t SectionSize;
982   if (Sec->VirtualSize)
983     SectionSize = std::min(Sec->VirtualSize, Sec->SizeOfRawData);
984   else
985     SectionSize = Sec->SizeOfRawData;
986 
987   return SectionSize;
988 }
989 
990 std::error_code
getSectionContents(const coff_section * Sec,ArrayRef<uint8_t> & Res) const991 COFFObjectFile::getSectionContents(const coff_section *Sec,
992                                    ArrayRef<uint8_t> &Res) const {
993   // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
994   // don't do anything interesting for them.
995   assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
996          "BSS sections don't have contents!");
997   // The only thing that we need to verify is that the contents is contained
998   // within the file bounds. We don't need to make sure it doesn't cover other
999   // data, as there's nothing that says that is not allowed.
1000   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
1001   uint32_t SectionSize = getSectionSize(Sec);
1002   if (checkOffset(Data, ConStart, SectionSize))
1003     return object_error::parse_failed;
1004   Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
1005   return object_error::success;
1006 }
1007 
toRel(DataRefImpl Rel) const1008 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
1009   return reinterpret_cast<const coff_relocation*>(Rel.p);
1010 }
1011 
moveRelocationNext(DataRefImpl & Rel) const1012 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
1013   Rel.p = reinterpret_cast<uintptr_t>(
1014             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
1015 }
1016 
getRelocationAddress(DataRefImpl Rel,uint64_t & Res) const1017 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
1018                                                      uint64_t &Res) const {
1019   report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
1020 }
1021 
getRelocationOffset(DataRefImpl Rel,uint64_t & Res) const1022 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
1023                                                     uint64_t &Res) const {
1024   const coff_relocation *R = toRel(Rel);
1025   const support::ulittle32_t *VirtualAddressPtr;
1026   if (std::error_code EC =
1027           getObject(VirtualAddressPtr, Data, &R->VirtualAddress))
1028     return EC;
1029   Res = *VirtualAddressPtr;
1030   return object_error::success;
1031 }
1032 
getRelocationSymbol(DataRefImpl Rel) const1033 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
1034   const coff_relocation *R = toRel(Rel);
1035   DataRefImpl Ref;
1036   if (R->SymbolTableIndex >= getNumberOfSymbols())
1037     return symbol_end();
1038   if (SymbolTable16)
1039     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
1040   else if (SymbolTable32)
1041     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
1042   else
1043     llvm_unreachable("no symbol table pointer!");
1044   return symbol_iterator(SymbolRef(Ref, this));
1045 }
1046 
getRelocationType(DataRefImpl Rel,uint64_t & Res) const1047 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
1048                                                   uint64_t &Res) const {
1049   const coff_relocation* R = toRel(Rel);
1050   Res = R->Type;
1051   return object_error::success;
1052 }
1053 
1054 const coff_section *
getCOFFSection(const SectionRef & Section) const1055 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
1056   return toSec(Section.getRawDataRefImpl());
1057 }
1058 
getCOFFSymbol(const DataRefImpl & Ref) const1059 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
1060   if (SymbolTable16)
1061     return toSymb<coff_symbol16>(Ref);
1062   if (SymbolTable32)
1063     return toSymb<coff_symbol32>(Ref);
1064   llvm_unreachable("no symbol table pointer!");
1065 }
1066 
getCOFFSymbol(const SymbolRef & Symbol) const1067 COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
1068   return getCOFFSymbol(Symbol.getRawDataRefImpl());
1069 }
1070 
1071 const coff_relocation *
getCOFFRelocation(const RelocationRef & Reloc) const1072 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
1073   return toRel(Reloc.getRawDataRefImpl());
1074 }
1075 
1076 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
1077   case COFF::reloc_type:                                                       \
1078     Res = #reloc_type;                                                         \
1079     break;
1080 
1081 std::error_code
getRelocationTypeName(DataRefImpl Rel,SmallVectorImpl<char> & Result) const1082 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
1083                                       SmallVectorImpl<char> &Result) const {
1084   const coff_relocation *Reloc = toRel(Rel);
1085   StringRef Res;
1086   switch (getMachine()) {
1087   case COFF::IMAGE_FILE_MACHINE_AMD64:
1088     switch (Reloc->Type) {
1089     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1090     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1091     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1092     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1093     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1094     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1095     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1096     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1097     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1098     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1099     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1100     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1101     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1102     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1103     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1104     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1105     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1106     default:
1107       Res = "Unknown";
1108     }
1109     break;
1110   case COFF::IMAGE_FILE_MACHINE_ARMNT:
1111     switch (Reloc->Type) {
1112     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
1113     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
1114     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
1115     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
1116     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
1117     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
1118     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
1119     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
1120     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
1121     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
1122     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
1123     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
1124     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
1125     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
1126     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
1127     default:
1128       Res = "Unknown";
1129     }
1130     break;
1131   case COFF::IMAGE_FILE_MACHINE_I386:
1132     switch (Reloc->Type) {
1133     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1134     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1135     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1136     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1137     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1138     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1139     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1140     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1141     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1142     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1143     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1144     default:
1145       Res = "Unknown";
1146     }
1147     break;
1148   default:
1149     Res = "Unknown";
1150   }
1151   Result.append(Res.begin(), Res.end());
1152   return object_error::success;
1153 }
1154 
1155 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1156 
1157 std::error_code
getRelocationValueString(DataRefImpl Rel,SmallVectorImpl<char> & Result) const1158 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
1159                                          SmallVectorImpl<char> &Result) const {
1160   const coff_relocation *Reloc = toRel(Rel);
1161   DataRefImpl Sym;
1162   ErrorOr<COFFSymbolRef> Symb = getSymbol(Reloc->SymbolTableIndex);
1163   if (std::error_code EC = Symb.getError())
1164     return EC;
1165   Sym.p = reinterpret_cast<uintptr_t>(Symb->getRawPtr());
1166   StringRef SymName;
1167   if (std::error_code EC = getSymbolName(Sym, SymName))
1168     return EC;
1169   Result.append(SymName.begin(), SymName.end());
1170   return object_error::success;
1171 }
1172 
isRelocatableObject() const1173 bool COFFObjectFile::isRelocatableObject() const {
1174   return !DataDirectory;
1175 }
1176 
1177 bool ImportDirectoryEntryRef::
operator ==(const ImportDirectoryEntryRef & Other) const1178 operator==(const ImportDirectoryEntryRef &Other) const {
1179   return ImportTable == Other.ImportTable && Index == Other.Index;
1180 }
1181 
moveNext()1182 void ImportDirectoryEntryRef::moveNext() {
1183   ++Index;
1184 }
1185 
getImportTableEntry(const import_directory_table_entry * & Result) const1186 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1187     const import_directory_table_entry *&Result) const {
1188   Result = ImportTable + Index;
1189   return object_error::success;
1190 }
1191 
1192 static imported_symbol_iterator
makeImportedSymbolIterator(const COFFObjectFile * Object,uintptr_t Ptr,int Index)1193 makeImportedSymbolIterator(const COFFObjectFile *Object,
1194                            uintptr_t Ptr, int Index) {
1195   if (Object->getBytesInAddress() == 4) {
1196     auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
1197     return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1198   }
1199   auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
1200   return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1201 }
1202 
1203 static imported_symbol_iterator
importedSymbolBegin(uint32_t RVA,const COFFObjectFile * Object)1204 importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1205   uintptr_t IntPtr = 0;
1206   Object->getRvaPtr(RVA, IntPtr);
1207   return makeImportedSymbolIterator(Object, IntPtr, 0);
1208 }
1209 
1210 static imported_symbol_iterator
importedSymbolEnd(uint32_t RVA,const COFFObjectFile * Object)1211 importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1212   uintptr_t IntPtr = 0;
1213   Object->getRvaPtr(RVA, IntPtr);
1214   // Forward the pointer to the last entry which is null.
1215   int Index = 0;
1216   if (Object->getBytesInAddress() == 4) {
1217     auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1218     while (*Entry++)
1219       ++Index;
1220   } else {
1221     auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1222     while (*Entry++)
1223       ++Index;
1224   }
1225   return makeImportedSymbolIterator(Object, IntPtr, Index);
1226 }
1227 
1228 imported_symbol_iterator
imported_symbol_begin() const1229 ImportDirectoryEntryRef::imported_symbol_begin() const {
1230   return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
1231                              OwningObject);
1232 }
1233 
1234 imported_symbol_iterator
imported_symbol_end() const1235 ImportDirectoryEntryRef::imported_symbol_end() const {
1236   return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
1237                            OwningObject);
1238 }
1239 
1240 iterator_range<imported_symbol_iterator>
imported_symbols() const1241 ImportDirectoryEntryRef::imported_symbols() const {
1242   return make_range(imported_symbol_begin(), imported_symbol_end());
1243 }
1244 
getName(StringRef & Result) const1245 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1246   uintptr_t IntPtr = 0;
1247   if (std::error_code EC =
1248           OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1249     return EC;
1250   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1251   return object_error::success;
1252 }
1253 
1254 std::error_code
getImportLookupTableRVA(uint32_t & Result) const1255 ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t  &Result) const {
1256   Result = ImportTable[Index].ImportLookupTableRVA;
1257   return object_error::success;
1258 }
1259 
1260 std::error_code
getImportAddressTableRVA(uint32_t & Result) const1261 ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
1262   Result = ImportTable[Index].ImportAddressTableRVA;
1263   return object_error::success;
1264 }
1265 
getImportLookupEntry(const import_lookup_table_entry32 * & Result) const1266 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1267     const import_lookup_table_entry32 *&Result) const {
1268   uintptr_t IntPtr = 0;
1269   uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
1270   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1271     return EC;
1272   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1273   return object_error::success;
1274 }
1275 
1276 bool DelayImportDirectoryEntryRef::
operator ==(const DelayImportDirectoryEntryRef & Other) const1277 operator==(const DelayImportDirectoryEntryRef &Other) const {
1278   return Table == Other.Table && Index == Other.Index;
1279 }
1280 
moveNext()1281 void DelayImportDirectoryEntryRef::moveNext() {
1282   ++Index;
1283 }
1284 
1285 imported_symbol_iterator
imported_symbol_begin() const1286 DelayImportDirectoryEntryRef::imported_symbol_begin() const {
1287   return importedSymbolBegin(Table[Index].DelayImportNameTable,
1288                              OwningObject);
1289 }
1290 
1291 imported_symbol_iterator
imported_symbol_end() const1292 DelayImportDirectoryEntryRef::imported_symbol_end() const {
1293   return importedSymbolEnd(Table[Index].DelayImportNameTable,
1294                            OwningObject);
1295 }
1296 
1297 iterator_range<imported_symbol_iterator>
imported_symbols() const1298 DelayImportDirectoryEntryRef::imported_symbols() const {
1299   return make_range(imported_symbol_begin(), imported_symbol_end());
1300 }
1301 
getName(StringRef & Result) const1302 std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
1303   uintptr_t IntPtr = 0;
1304   if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
1305     return EC;
1306   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1307   return object_error::success;
1308 }
1309 
1310 std::error_code DelayImportDirectoryEntryRef::
getDelayImportTable(const delay_import_directory_table_entry * & Result) const1311 getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
1312   Result = Table;
1313   return object_error::success;
1314 }
1315 
1316 std::error_code DelayImportDirectoryEntryRef::
getImportAddress(int AddrIndex,uint64_t & Result) const1317 getImportAddress(int AddrIndex, uint64_t &Result) const {
1318   uint32_t RVA = Table[Index].DelayImportAddressTable +
1319       AddrIndex * (OwningObject->is64() ? 8 : 4);
1320   uintptr_t IntPtr = 0;
1321   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1322     return EC;
1323   if (OwningObject->is64())
1324     Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1325   else
1326     Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
1327   return object_error::success;
1328 }
1329 
1330 bool ExportDirectoryEntryRef::
operator ==(const ExportDirectoryEntryRef & Other) const1331 operator==(const ExportDirectoryEntryRef &Other) const {
1332   return ExportTable == Other.ExportTable && Index == Other.Index;
1333 }
1334 
moveNext()1335 void ExportDirectoryEntryRef::moveNext() {
1336   ++Index;
1337 }
1338 
1339 // Returns the name of the current export symbol. If the symbol is exported only
1340 // by ordinal, the empty string is set as a result.
getDllName(StringRef & Result) const1341 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1342   uintptr_t IntPtr = 0;
1343   if (std::error_code EC =
1344           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1345     return EC;
1346   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1347   return object_error::success;
1348 }
1349 
1350 // Returns the starting ordinal number.
1351 std::error_code
getOrdinalBase(uint32_t & Result) const1352 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1353   Result = ExportTable->OrdinalBase;
1354   return object_error::success;
1355 }
1356 
1357 // Returns the export ordinal of the current export symbol.
getOrdinal(uint32_t & Result) const1358 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1359   Result = ExportTable->OrdinalBase + Index;
1360   return object_error::success;
1361 }
1362 
1363 // Returns the address of the current export symbol.
getExportRVA(uint32_t & Result) const1364 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1365   uintptr_t IntPtr = 0;
1366   if (std::error_code EC =
1367           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1368     return EC;
1369   const export_address_table_entry *entry =
1370       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1371   Result = entry[Index].ExportRVA;
1372   return object_error::success;
1373 }
1374 
1375 // Returns the name of the current export symbol. If the symbol is exported only
1376 // by ordinal, the empty string is set as a result.
1377 std::error_code
getSymbolName(StringRef & Result) const1378 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1379   uintptr_t IntPtr = 0;
1380   if (std::error_code EC =
1381           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1382     return EC;
1383   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1384 
1385   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1386   int Offset = 0;
1387   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1388        I < E; ++I, ++Offset) {
1389     if (*I != Index)
1390       continue;
1391     if (std::error_code EC =
1392             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1393       return EC;
1394     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1395     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1396       return EC;
1397     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1398     return object_error::success;
1399   }
1400   Result = "";
1401   return object_error::success;
1402 }
1403 
1404 bool ImportedSymbolRef::
operator ==(const ImportedSymbolRef & Other) const1405 operator==(const ImportedSymbolRef &Other) const {
1406   return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1407       && Index == Other.Index;
1408 }
1409 
moveNext()1410 void ImportedSymbolRef::moveNext() {
1411   ++Index;
1412 }
1413 
1414 std::error_code
getSymbolName(StringRef & Result) const1415 ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1416   uint32_t RVA;
1417   if (Entry32) {
1418     // If a symbol is imported only by ordinal, it has no name.
1419     if (Entry32[Index].isOrdinal())
1420       return object_error::success;
1421     RVA = Entry32[Index].getHintNameRVA();
1422   } else {
1423     if (Entry64[Index].isOrdinal())
1424       return object_error::success;
1425     RVA = Entry64[Index].getHintNameRVA();
1426   }
1427   uintptr_t IntPtr = 0;
1428   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1429     return EC;
1430   // +2 because the first two bytes is hint.
1431   Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
1432   return object_error::success;
1433 }
1434 
getOrdinal(uint16_t & Result) const1435 std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1436   uint32_t RVA;
1437   if (Entry32) {
1438     if (Entry32[Index].isOrdinal()) {
1439       Result = Entry32[Index].getOrdinal();
1440       return object_error::success;
1441     }
1442     RVA = Entry32[Index].getHintNameRVA();
1443   } else {
1444     if (Entry64[Index].isOrdinal()) {
1445       Result = Entry64[Index].getOrdinal();
1446       return object_error::success;
1447     }
1448     RVA = Entry64[Index].getHintNameRVA();
1449   }
1450   uintptr_t IntPtr = 0;
1451   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1452     return EC;
1453   Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
1454   return object_error::success;
1455 }
1456 
1457 ErrorOr<std::unique_ptr<COFFObjectFile>>
createCOFFObjectFile(MemoryBufferRef Object)1458 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1459   std::error_code EC;
1460   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1461   if (EC)
1462     return EC;
1463   return std::move(Ret);
1464 }
1465 
operator ==(const BaseRelocRef & Other) const1466 bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
1467   return Header == Other.Header && Index == Other.Index;
1468 }
1469 
moveNext()1470 void BaseRelocRef::moveNext() {
1471   // Header->BlockSize is the size of the current block, including the
1472   // size of the header itself.
1473   uint32_t Size = sizeof(*Header) +
1474       sizeof(coff_base_reloc_block_entry) * (Index + 1);
1475   if (Size == Header->BlockSize) {
1476     // .reloc contains a list of base relocation blocks. Each block
1477     // consists of the header followed by entries. The header contains
1478     // how many entories will follow. When we reach the end of the
1479     // current block, proceed to the next block.
1480     Header = reinterpret_cast<const coff_base_reloc_block_header *>(
1481         reinterpret_cast<const uint8_t *>(Header) + Size);
1482     Index = 0;
1483   } else {
1484     ++Index;
1485   }
1486 }
1487 
getType(uint8_t & Type) const1488 std::error_code BaseRelocRef::getType(uint8_t &Type) const {
1489   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1490   Type = Entry[Index].getType();
1491   return object_error::success;
1492 }
1493 
getRVA(uint32_t & Result) const1494 std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
1495   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
1496   Result = Header->PageRVA + Entry[Index].getOffset();
1497   return object_error::success;
1498 }
1499