18e90adafSMichael J. Spencer //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===//
28e90adafSMichael J. Spencer //
38e90adafSMichael J. Spencer //                     The LLVM Compiler Infrastructure
48e90adafSMichael J. Spencer //
58e90adafSMichael J. Spencer // This file is distributed under the University of Illinois Open Source
68e90adafSMichael J. Spencer // License. See LICENSE.TXT for details.
78e90adafSMichael J. Spencer //
88e90adafSMichael J. Spencer //===----------------------------------------------------------------------===//
98e90adafSMichael J. Spencer //
108e90adafSMichael J. Spencer // This file declares the COFFObjectFile class.
118e90adafSMichael J. Spencer //
128e90adafSMichael J. Spencer //===----------------------------------------------------------------------===//
138e90adafSMichael J. Spencer 
14ec29b121SMichael J. Spencer #include "llvm/Object/COFF.h"
159da9e693SMichael J. Spencer #include "llvm/ADT/ArrayRef.h"
16e5fd0047SMichael J. Spencer #include "llvm/ADT/SmallString.h"
178e90adafSMichael J. Spencer #include "llvm/ADT/StringSwitch.h"
188e90adafSMichael J. Spencer #include "llvm/ADT/Triple.h"
196a75acb1SRui Ueyama #include "llvm/ADT/iterator_range.h"
20f078eff3SRui Ueyama #include "llvm/Support/COFF.h"
21c2bed429SRui Ueyama #include "llvm/Support/Debug.h"
22c2bed429SRui Ueyama #include "llvm/Support/raw_ostream.h"
23981af002SWill Dietz #include <cctype>
249d2c15efSNico Rieck #include <limits>
258e90adafSMichael J. Spencer 
268e90adafSMichael J. Spencer using namespace llvm;
278e90adafSMichael J. Spencer using namespace object;
288e90adafSMichael J. Spencer 
298e90adafSMichael J. Spencer using support::ulittle16_t;
308e90adafSMichael J. Spencer using support::ulittle32_t;
31861021f9SRui Ueyama using support::ulittle64_t;
328e90adafSMichael J. Spencer using support::little16_t;
338e90adafSMichael J. Spencer 
341d6167fdSMichael J. Spencer // Returns false if size is greater than the buffer size. And sets ec.
3548af1c2aSRafael Espindola static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
36c3f9b5a5SRafael Espindola   if (M.getBufferSize() < Size) {
378ff24d25SRui Ueyama     EC = object_error::unexpected_eof;
381d6167fdSMichael J. Spencer     return false;
391d6167fdSMichael J. Spencer   }
401d6167fdSMichael J. Spencer   return true;
418e90adafSMichael J. Spencer }
428e90adafSMichael J. Spencer 
43e830c60dSDavid Majnemer static std::error_code checkOffset(MemoryBufferRef M, uintptr_t Addr,
4494751be7SDavid Majnemer                                    const uint64_t Size) {
45e830c60dSDavid Majnemer   if (Addr + Size < Addr || Addr + Size < Size ||
46e830c60dSDavid Majnemer       Addr + Size > uintptr_t(M.getBufferEnd()) ||
47e830c60dSDavid Majnemer       Addr < uintptr_t(M.getBufferStart())) {
48e830c60dSDavid Majnemer     return object_error::unexpected_eof;
49e830c60dSDavid Majnemer   }
507d099195SRui Ueyama   return std::error_code();
51e830c60dSDavid Majnemer }
52e830c60dSDavid Majnemer 
53ed64342bSRui Ueyama // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
54ed64342bSRui Ueyama // Returns unexpected_eof if error.
55ed64342bSRui Ueyama template <typename T>
5648af1c2aSRafael Espindola static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
5758323a97SDavid Majnemer                                  const void *Ptr,
58236b0ca7SDavid Majnemer                                  const uint64_t Size = sizeof(T)) {
59ed64342bSRui Ueyama   uintptr_t Addr = uintptr_t(Ptr);
60e830c60dSDavid Majnemer   if (std::error_code EC = checkOffset(M, Addr, Size))
61e830c60dSDavid Majnemer     return EC;
62ed64342bSRui Ueyama   Obj = reinterpret_cast<const T *>(Addr);
637d099195SRui Ueyama   return std::error_code();
641d6167fdSMichael J. Spencer }
651d6167fdSMichael J. Spencer 
669d2c15efSNico Rieck // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
679d2c15efSNico Rieck // prefixed slashes.
689d2c15efSNico Rieck static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
699d2c15efSNico Rieck   assert(Str.size() <= 6 && "String too long, possible overflow.");
709d2c15efSNico Rieck   if (Str.size() > 6)
719d2c15efSNico Rieck     return true;
729d2c15efSNico Rieck 
739d2c15efSNico Rieck   uint64_t Value = 0;
749d2c15efSNico Rieck   while (!Str.empty()) {
759d2c15efSNico Rieck     unsigned CharVal;
769d2c15efSNico Rieck     if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
779d2c15efSNico Rieck       CharVal = Str[0] - 'A';
789d2c15efSNico Rieck     else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
799d2c15efSNico Rieck       CharVal = Str[0] - 'a' + 26;
809d2c15efSNico Rieck     else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
819d2c15efSNico Rieck       CharVal = Str[0] - '0' + 52;
829d2c15efSNico Rieck     else if (Str[0] == '+') // 62
835500b07cSRui Ueyama       CharVal = 62;
849d2c15efSNico Rieck     else if (Str[0] == '/') // 63
855500b07cSRui Ueyama       CharVal = 63;
869d2c15efSNico Rieck     else
879d2c15efSNico Rieck       return true;
889d2c15efSNico Rieck 
899d2c15efSNico Rieck     Value = (Value * 64) + CharVal;
909d2c15efSNico Rieck     Str = Str.substr(1);
919d2c15efSNico Rieck   }
929d2c15efSNico Rieck 
939d2c15efSNico Rieck   if (Value > std::numeric_limits<uint32_t>::max())
949d2c15efSNico Rieck     return true;
959d2c15efSNico Rieck 
969d2c15efSNico Rieck   Result = static_cast<uint32_t>(Value);
979d2c15efSNico Rieck   return false;
989d2c15efSNico Rieck }
999d2c15efSNico Rieck 
10044f51e51SDavid Majnemer template <typename coff_symbol_type>
10144f51e51SDavid Majnemer const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
10244f51e51SDavid Majnemer   const coff_symbol_type *Addr =
10344f51e51SDavid Majnemer       reinterpret_cast<const coff_symbol_type *>(Ref.p);
1041d6167fdSMichael J. Spencer 
105236b0ca7SDavid Majnemer   assert(!checkOffset(Data, uintptr_t(Addr), sizeof(*Addr)));
1061d6167fdSMichael J. Spencer #ifndef NDEBUG
1071d6167fdSMichael J. Spencer   // Verify that the symbol points to a valid entry in the symbol table.
1088ff24d25SRui Ueyama   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
1091d6167fdSMichael J. Spencer 
11044f51e51SDavid Majnemer   assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
11144f51e51SDavid Majnemer          "Symbol did not point to the beginning of a symbol");
1121d6167fdSMichael J. Spencer #endif
1131d6167fdSMichael J. Spencer 
1148ff24d25SRui Ueyama   return Addr;
1151d6167fdSMichael J. Spencer }
1161d6167fdSMichael J. Spencer 
1178ff24d25SRui Ueyama const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
1188ff24d25SRui Ueyama   const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
1191d6167fdSMichael J. Spencer 
1201d6167fdSMichael J. Spencer # ifndef NDEBUG
1211d6167fdSMichael J. Spencer   // Verify that the section points to a valid entry in the section table.
12244f51e51SDavid Majnemer   if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
1231d6167fdSMichael J. Spencer     report_fatal_error("Section was outside of section table.");
1241d6167fdSMichael J. Spencer 
1258ff24d25SRui Ueyama   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
1268ff24d25SRui Ueyama   assert(Offset % sizeof(coff_section) == 0 &&
1271d6167fdSMichael J. Spencer          "Section did not point to the beginning of a section");
1281d6167fdSMichael J. Spencer # endif
1291d6167fdSMichael J. Spencer 
1308ff24d25SRui Ueyama   return Addr;
1311d6167fdSMichael J. Spencer }
1321d6167fdSMichael J. Spencer 
1335e812afaSRafael Espindola void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
134236b0ca7SDavid Majnemer   auto End = reinterpret_cast<uintptr_t>(StringTable);
13544f51e51SDavid Majnemer   if (SymbolTable16) {
13644f51e51SDavid Majnemer     const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
1378ff24d25SRui Ueyama     Symb += 1 + Symb->NumberOfAuxSymbols;
138236b0ca7SDavid Majnemer     Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
13944f51e51SDavid Majnemer   } else if (SymbolTable32) {
14044f51e51SDavid Majnemer     const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
14144f51e51SDavid Majnemer     Symb += 1 + Symb->NumberOfAuxSymbols;
142236b0ca7SDavid Majnemer     Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
14344f51e51SDavid Majnemer   } else {
14444f51e51SDavid Majnemer     llvm_unreachable("no symbol table pointer!");
14544f51e51SDavid Majnemer   }
1461d6167fdSMichael J. Spencer }
1471d6167fdSMichael J. Spencer 
1485d0c2ffaSRafael Espindola ErrorOr<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
14944f51e51SDavid Majnemer   COFFSymbolRef Symb = getCOFFSymbol(Ref);
1505d0c2ffaSRafael Espindola   StringRef Result;
1515d0c2ffaSRafael Espindola   std::error_code EC = getSymbolName(Symb, Result);
1525d0c2ffaSRafael Espindola   if (EC)
1535d0c2ffaSRafael Espindola     return EC;
1545d0c2ffaSRafael Espindola   return Result;
1558e90adafSMichael J. Spencer }
1568e90adafSMichael J. Spencer 
157be8b0ea8SRafael Espindola uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const {
158be8b0ea8SRafael Espindola   return getCOFFSymbol(Ref).getValue();
159991af666SRafael Espindola }
160991af666SRafael Espindola 
161ed067c45SRafael Espindola ErrorOr<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
162ed067c45SRafael Espindola   uint64_t Result = getSymbolValue(Ref);
16344f51e51SDavid Majnemer   COFFSymbolRef Symb = getCOFFSymbol(Ref);
164c7d7c6fbSDavid Majnemer   int32_t SectionNumber = Symb.getSectionNumber();
165991af666SRafael Espindola 
166991af666SRafael Espindola   if (Symb.isAnyUndefined() || Symb.isCommon() ||
167991af666SRafael Espindola       COFF::isReservedSectionNumber(SectionNumber))
168ed067c45SRafael Espindola     return Result;
16954c9f3daSRafael Espindola 
1702617dcceSCraig Topper   const coff_section *Section = nullptr;
171c7d7c6fbSDavid Majnemer   if (std::error_code EC = getSection(SectionNumber, Section))
1728ff24d25SRui Ueyama     return EC;
173991af666SRafael Espindola   Result += Section->VirtualAddress;
174*47ea9eceSReid Kleckner 
175*47ea9eceSReid Kleckner   // The section VirtualAddress does not include ImageBase, and we want to
176*47ea9eceSReid Kleckner   // return virtual addresses.
177*47ea9eceSReid Kleckner   if (PE32Header)
178*47ea9eceSReid Kleckner     Result += PE32Header->ImageBase;
179*47ea9eceSReid Kleckner   else if (PE32PlusHeader)
180*47ea9eceSReid Kleckner     Result += PE32Header->ImageBase;
181*47ea9eceSReid Kleckner 
182ed067c45SRafael Espindola   return Result;
183c7d7c6fbSDavid Majnemer }
184c7d7c6fbSDavid Majnemer 
1852fa80cc5SRafael Espindola SymbolRef::Type COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
18644f51e51SDavid Majnemer   COFFSymbolRef Symb = getCOFFSymbol(Ref);
187c7d7c6fbSDavid Majnemer   int32_t SectionNumber = Symb.getSectionNumber();
18844f51e51SDavid Majnemer 
1892fa80cc5SRafael Espindola   if (Symb.isAnyUndefined())
1902fa80cc5SRafael Espindola     return SymbolRef::ST_Unknown;
1912fa80cc5SRafael Espindola   if (Symb.isFunctionDefinition())
1922fa80cc5SRafael Espindola     return SymbolRef::ST_Function;
1932fa80cc5SRafael Espindola   if (Symb.isCommon())
1942fa80cc5SRafael Espindola     return SymbolRef::ST_Data;
1952fa80cc5SRafael Espindola   if (Symb.isFileRecord())
1962fa80cc5SRafael Espindola     return SymbolRef::ST_File;
1972fa80cc5SRafael Espindola 
1981a666e0fSDavid Majnemer   // TODO: perhaps we need a new symbol type ST_Section.
1992fa80cc5SRafael Espindola   if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
2002fa80cc5SRafael Espindola     return SymbolRef::ST_Debug;
2012fa80cc5SRafael Espindola 
2022fa80cc5SRafael Espindola   if (!COFF::isReservedSectionNumber(SectionNumber))
2032fa80cc5SRafael Espindola     return SymbolRef::ST_Data;
2042fa80cc5SRafael Espindola 
2052fa80cc5SRafael Espindola   return SymbolRef::ST_Other;
20675d1cf33SBenjamin Kramer }
20775d1cf33SBenjamin Kramer 
20820122a43SRafael Espindola uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
20944f51e51SDavid Majnemer   COFFSymbolRef Symb = getCOFFSymbol(Ref);
21020122a43SRafael Espindola   uint32_t Result = SymbolRef::SF_None;
21175d1cf33SBenjamin Kramer 
212c7d7c6fbSDavid Majnemer   if (Symb.isExternal() || Symb.isWeakExternal())
2131df4b84dSDavid Meyer     Result |= SymbolRef::SF_Global;
2141df4b84dSDavid Meyer 
215c7d7c6fbSDavid Majnemer   if (Symb.isWeakExternal())
2161df4b84dSDavid Meyer     Result |= SymbolRef::SF_Weak;
2171df4b84dSDavid Meyer 
21844f51e51SDavid Majnemer   if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
2191df4b84dSDavid Meyer     Result |= SymbolRef::SF_Absolute;
2201df4b84dSDavid Meyer 
221c7d7c6fbSDavid Majnemer   if (Symb.isFileRecord())
222c7d7c6fbSDavid Majnemer     Result |= SymbolRef::SF_FormatSpecific;
223c7d7c6fbSDavid Majnemer 
224c7d7c6fbSDavid Majnemer   if (Symb.isSectionDefinition())
225c7d7c6fbSDavid Majnemer     Result |= SymbolRef::SF_FormatSpecific;
226c7d7c6fbSDavid Majnemer 
227c7d7c6fbSDavid Majnemer   if (Symb.isCommon())
228c7d7c6fbSDavid Majnemer     Result |= SymbolRef::SF_Common;
229c7d7c6fbSDavid Majnemer 
230c7d7c6fbSDavid Majnemer   if (Symb.isAnyUndefined())
231c7d7c6fbSDavid Majnemer     Result |= SymbolRef::SF_Undefined;
232c7d7c6fbSDavid Majnemer 
23320122a43SRafael Espindola   return Result;
23401759754SMichael J. Spencer }
23501759754SMichael J. Spencer 
236d7a32ea4SRafael Espindola uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
237c7d7c6fbSDavid Majnemer   COFFSymbolRef Symb = getCOFFSymbol(Ref);
2385eb02e45SRafael Espindola   return Symb.getValue();
2398e90adafSMichael J. Spencer }
2408e90adafSMichael J. Spencer 
241db4ed0bdSRafael Espindola std::error_code
242db4ed0bdSRafael Espindola COFFObjectFile::getSymbolSection(DataRefImpl Ref,
24332173153SMichael J. Spencer                                  section_iterator &Result) const {
24444f51e51SDavid Majnemer   COFFSymbolRef Symb = getCOFFSymbol(Ref);
24544f51e51SDavid Majnemer   if (COFF::isReservedSectionNumber(Symb.getSectionNumber())) {
246b5155a57SRafael Espindola     Result = section_end();
247f078eff3SRui Ueyama   } else {
2482617dcceSCraig Topper     const coff_section *Sec = nullptr;
24944f51e51SDavid Majnemer     if (std::error_code EC = getSection(Symb.getSectionNumber(), Sec))
250db4ed0bdSRafael Espindola       return EC;
2518ff24d25SRui Ueyama     DataRefImpl Ref;
2528ff24d25SRui Ueyama     Ref.p = reinterpret_cast<uintptr_t>(Sec);
2538ff24d25SRui Ueyama     Result = section_iterator(SectionRef(Ref, this));
25432173153SMichael J. Spencer   }
2557d099195SRui Ueyama   return std::error_code();
25632173153SMichael J. Spencer }
25732173153SMichael J. Spencer 
2586bf32210SRafael Espindola unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
2596bf32210SRafael Espindola   COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
2606bf32210SRafael Espindola   return Symb.getSectionNumber();
2616bf32210SRafael Espindola }
2626bf32210SRafael Espindola 
2635e812afaSRafael Espindola void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
2648ff24d25SRui Ueyama   const coff_section *Sec = toSec(Ref);
2658ff24d25SRui Ueyama   Sec += 1;
2668ff24d25SRui Ueyama   Ref.p = reinterpret_cast<uintptr_t>(Sec);
2678e90adafSMichael J. Spencer }
2688e90adafSMichael J. Spencer 
269db4ed0bdSRafael Espindola std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
2701d6167fdSMichael J. Spencer                                                StringRef &Result) const {
2718ff24d25SRui Ueyama   const coff_section *Sec = toSec(Ref);
2728ff24d25SRui Ueyama   return getSectionName(Sec, Result);
2738e90adafSMichael J. Spencer }
2748e90adafSMichael J. Spencer 
27580291274SRafael Espindola uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
2768ff24d25SRui Ueyama   const coff_section *Sec = toSec(Ref);
27780291274SRafael Espindola   return Sec->VirtualAddress;
2788e90adafSMichael J. Spencer }
2798e90adafSMichael J. Spencer 
28080291274SRafael Espindola uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
281a9ee5c06SDavid Majnemer   return getSectionSize(toSec(Ref));
2828e90adafSMichael J. Spencer }
2838e90adafSMichael J. Spencer 
284db4ed0bdSRafael Espindola std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
2851d6167fdSMichael J. Spencer                                                    StringRef &Result) const {
2868ff24d25SRui Ueyama   const coff_section *Sec = toSec(Ref);
2879da9e693SMichael J. Spencer   ArrayRef<uint8_t> Res;
288db4ed0bdSRafael Espindola   std::error_code EC = getSectionContents(Sec, Res);
2899da9e693SMichael J. Spencer   Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
2909da9e693SMichael J. Spencer   return EC;
2918e90adafSMichael J. Spencer }
2928e90adafSMichael J. Spencer 
29380291274SRafael Espindola uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
2948ff24d25SRui Ueyama   const coff_section *Sec = toSec(Ref);
29580291274SRafael Espindola   return uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
2967989460aSMichael J. Spencer }
2977989460aSMichael J. Spencer 
29880291274SRafael Espindola bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
2998ff24d25SRui Ueyama   const coff_section *Sec = toSec(Ref);
30080291274SRafael Espindola   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
3018e90adafSMichael J. Spencer }
3028e90adafSMichael J. Spencer 
30380291274SRafael Espindola bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
3048ff24d25SRui Ueyama   const coff_section *Sec = toSec(Ref);
30580291274SRafael Espindola   return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
306800619f2SMichael J. Spencer }
307800619f2SMichael J. Spencer 
30880291274SRafael Espindola bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
3098ff24d25SRui Ueyama   const coff_section *Sec = toSec(Ref);
3101a666e0fSDavid Majnemer   const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
3111a666e0fSDavid Majnemer                             COFF::IMAGE_SCN_MEM_READ |
3121a666e0fSDavid Majnemer                             COFF::IMAGE_SCN_MEM_WRITE;
3131a666e0fSDavid Majnemer   return (Sec->Characteristics & BssFlags) == BssFlags;
314800619f2SMichael J. Spencer }
315800619f2SMichael J. Spencer 
3166bf32210SRafael Espindola unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
3176bf32210SRafael Espindola   uintptr_t Offset =
3186bf32210SRafael Espindola       uintptr_t(Sec.getRawDataRefImpl().p) - uintptr_t(SectionTable);
3196bf32210SRafael Espindola   assert((Offset % sizeof(coff_section)) == 0);
3206bf32210SRafael Espindola   return (Offset / sizeof(coff_section)) + 1;
3216bf32210SRafael Espindola }
3226bf32210SRafael Espindola 
32380291274SRafael Espindola bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
3248ff24d25SRui Ueyama   const coff_section *Sec = toSec(Ref);
3251a666e0fSDavid Majnemer   // In COFF, a virtual section won't have any in-file
3261a666e0fSDavid Majnemer   // content, so the file pointer to the content will be zero.
3271a666e0fSDavid Majnemer   return Sec->PointerToRawData == 0;
3282138ef6dSPreston Gurd }
3292138ef6dSPreston Gurd 
330e830c60dSDavid Majnemer static uint32_t getNumberOfRelocations(const coff_section *Sec,
331e830c60dSDavid Majnemer                                        MemoryBufferRef M, const uint8_t *base) {
332e830c60dSDavid Majnemer   // The field for the number of relocations in COFF section table is only
333e830c60dSDavid Majnemer   // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
334e830c60dSDavid Majnemer   // NumberOfRelocations field, and the actual relocation count is stored in the
335e830c60dSDavid Majnemer   // VirtualAddress field in the first relocation entry.
336e830c60dSDavid Majnemer   if (Sec->hasExtendedRelocations()) {
337e830c60dSDavid Majnemer     const coff_relocation *FirstReloc;
338e830c60dSDavid Majnemer     if (getObject(FirstReloc, M, reinterpret_cast<const coff_relocation*>(
339e830c60dSDavid Majnemer         base + Sec->PointerToRelocations)))
340e830c60dSDavid Majnemer       return 0;
34198fe58a3SRui Ueyama     // -1 to exclude this first relocation entry.
34298fe58a3SRui Ueyama     return FirstReloc->VirtualAddress - 1;
343e830c60dSDavid Majnemer   }
344e830c60dSDavid Majnemer   return Sec->NumberOfRelocations;
345e830c60dSDavid Majnemer }
346e830c60dSDavid Majnemer 
34794751be7SDavid Majnemer static const coff_relocation *
34894751be7SDavid Majnemer getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
34994751be7SDavid Majnemer   uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
35094751be7SDavid Majnemer   if (!NumRelocs)
35194751be7SDavid Majnemer     return nullptr;
352827c8a2bSRui Ueyama   auto begin = reinterpret_cast<const coff_relocation *>(
35394751be7SDavid Majnemer       Base + Sec->PointerToRelocations);
354827c8a2bSRui Ueyama   if (Sec->hasExtendedRelocations()) {
355827c8a2bSRui Ueyama     // Skip the first relocation entry repurposed to store the number of
356827c8a2bSRui Ueyama     // relocations.
357827c8a2bSRui Ueyama     begin++;
358827c8a2bSRui Ueyama   }
35994751be7SDavid Majnemer   if (checkOffset(M, uintptr_t(begin), sizeof(coff_relocation) * NumRelocs))
36094751be7SDavid Majnemer     return nullptr;
36194751be7SDavid Majnemer   return begin;
362827c8a2bSRui Ueyama }
36394751be7SDavid Majnemer 
36494751be7SDavid Majnemer relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
36594751be7SDavid Majnemer   const coff_section *Sec = toSec(Ref);
36694751be7SDavid Majnemer   const coff_relocation *begin = getFirstReloc(Sec, Data, base());
36776d650e8SRafael Espindola   if (begin && Sec->VirtualAddress != 0)
36876d650e8SRafael Espindola     report_fatal_error("Sections with relocations should have an address of 0");
36994751be7SDavid Majnemer   DataRefImpl Ret;
37094751be7SDavid Majnemer   Ret.p = reinterpret_cast<uintptr_t>(begin);
3718ff24d25SRui Ueyama   return relocation_iterator(RelocationRef(Ret, this));
372e5fd0047SMichael J. Spencer }
373e5fd0047SMichael J. Spencer 
3748ff24d25SRui Ueyama relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
3758ff24d25SRui Ueyama   const coff_section *Sec = toSec(Ref);
37694751be7SDavid Majnemer   const coff_relocation *I = getFirstReloc(Sec, Data, base());
37794751be7SDavid Majnemer   if (I)
37894751be7SDavid Majnemer     I += getNumberOfRelocations(Sec, Data, base());
3798ff24d25SRui Ueyama   DataRefImpl Ret;
38094751be7SDavid Majnemer   Ret.p = reinterpret_cast<uintptr_t>(I);
3818ff24d25SRui Ueyama   return relocation_iterator(RelocationRef(Ret, this));
382e5fd0047SMichael J. Spencer }
383e5fd0047SMichael J. Spencer 
384c2bed429SRui Ueyama // Initialize the pointer to the symbol table.
385db4ed0bdSRafael Espindola std::error_code COFFObjectFile::initSymbolTablePtr() {
38644f51e51SDavid Majnemer   if (COFFHeader)
387236b0ca7SDavid Majnemer     if (std::error_code EC = getObject(
388236b0ca7SDavid Majnemer             SymbolTable16, Data, base() + getPointerToSymbolTable(),
389236b0ca7SDavid Majnemer             (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
39044f51e51SDavid Majnemer       return EC;
39144f51e51SDavid Majnemer 
39244f51e51SDavid Majnemer   if (COFFBigObjHeader)
393236b0ca7SDavid Majnemer     if (std::error_code EC = getObject(
394236b0ca7SDavid Majnemer             SymbolTable32, Data, base() + getPointerToSymbolTable(),
395236b0ca7SDavid Majnemer             (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
3968ff24d25SRui Ueyama       return EC;
397c2bed429SRui Ueyama 
398c2bed429SRui Ueyama   // Find string table. The first four byte of the string table contains the
399c2bed429SRui Ueyama   // total size of the string table, including the size field itself. If the
400c2bed429SRui Ueyama   // string table is empty, the value of the first four byte would be 4.
401f69b0585SDavid Majnemer   uint32_t StringTableOffset = getPointerToSymbolTable() +
40244f51e51SDavid Majnemer                                getNumberOfSymbols() * getSymbolTableEntrySize();
403f69b0585SDavid Majnemer   const uint8_t *StringTableAddr = base() + StringTableOffset;
404c2bed429SRui Ueyama   const ulittle32_t *StringTableSizePtr;
40548af1c2aSRafael Espindola   if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
4068ff24d25SRui Ueyama     return EC;
407c2bed429SRui Ueyama   StringTableSize = *StringTableSizePtr;
408db4ed0bdSRafael Espindola   if (std::error_code EC =
40948af1c2aSRafael Espindola           getObject(StringTable, Data, StringTableAddr, StringTableSize))
4108ff24d25SRui Ueyama     return EC;
411c2bed429SRui Ueyama 
412773a5795SNico Rieck   // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
413773a5795SNico Rieck   // tools like cvtres write a size of 0 for an empty table instead of 4.
414773a5795SNico Rieck   if (StringTableSize < 4)
415773a5795SNico Rieck       StringTableSize = 4;
416773a5795SNico Rieck 
417c2bed429SRui Ueyama   // Check that the string table is null terminated if has any in it.
418773a5795SNico Rieck   if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
419c2bed429SRui Ueyama     return  object_error::parse_failed;
4207d099195SRui Ueyama   return std::error_code();
421c2bed429SRui Ueyama }
422c2bed429SRui Ueyama 
423215a586cSRui Ueyama // Returns the file offset for the given VA.
424db4ed0bdSRafael Espindola std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
425b6eb264aSRui Ueyama   uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
426b6eb264aSRui Ueyama                                   : (uint64_t)PE32PlusHeader->ImageBase;
427b7a40081SRui Ueyama   uint64_t Rva = Addr - ImageBase;
428b7a40081SRui Ueyama   assert(Rva <= UINT32_MAX);
429b7a40081SRui Ueyama   return getRvaPtr((uint32_t)Rva, Res);
430215a586cSRui Ueyama }
431215a586cSRui Ueyama 
432c2bed429SRui Ueyama // Returns the file offset for the given RVA.
433db4ed0bdSRafael Espindola std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
43427dc8394SAlexey Samsonov   for (const SectionRef &S : sections()) {
43527dc8394SAlexey Samsonov     const coff_section *Section = getCOFFSection(S);
436c2bed429SRui Ueyama     uint32_t SectionStart = Section->VirtualAddress;
437c2bed429SRui Ueyama     uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
438215a586cSRui Ueyama     if (SectionStart <= Addr && Addr < SectionEnd) {
439215a586cSRui Ueyama       uint32_t Offset = Addr - SectionStart;
440c2bed429SRui Ueyama       Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
4417d099195SRui Ueyama       return std::error_code();
442c2bed429SRui Ueyama     }
443c2bed429SRui Ueyama   }
444c2bed429SRui Ueyama   return object_error::parse_failed;
445c2bed429SRui Ueyama }
446c2bed429SRui Ueyama 
447c2bed429SRui Ueyama // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
448c2bed429SRui Ueyama // table entry.
449db4ed0bdSRafael Espindola std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
450db4ed0bdSRafael Espindola                                             StringRef &Name) const {
451c2bed429SRui Ueyama   uintptr_t IntPtr = 0;
452db4ed0bdSRafael Espindola   if (std::error_code EC = getRvaPtr(Rva, IntPtr))
4538ff24d25SRui Ueyama     return EC;
454c2bed429SRui Ueyama   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
455c2bed429SRui Ueyama   Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
456c2bed429SRui Ueyama   Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
4577d099195SRui Ueyama   return std::error_code();
458c2bed429SRui Ueyama }
459c2bed429SRui Ueyama 
460c2bed429SRui Ueyama // Find the import table.
461db4ed0bdSRafael Espindola std::error_code COFFObjectFile::initImportTablePtr() {
462c2bed429SRui Ueyama   // First, we get the RVA of the import table. If the file lacks a pointer to
463c2bed429SRui Ueyama   // the import table, do nothing.
464c2bed429SRui Ueyama   const data_directory *DataEntry;
465c2bed429SRui Ueyama   if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
4667d099195SRui Ueyama     return std::error_code();
467c2bed429SRui Ueyama 
468c2bed429SRui Ueyama   // Do nothing if the pointer to import table is NULL.
469c2bed429SRui Ueyama   if (DataEntry->RelativeVirtualAddress == 0)
4707d099195SRui Ueyama     return std::error_code();
471c2bed429SRui Ueyama 
472c2bed429SRui Ueyama   uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
4731e152d5eSRui Ueyama   // -1 because the last entry is the null entry.
474c2bed429SRui Ueyama   NumberOfImportDirectory = DataEntry->Size /
4751e152d5eSRui Ueyama       sizeof(import_directory_table_entry) - 1;
476c2bed429SRui Ueyama 
477c2bed429SRui Ueyama   // Find the section that contains the RVA. This is needed because the RVA is
478c2bed429SRui Ueyama   // the import table's memory address which is different from its file offset.
479c2bed429SRui Ueyama   uintptr_t IntPtr = 0;
480db4ed0bdSRafael Espindola   if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
4818ff24d25SRui Ueyama     return EC;
482c2bed429SRui Ueyama   ImportDirectory = reinterpret_cast<
483c2bed429SRui Ueyama       const import_directory_table_entry *>(IntPtr);
4847d099195SRui Ueyama   return std::error_code();
485ad882ba8SRui Ueyama }
486c2bed429SRui Ueyama 
48715d99359SRui Ueyama // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
48815d99359SRui Ueyama std::error_code COFFObjectFile::initDelayImportTablePtr() {
48915d99359SRui Ueyama   const data_directory *DataEntry;
49015d99359SRui Ueyama   if (getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR, DataEntry))
4917d099195SRui Ueyama     return std::error_code();
49215d99359SRui Ueyama   if (DataEntry->RelativeVirtualAddress == 0)
4937d099195SRui Ueyama     return std::error_code();
49415d99359SRui Ueyama 
49515d99359SRui Ueyama   uint32_t RVA = DataEntry->RelativeVirtualAddress;
49615d99359SRui Ueyama   NumberOfDelayImportDirectory = DataEntry->Size /
49715d99359SRui Ueyama       sizeof(delay_import_directory_table_entry) - 1;
49815d99359SRui Ueyama 
49915d99359SRui Ueyama   uintptr_t IntPtr = 0;
50015d99359SRui Ueyama   if (std::error_code EC = getRvaPtr(RVA, IntPtr))
50115d99359SRui Ueyama     return EC;
50215d99359SRui Ueyama   DelayImportDirectory = reinterpret_cast<
50315d99359SRui Ueyama       const delay_import_directory_table_entry *>(IntPtr);
5047d099195SRui Ueyama   return std::error_code();
50515d99359SRui Ueyama }
50615d99359SRui Ueyama 
507ad882ba8SRui Ueyama // Find the export table.
508db4ed0bdSRafael Espindola std::error_code COFFObjectFile::initExportTablePtr() {
509ad882ba8SRui Ueyama   // First, we get the RVA of the export table. If the file lacks a pointer to
510ad882ba8SRui Ueyama   // the export table, do nothing.
511ad882ba8SRui Ueyama   const data_directory *DataEntry;
512ad882ba8SRui Ueyama   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
5137d099195SRui Ueyama     return std::error_code();
514ad882ba8SRui Ueyama 
515ad882ba8SRui Ueyama   // Do nothing if the pointer to export table is NULL.
516ad882ba8SRui Ueyama   if (DataEntry->RelativeVirtualAddress == 0)
5177d099195SRui Ueyama     return std::error_code();
518ad882ba8SRui Ueyama 
519ad882ba8SRui Ueyama   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
520ad882ba8SRui Ueyama   uintptr_t IntPtr = 0;
521db4ed0bdSRafael Espindola   if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
522ad882ba8SRui Ueyama     return EC;
52324fc2d64SRui Ueyama   ExportDirectory =
52424fc2d64SRui Ueyama       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
5257d099195SRui Ueyama   return std::error_code();
526c2bed429SRui Ueyama }
527c2bed429SRui Ueyama 
52874e85130SRui Ueyama std::error_code COFFObjectFile::initBaseRelocPtr() {
52974e85130SRui Ueyama   const data_directory *DataEntry;
53074e85130SRui Ueyama   if (getDataDirectory(COFF::BASE_RELOCATION_TABLE, DataEntry))
5317d099195SRui Ueyama     return std::error_code();
53274e85130SRui Ueyama   if (DataEntry->RelativeVirtualAddress == 0)
5337d099195SRui Ueyama     return std::error_code();
53474e85130SRui Ueyama 
53574e85130SRui Ueyama   uintptr_t IntPtr = 0;
53674e85130SRui Ueyama   if (std::error_code EC = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
53774e85130SRui Ueyama     return EC;
53874e85130SRui Ueyama   BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
53974e85130SRui Ueyama       IntPtr);
54074e85130SRui Ueyama   BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
54174e85130SRui Ueyama       IntPtr + DataEntry->Size);
5427d099195SRui Ueyama   return std::error_code();
54374e85130SRui Ueyama }
54474e85130SRui Ueyama 
54548af1c2aSRafael Espindola COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
54648af1c2aSRafael Espindola     : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
54744f51e51SDavid Majnemer       COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
54844f51e51SDavid Majnemer       DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
54944f51e51SDavid Majnemer       SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
55044f51e51SDavid Majnemer       ImportDirectory(nullptr), NumberOfImportDirectory(0),
55115d99359SRui Ueyama       DelayImportDirectory(nullptr), NumberOfDelayImportDirectory(0),
55274e85130SRui Ueyama       ExportDirectory(nullptr), BaseRelocHeader(nullptr),
55374e85130SRui Ueyama       BaseRelocEnd(nullptr) {
5541d6167fdSMichael J. Spencer   // Check that we at least have enough room for a header.
55548af1c2aSRafael Espindola   if (!checkSize(Data, EC, sizeof(coff_file_header)))
556c3f9b5a5SRafael Espindola     return;
557ee066fc4SEric Christopher 
55882ebd8e3SRui Ueyama   // The current location in the file where we are looking at.
55982ebd8e3SRui Ueyama   uint64_t CurPtr = 0;
56082ebd8e3SRui Ueyama 
56182ebd8e3SRui Ueyama   // PE header is optional and is present only in executables. If it exists,
56282ebd8e3SRui Ueyama   // it is placed right after COFF header.
5638ff24d25SRui Ueyama   bool HasPEHeader = false;
564ee066fc4SEric Christopher 
5651d6167fdSMichael J. Spencer   // Check if this is a PE/COFF file.
56650267222SDavid Majnemer   if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
567ee066fc4SEric Christopher     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
568ee066fc4SEric Christopher     // PE signature to find 'normal' COFF header.
56950267222SDavid Majnemer     const auto *DH = reinterpret_cast<const dos_header *>(base());
57050267222SDavid Majnemer     if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
57150267222SDavid Majnemer       CurPtr = DH->AddressOfNewExeHeader;
57282ebd8e3SRui Ueyama       // Check the PE magic bytes. ("PE\0\0")
57350267222SDavid Majnemer       if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
5748ff24d25SRui Ueyama         EC = object_error::parse_failed;
5751d6167fdSMichael J. Spencer         return;
5761d6167fdSMichael J. Spencer       }
57744f51e51SDavid Majnemer       CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
5788ff24d25SRui Ueyama       HasPEHeader = true;
579ee066fc4SEric Christopher     }
58050267222SDavid Majnemer   }
581ee066fc4SEric Christopher 
58248af1c2aSRafael Espindola   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
5831d6167fdSMichael J. Spencer     return;
58444f51e51SDavid Majnemer 
58544f51e51SDavid Majnemer   // It might be a bigobj file, let's check.  Note that COFF bigobj and COFF
58644f51e51SDavid Majnemer   // import libraries share a common prefix but bigobj is more restrictive.
58744f51e51SDavid Majnemer   if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
58844f51e51SDavid Majnemer       COFFHeader->NumberOfSections == uint16_t(0xffff) &&
58944f51e51SDavid Majnemer       checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
59044f51e51SDavid Majnemer     if ((EC = getObject(COFFBigObjHeader, Data, base() + CurPtr)))
59144f51e51SDavid Majnemer       return;
59244f51e51SDavid Majnemer 
59344f51e51SDavid Majnemer     // Verify that we are dealing with bigobj.
59444f51e51SDavid Majnemer     if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
59544f51e51SDavid Majnemer         std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
59644f51e51SDavid Majnemer                     sizeof(COFF::BigObjMagic)) == 0) {
59744f51e51SDavid Majnemer       COFFHeader = nullptr;
59844f51e51SDavid Majnemer       CurPtr += sizeof(coff_bigobj_file_header);
59944f51e51SDavid Majnemer     } else {
60044f51e51SDavid Majnemer       // It's not a bigobj.
60144f51e51SDavid Majnemer       COFFBigObjHeader = nullptr;
60244f51e51SDavid Majnemer     }
60344f51e51SDavid Majnemer   }
60444f51e51SDavid Majnemer   if (COFFHeader) {
60544f51e51SDavid Majnemer     // The prior checkSize call may have failed.  This isn't a hard error
60644f51e51SDavid Majnemer     // because we were just trying to sniff out bigobj.
6077d099195SRui Ueyama     EC = std::error_code();
60882ebd8e3SRui Ueyama     CurPtr += sizeof(coff_file_header);
60982ebd8e3SRui Ueyama 
61044f51e51SDavid Majnemer     if (COFFHeader->isImportLibrary())
61144f51e51SDavid Majnemer       return;
61244f51e51SDavid Majnemer   }
61344f51e51SDavid Majnemer 
6148ff24d25SRui Ueyama   if (HasPEHeader) {
61510ed9ddcSRui Ueyama     const pe32_header *Header;
61648af1c2aSRafael Espindola     if ((EC = getObject(Header, Data, base() + CurPtr)))
61782ebd8e3SRui Ueyama       return;
61810ed9ddcSRui Ueyama 
61910ed9ddcSRui Ueyama     const uint8_t *DataDirAddr;
62010ed9ddcSRui Ueyama     uint64_t DataDirSize;
62150267222SDavid Majnemer     if (Header->Magic == COFF::PE32Header::PE32) {
62210ed9ddcSRui Ueyama       PE32Header = Header;
62310ed9ddcSRui Ueyama       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
62410ed9ddcSRui Ueyama       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
62550267222SDavid Majnemer     } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
62610ed9ddcSRui Ueyama       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
62710ed9ddcSRui Ueyama       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
62810ed9ddcSRui Ueyama       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
62910ed9ddcSRui Ueyama     } else {
63010ed9ddcSRui Ueyama       // It's neither PE32 nor PE32+.
63110ed9ddcSRui Ueyama       EC = object_error::parse_failed;
632ed64342bSRui Ueyama       return;
633ed64342bSRui Ueyama     }
63448af1c2aSRafael Espindola     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
63510ed9ddcSRui Ueyama       return;
63682ebd8e3SRui Ueyama     CurPtr += COFFHeader->SizeOfOptionalHeader;
63782ebd8e3SRui Ueyama   }
6381d6167fdSMichael J. Spencer 
63948af1c2aSRafael Espindola   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
640236b0ca7SDavid Majnemer                       (uint64_t)getNumberOfSections() * sizeof(coff_section))))
6411d6167fdSMichael J. Spencer     return;
6421d6167fdSMichael J. Spencer 
643c2bed429SRui Ueyama   // Initialize the pointer to the symbol table.
644236b0ca7SDavid Majnemer   if (getPointerToSymbolTable() != 0) {
6458ff24d25SRui Ueyama     if ((EC = initSymbolTablePtr()))
6461d6167fdSMichael J. Spencer       return;
647236b0ca7SDavid Majnemer   } else {
648236b0ca7SDavid Majnemer     // We had better not have any symbols if we don't have a symbol table.
649236b0ca7SDavid Majnemer     if (getNumberOfSymbols() != 0) {
650236b0ca7SDavid Majnemer       EC = object_error::parse_failed;
651236b0ca7SDavid Majnemer       return;
652236b0ca7SDavid Majnemer     }
653236b0ca7SDavid Majnemer   }
6548e90adafSMichael J. Spencer 
655c2bed429SRui Ueyama   // Initialize the pointer to the beginning of the import table.
6568ff24d25SRui Ueyama   if ((EC = initImportTablePtr()))
657ed64342bSRui Ueyama     return;
65815d99359SRui Ueyama   if ((EC = initDelayImportTablePtr()))
65915d99359SRui Ueyama     return;
6601d6167fdSMichael J. Spencer 
661ad882ba8SRui Ueyama   // Initialize the pointer to the export table.
6628ff24d25SRui Ueyama   if ((EC = initExportTablePtr()))
663ad882ba8SRui Ueyama     return;
664ad882ba8SRui Ueyama 
66574e85130SRui Ueyama   // Initialize the pointer to the base relocation table.
66674e85130SRui Ueyama   if ((EC = initBaseRelocPtr()))
66774e85130SRui Ueyama     return;
66874e85130SRui Ueyama 
6697d099195SRui Ueyama   EC = std::error_code();
6708e90adafSMichael J. Spencer }
6718e90adafSMichael J. Spencer 
672f12b8282SRafael Espindola basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
6738ff24d25SRui Ueyama   DataRefImpl Ret;
67444f51e51SDavid Majnemer   Ret.p = getSymbolTable();
675f12b8282SRafael Espindola   return basic_symbol_iterator(SymbolRef(Ret, this));
6768e90adafSMichael J. Spencer }
6778e90adafSMichael J. Spencer 
678f12b8282SRafael Espindola basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
6798e90adafSMichael J. Spencer   // The symbol table ends where the string table begins.
6808ff24d25SRui Ueyama   DataRefImpl Ret;
6818ff24d25SRui Ueyama   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
682f12b8282SRafael Espindola   return basic_symbol_iterator(SymbolRef(Ret, this));
6838e90adafSMichael J. Spencer }
6848e90adafSMichael J. Spencer 
685bc654b18SRui Ueyama import_directory_iterator COFFObjectFile::import_directory_begin() const {
686a045b73aSRui Ueyama   return import_directory_iterator(
687a045b73aSRui Ueyama       ImportDirectoryEntryRef(ImportDirectory, 0, this));
688c2bed429SRui Ueyama }
689c2bed429SRui Ueyama 
690bc654b18SRui Ueyama import_directory_iterator COFFObjectFile::import_directory_end() const {
691a045b73aSRui Ueyama   return import_directory_iterator(
692a045b73aSRui Ueyama       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
693c2bed429SRui Ueyama }
694c429b80dSDavid Meyer 
69515d99359SRui Ueyama delay_import_directory_iterator
69615d99359SRui Ueyama COFFObjectFile::delay_import_directory_begin() const {
69715d99359SRui Ueyama   return delay_import_directory_iterator(
69815d99359SRui Ueyama       DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
69915d99359SRui Ueyama }
70015d99359SRui Ueyama 
70115d99359SRui Ueyama delay_import_directory_iterator
70215d99359SRui Ueyama COFFObjectFile::delay_import_directory_end() const {
70315d99359SRui Ueyama   return delay_import_directory_iterator(
70415d99359SRui Ueyama       DelayImportDirectoryEntryRef(
70515d99359SRui Ueyama           DelayImportDirectory, NumberOfDelayImportDirectory, this));
70615d99359SRui Ueyama }
70715d99359SRui Ueyama 
708ad882ba8SRui Ueyama export_directory_iterator COFFObjectFile::export_directory_begin() const {
709ad882ba8SRui Ueyama   return export_directory_iterator(
710ad882ba8SRui Ueyama       ExportDirectoryEntryRef(ExportDirectory, 0, this));
711ad882ba8SRui Ueyama }
712ad882ba8SRui Ueyama 
713ad882ba8SRui Ueyama export_directory_iterator COFFObjectFile::export_directory_end() const {
7142617dcceSCraig Topper   if (!ExportDirectory)
7152617dcceSCraig Topper     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
7168ff24d25SRui Ueyama   ExportDirectoryEntryRef Ref(ExportDirectory,
717ad882ba8SRui Ueyama                               ExportDirectory->AddressTableEntries, this);
7188ff24d25SRui Ueyama   return export_directory_iterator(Ref);
719ad882ba8SRui Ueyama }
720ad882ba8SRui Ueyama 
721b5155a57SRafael Espindola section_iterator COFFObjectFile::section_begin() const {
7228ff24d25SRui Ueyama   DataRefImpl Ret;
7238ff24d25SRui Ueyama   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
7248ff24d25SRui Ueyama   return section_iterator(SectionRef(Ret, this));
7258e90adafSMichael J. Spencer }
7268e90adafSMichael J. Spencer 
727b5155a57SRafael Espindola section_iterator COFFObjectFile::section_end() const {
7288ff24d25SRui Ueyama   DataRefImpl Ret;
72944f51e51SDavid Majnemer   int NumSections =
73044f51e51SDavid Majnemer       COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
7318ff24d25SRui Ueyama   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
7328ff24d25SRui Ueyama   return section_iterator(SectionRef(Ret, this));
7338e90adafSMichael J. Spencer }
7348e90adafSMichael J. Spencer 
73574e85130SRui Ueyama base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
73674e85130SRui Ueyama   return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
73774e85130SRui Ueyama }
73874e85130SRui Ueyama 
73974e85130SRui Ueyama base_reloc_iterator COFFObjectFile::base_reloc_end() const {
74074e85130SRui Ueyama   return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
74174e85130SRui Ueyama }
74274e85130SRui Ueyama 
7438e90adafSMichael J. Spencer uint8_t COFFObjectFile::getBytesInAddress() const {
7440324b672SMichael J. Spencer   return getArch() == Triple::x86_64 ? 8 : 4;
7458e90adafSMichael J. Spencer }
7468e90adafSMichael J. Spencer 
7478e90adafSMichael J. Spencer StringRef COFFObjectFile::getFileFormatName() const {
74844f51e51SDavid Majnemer   switch(getMachine()) {
7498e90adafSMichael J. Spencer   case COFF::IMAGE_FILE_MACHINE_I386:
7508e90adafSMichael J. Spencer     return "COFF-i386";
7518e90adafSMichael J. Spencer   case COFF::IMAGE_FILE_MACHINE_AMD64:
7528e90adafSMichael J. Spencer     return "COFF-x86-64";
7539b7c0af2SSaleem Abdulrasool   case COFF::IMAGE_FILE_MACHINE_ARMNT:
7549b7c0af2SSaleem Abdulrasool     return "COFF-ARM";
7551eff5c9cSMartell Malone   case COFF::IMAGE_FILE_MACHINE_ARM64:
7561eff5c9cSMartell Malone     return "COFF-ARM64";
7578e90adafSMichael J. Spencer   default:
7588e90adafSMichael J. Spencer     return "COFF-<unknown arch>";
7598e90adafSMichael J. Spencer   }
7608e90adafSMichael J. Spencer }
7618e90adafSMichael J. Spencer 
7628e90adafSMichael J. Spencer unsigned COFFObjectFile::getArch() const {
76344f51e51SDavid Majnemer   switch (getMachine()) {
7648e90adafSMichael J. Spencer   case COFF::IMAGE_FILE_MACHINE_I386:
7658e90adafSMichael J. Spencer     return Triple::x86;
7668e90adafSMichael J. Spencer   case COFF::IMAGE_FILE_MACHINE_AMD64:
7678e90adafSMichael J. Spencer     return Triple::x86_64;
7689b7c0af2SSaleem Abdulrasool   case COFF::IMAGE_FILE_MACHINE_ARMNT:
7699b7c0af2SSaleem Abdulrasool     return Triple::thumb;
7701eff5c9cSMartell Malone   case COFF::IMAGE_FILE_MACHINE_ARM64:
7711eff5c9cSMartell Malone     return Triple::aarch64;
7728e90adafSMichael J. Spencer   default:
7738e90adafSMichael J. Spencer     return Triple::UnknownArch;
7748e90adafSMichael J. Spencer   }
7758e90adafSMichael J. Spencer }
7768e90adafSMichael J. Spencer 
777979fb40bSRui Ueyama iterator_range<import_directory_iterator>
778979fb40bSRui Ueyama COFFObjectFile::import_directories() const {
779979fb40bSRui Ueyama   return make_range(import_directory_begin(), import_directory_end());
780979fb40bSRui Ueyama }
781979fb40bSRui Ueyama 
782979fb40bSRui Ueyama iterator_range<delay_import_directory_iterator>
783979fb40bSRui Ueyama COFFObjectFile::delay_import_directories() const {
784979fb40bSRui Ueyama   return make_range(delay_import_directory_begin(),
785979fb40bSRui Ueyama                     delay_import_directory_end());
786979fb40bSRui Ueyama }
787979fb40bSRui Ueyama 
788979fb40bSRui Ueyama iterator_range<export_directory_iterator>
789979fb40bSRui Ueyama COFFObjectFile::export_directories() const {
790979fb40bSRui Ueyama   return make_range(export_directory_begin(), export_directory_end());
791979fb40bSRui Ueyama }
792979fb40bSRui Ueyama 
79374e85130SRui Ueyama iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
79474e85130SRui Ueyama   return make_range(base_reloc_begin(), base_reloc_end());
79574e85130SRui Ueyama }
79674e85130SRui Ueyama 
797db4ed0bdSRafael Espindola std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
79882ebd8e3SRui Ueyama   Res = PE32Header;
7997d099195SRui Ueyama   return std::error_code();
80089a7a5eaSMichael J. Spencer }
80189a7a5eaSMichael J. Spencer 
802db4ed0bdSRafael Espindola std::error_code
80310ed9ddcSRui Ueyama COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
80410ed9ddcSRui Ueyama   Res = PE32PlusHeader;
8057d099195SRui Ueyama   return std::error_code();
80610ed9ddcSRui Ueyama }
80710ed9ddcSRui Ueyama 
808db4ed0bdSRafael Espindola std::error_code
809db4ed0bdSRafael Espindola COFFObjectFile::getDataDirectory(uint32_t Index,
810ed64342bSRui Ueyama                                  const data_directory *&Res) const {
811ed64342bSRui Ueyama   // Error if if there's no data directory or the index is out of range.
812f69b0585SDavid Majnemer   if (!DataDirectory) {
813f69b0585SDavid Majnemer     Res = nullptr;
81410ed9ddcSRui Ueyama     return object_error::parse_failed;
815f69b0585SDavid Majnemer   }
81610ed9ddcSRui Ueyama   assert(PE32Header || PE32PlusHeader);
81710ed9ddcSRui Ueyama   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
81810ed9ddcSRui Ueyama                                : PE32PlusHeader->NumberOfRvaAndSize;
819f69b0585SDavid Majnemer   if (Index >= NumEnt) {
820f69b0585SDavid Majnemer     Res = nullptr;
821ed64342bSRui Ueyama     return object_error::parse_failed;
822f69b0585SDavid Majnemer   }
8238ff24d25SRui Ueyama   Res = &DataDirectory[Index];
8247d099195SRui Ueyama   return std::error_code();
825ed64342bSRui Ueyama }
826ed64342bSRui Ueyama 
827db4ed0bdSRafael Espindola std::error_code COFFObjectFile::getSection(int32_t Index,
8281d6167fdSMichael J. Spencer                                            const coff_section *&Result) const {
8292617dcceSCraig Topper   Result = nullptr;
830236b0ca7SDavid Majnemer   if (COFF::isReservedSectionNumber(Index))
8317d099195SRui Ueyama     return std::error_code();
832236b0ca7SDavid Majnemer   if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
8331d6167fdSMichael J. Spencer     // We already verified the section table data, so no need to check again.
8348ff24d25SRui Ueyama     Result = SectionTable + (Index - 1);
8357d099195SRui Ueyama     return std::error_code();
8368e90adafSMichael J. Spencer   }
837236b0ca7SDavid Majnemer   return object_error::parse_failed;
838236b0ca7SDavid Majnemer }
8398e90adafSMichael J. Spencer 
840db4ed0bdSRafael Espindola std::error_code COFFObjectFile::getString(uint32_t Offset,
8411d6167fdSMichael J. Spencer                                           StringRef &Result) const {
8421d6167fdSMichael J. Spencer   if (StringTableSize <= 4)
8431d6167fdSMichael J. Spencer     // Tried to get a string from an empty string table.
8441d6167fdSMichael J. Spencer     return object_error::parse_failed;
8458ff24d25SRui Ueyama   if (Offset >= StringTableSize)
8461d6167fdSMichael J. Spencer     return object_error::unexpected_eof;
8478ff24d25SRui Ueyama   Result = StringRef(StringTable + Offset);
8487d099195SRui Ueyama   return std::error_code();
8498e90adafSMichael J. Spencer }
850022ecdf2SBenjamin Kramer 
85144f51e51SDavid Majnemer std::error_code COFFObjectFile::getSymbolName(COFFSymbolRef Symbol,
85289a7a5eaSMichael J. Spencer                                               StringRef &Res) const {
853e40d30f3SRui Ueyama   return getSymbolName(Symbol.getGeneric(), Res);
854e40d30f3SRui Ueyama }
855e40d30f3SRui Ueyama 
856e40d30f3SRui Ueyama std::error_code COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol,
857e40d30f3SRui Ueyama                                               StringRef &Res) const {
85889a7a5eaSMichael J. Spencer   // Check for string table entry. First 4 bytes are 0.
859e40d30f3SRui Ueyama   if (Symbol->Name.Offset.Zeroes == 0) {
860e40d30f3SRui Ueyama     if (std::error_code EC = getString(Symbol->Name.Offset.Offset, Res))
8618ff24d25SRui Ueyama       return EC;
8627d099195SRui Ueyama     return std::error_code();
86389a7a5eaSMichael J. Spencer   }
86489a7a5eaSMichael J. Spencer 
865e40d30f3SRui Ueyama   if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
86689a7a5eaSMichael J. Spencer     // Null terminated, let ::strlen figure out the length.
867e40d30f3SRui Ueyama     Res = StringRef(Symbol->Name.ShortName);
86889a7a5eaSMichael J. Spencer   else
86989a7a5eaSMichael J. Spencer     // Not null terminated, use all 8 bytes.
870e40d30f3SRui Ueyama     Res = StringRef(Symbol->Name.ShortName, COFF::NameSize);
8717d099195SRui Ueyama   return std::error_code();
87289a7a5eaSMichael J. Spencer }
87389a7a5eaSMichael J. Spencer 
87444f51e51SDavid Majnemer ArrayRef<uint8_t>
87544f51e51SDavid Majnemer COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
8762617dcceSCraig Topper   const uint8_t *Aux = nullptr;
87771757ef3SMarshall Clow 
87844f51e51SDavid Majnemer   size_t SymbolSize = getSymbolTableEntrySize();
87944f51e51SDavid Majnemer   if (Symbol.getNumberOfAuxSymbols() > 0) {
88071757ef3SMarshall Clow     // AUX data comes immediately after the symbol in COFF
88144f51e51SDavid Majnemer     Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
88271757ef3SMarshall Clow # ifndef NDEBUG
8838ff24d25SRui Ueyama     // Verify that the Aux symbol points to a valid entry in the symbol table.
8848ff24d25SRui Ueyama     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
88544f51e51SDavid Majnemer     if (Offset < getPointerToSymbolTable() ||
88644f51e51SDavid Majnemer         Offset >=
88744f51e51SDavid Majnemer             getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
88871757ef3SMarshall Clow       report_fatal_error("Aux Symbol data was outside of symbol table.");
88971757ef3SMarshall Clow 
89044f51e51SDavid Majnemer     assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
89144f51e51SDavid Majnemer            "Aux Symbol data did not point to the beginning of a symbol");
89271757ef3SMarshall Clow # endif
893bfb85e67SMarshall Clow   }
89444f51e51SDavid Majnemer   return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
89571757ef3SMarshall Clow }
89671757ef3SMarshall Clow 
897db4ed0bdSRafael Espindola std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
89853c2d547SMichael J. Spencer                                                StringRef &Res) const {
89953c2d547SMichael J. Spencer   StringRef Name;
90044f51e51SDavid Majnemer   if (Sec->Name[COFF::NameSize - 1] == 0)
90153c2d547SMichael J. Spencer     // Null terminated, let ::strlen figure out the length.
90253c2d547SMichael J. Spencer     Name = Sec->Name;
90353c2d547SMichael J. Spencer   else
90453c2d547SMichael J. Spencer     // Not null terminated, use all 8 bytes.
90544f51e51SDavid Majnemer     Name = StringRef(Sec->Name, COFF::NameSize);
90653c2d547SMichael J. Spencer 
90753c2d547SMichael J. Spencer   // Check for string table entry. First byte is '/'.
9082314b3deSDavid Majnemer   if (Name.startswith("/")) {
90953c2d547SMichael J. Spencer     uint32_t Offset;
9102314b3deSDavid Majnemer     if (Name.startswith("//")) {
9119d2c15efSNico Rieck       if (decodeBase64StringEntry(Name.substr(2), Offset))
9129d2c15efSNico Rieck         return object_error::parse_failed;
9139d2c15efSNico Rieck     } else {
91453c2d547SMichael J. Spencer       if (Name.substr(1).getAsInteger(10, Offset))
91553c2d547SMichael J. Spencer         return object_error::parse_failed;
9169d2c15efSNico Rieck     }
917db4ed0bdSRafael Espindola     if (std::error_code EC = getString(Offset, Name))
9188ff24d25SRui Ueyama       return EC;
91953c2d547SMichael J. Spencer   }
92053c2d547SMichael J. Spencer 
92153c2d547SMichael J. Spencer   Res = Name;
9227d099195SRui Ueyama   return std::error_code();
92353c2d547SMichael J. Spencer }
92453c2d547SMichael J. Spencer 
925a9ee5c06SDavid Majnemer uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
926a9ee5c06SDavid Majnemer   // SizeOfRawData and VirtualSize change what they represent depending on
927a9ee5c06SDavid Majnemer   // whether or not we have an executable image.
928a9ee5c06SDavid Majnemer   //
929a9ee5c06SDavid Majnemer   // For object files, SizeOfRawData contains the size of section's data;
930d5297ee7SRui Ueyama   // VirtualSize should be zero but isn't due to buggy COFF writers.
931a9ee5c06SDavid Majnemer   //
932a9ee5c06SDavid Majnemer   // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
933a9ee5c06SDavid Majnemer   // actual section size is in VirtualSize.  It is possible for VirtualSize to
934a9ee5c06SDavid Majnemer   // be greater than SizeOfRawData; the contents past that point should be
935a9ee5c06SDavid Majnemer   // considered to be zero.
936d5297ee7SRui Ueyama   if (getDOSHeader())
937d5297ee7SRui Ueyama     return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
938d5297ee7SRui Ueyama   return Sec->SizeOfRawData;
939a9ee5c06SDavid Majnemer }
940a9ee5c06SDavid Majnemer 
941db4ed0bdSRafael Espindola std::error_code
942db4ed0bdSRafael Espindola COFFObjectFile::getSectionContents(const coff_section *Sec,
9439da9e693SMichael J. Spencer                                    ArrayRef<uint8_t> &Res) const {
944dd9cff2eSDavid Majnemer   // PointerToRawData and SizeOfRawData won't make sense for BSS sections,
945dd9cff2eSDavid Majnemer   // don't do anything interesting for them.
946dac39857SDavid Majnemer   assert((Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0 &&
947dac39857SDavid Majnemer          "BSS sections don't have contents!");
9489da9e693SMichael J. Spencer   // The only thing that we need to verify is that the contents is contained
9499da9e693SMichael J. Spencer   // within the file bounds. We don't need to make sure it doesn't cover other
9509da9e693SMichael J. Spencer   // data, as there's nothing that says that is not allowed.
9519da9e693SMichael J. Spencer   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
952a9ee5c06SDavid Majnemer   uint32_t SectionSize = getSectionSize(Sec);
953e830c60dSDavid Majnemer   if (checkOffset(Data, ConStart, SectionSize))
9549da9e693SMichael J. Spencer     return object_error::parse_failed;
955a9ee5c06SDavid Majnemer   Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
9567d099195SRui Ueyama   return std::error_code();
9579da9e693SMichael J. Spencer }
9589da9e693SMichael J. Spencer 
959022ecdf2SBenjamin Kramer const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
960e5fd0047SMichael J. Spencer   return reinterpret_cast<const coff_relocation*>(Rel.p);
961022ecdf2SBenjamin Kramer }
9628ff24d25SRui Ueyama 
9635e812afaSRafael Espindola void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
964e5fd0047SMichael J. Spencer   Rel.p = reinterpret_cast<uintptr_t>(
965e5fd0047SMichael J. Spencer             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
966022ecdf2SBenjamin Kramer }
9678ff24d25SRui Ueyama 
96896d071cdSRafael Espindola uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
96958323a97SDavid Majnemer   const coff_relocation *R = toRel(Rel);
97096d071cdSRafael Espindola   return R->VirtualAddress;
971cbe72fc9SDanil Malyshev }
9728ff24d25SRui Ueyama 
973806f0064SRafael Espindola symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
974022ecdf2SBenjamin Kramer   const coff_relocation *R = toRel(Rel);
9758ff24d25SRui Ueyama   DataRefImpl Ref;
976236b0ca7SDavid Majnemer   if (R->SymbolTableIndex >= getNumberOfSymbols())
977236b0ca7SDavid Majnemer     return symbol_end();
97844f51e51SDavid Majnemer   if (SymbolTable16)
97944f51e51SDavid Majnemer     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
98044f51e51SDavid Majnemer   else if (SymbolTable32)
98144f51e51SDavid Majnemer     Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
98244f51e51SDavid Majnemer   else
983c7353b58SDavid Majnemer     llvm_unreachable("no symbol table pointer!");
9848ff24d25SRui Ueyama   return symbol_iterator(SymbolRef(Ref, this));
985022ecdf2SBenjamin Kramer }
9868ff24d25SRui Ueyama 
98799c041b7SRafael Espindola uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
988022ecdf2SBenjamin Kramer   const coff_relocation* R = toRel(Rel);
98999c041b7SRafael Espindola   return R->Type;
990022ecdf2SBenjamin Kramer }
991e5fd0047SMichael J. Spencer 
99227dc8394SAlexey Samsonov const coff_section *
99327dc8394SAlexey Samsonov COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
99427dc8394SAlexey Samsonov   return toSec(Section.getRawDataRefImpl());
99571757ef3SMarshall Clow }
99671757ef3SMarshall Clow 
99744f51e51SDavid Majnemer COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
99844f51e51SDavid Majnemer   if (SymbolTable16)
99944f51e51SDavid Majnemer     return toSymb<coff_symbol16>(Ref);
100044f51e51SDavid Majnemer   if (SymbolTable32)
100144f51e51SDavid Majnemer     return toSymb<coff_symbol32>(Ref);
100244f51e51SDavid Majnemer   llvm_unreachable("no symbol table pointer!");
100344f51e51SDavid Majnemer }
100444f51e51SDavid Majnemer 
100544f51e51SDavid Majnemer COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
100644f51e51SDavid Majnemer   return getCOFFSymbol(Symbol.getRawDataRefImpl());
100771757ef3SMarshall Clow }
100871757ef3SMarshall Clow 
1009f12b8282SRafael Espindola const coff_relocation *
101027dc8394SAlexey Samsonov COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
101127dc8394SAlexey Samsonov   return toRel(Reloc.getRawDataRefImpl());
1012d3e2a76cSMarshall Clow }
1013d3e2a76cSMarshall Clow 
10146a75acb1SRui Ueyama iterator_range<const coff_relocation *>
10156a75acb1SRui Ueyama COFFObjectFile::getRelocations(const coff_section *Sec) const {
10166a75acb1SRui Ueyama   const coff_relocation *I = getFirstReloc(Sec, Data, base());
10176a75acb1SRui Ueyama   const coff_relocation *E = I;
10186a75acb1SRui Ueyama   if (I)
10196a75acb1SRui Ueyama     E += getNumberOfRelocations(Sec, Data, base());
10206a75acb1SRui Ueyama   return make_range(I, E);
10216a75acb1SRui Ueyama }
10226a75acb1SRui Ueyama 
102327dc8394SAlexey Samsonov #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
102427dc8394SAlexey Samsonov   case COFF::reloc_type:                                                       \
102527dc8394SAlexey Samsonov     Res = #reloc_type;                                                         \
102627dc8394SAlexey Samsonov     break;
1027e5fd0047SMichael J. Spencer 
102841bb4325SRafael Espindola void COFFObjectFile::getRelocationTypeName(
102941bb4325SRafael Espindola     DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
10308ff24d25SRui Ueyama   const coff_relocation *Reloc = toRel(Rel);
10318ff24d25SRui Ueyama   StringRef Res;
103244f51e51SDavid Majnemer   switch (getMachine()) {
1033e5fd0047SMichael J. Spencer   case COFF::IMAGE_FILE_MACHINE_AMD64:
10348ff24d25SRui Ueyama     switch (Reloc->Type) {
1035e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
1036e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
1037e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
1038e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
1039e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
1040e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
1041e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
1042e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
1043e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
1044e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
1045e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
1046e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
1047e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
1048e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
1049e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
1050e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
1051e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
1052e5fd0047SMichael J. Spencer     default:
10538ff24d25SRui Ueyama       Res = "Unknown";
1054e5fd0047SMichael J. Spencer     }
1055e5fd0047SMichael J. Spencer     break;
10565c503bf4SSaleem Abdulrasool   case COFF::IMAGE_FILE_MACHINE_ARMNT:
10575c503bf4SSaleem Abdulrasool     switch (Reloc->Type) {
10585c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
10595c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
10605c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
10615c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
10625c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
10635c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
10645c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
10655c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
10665c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
10675c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
10685c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
10695c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
10705c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
10715c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
10725c503bf4SSaleem Abdulrasool     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
10735c503bf4SSaleem Abdulrasool     default:
10745c503bf4SSaleem Abdulrasool       Res = "Unknown";
10755c503bf4SSaleem Abdulrasool     }
10765c503bf4SSaleem Abdulrasool     break;
1077e5fd0047SMichael J. Spencer   case COFF::IMAGE_FILE_MACHINE_I386:
10788ff24d25SRui Ueyama     switch (Reloc->Type) {
1079e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
1080e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
1081e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
1082e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
1083e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
1084e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
1085e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
1086e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
1087e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
1088e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
1089e5fd0047SMichael J. Spencer     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
1090e5fd0047SMichael J. Spencer     default:
10918ff24d25SRui Ueyama       Res = "Unknown";
1092e5fd0047SMichael J. Spencer     }
1093e5fd0047SMichael J. Spencer     break;
1094e5fd0047SMichael J. Spencer   default:
10958ff24d25SRui Ueyama     Res = "Unknown";
1096e5fd0047SMichael J. Spencer   }
10978ff24d25SRui Ueyama   Result.append(Res.begin(), Res.end());
1098e5fd0047SMichael J. Spencer }
1099e5fd0047SMichael J. Spencer 
1100e5fd0047SMichael J. Spencer #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
1101e5fd0047SMichael J. Spencer 
1102c66d761bSRafael Espindola bool COFFObjectFile::isRelocatableObject() const {
1103c66d761bSRafael Espindola   return !DataDirectory;
1104c66d761bSRafael Espindola }
1105c66d761bSRafael Espindola 
1106c2bed429SRui Ueyama bool ImportDirectoryEntryRef::
1107c2bed429SRui Ueyama operator==(const ImportDirectoryEntryRef &Other) const {
1108a045b73aSRui Ueyama   return ImportTable == Other.ImportTable && Index == Other.Index;
1109c2bed429SRui Ueyama }
1110c2bed429SRui Ueyama 
11115e812afaSRafael Espindola void ImportDirectoryEntryRef::moveNext() {
11125e812afaSRafael Espindola   ++Index;
1113c2bed429SRui Ueyama }
1114c2bed429SRui Ueyama 
1115db4ed0bdSRafael Espindola std::error_code ImportDirectoryEntryRef::getImportTableEntry(
1116db4ed0bdSRafael Espindola     const import_directory_table_entry *&Result) const {
11171e152d5eSRui Ueyama   Result = ImportTable + Index;
11187d099195SRui Ueyama   return std::error_code();
1119c2bed429SRui Ueyama }
1120c2bed429SRui Ueyama 
1121861021f9SRui Ueyama static imported_symbol_iterator
112215d99359SRui Ueyama makeImportedSymbolIterator(const COFFObjectFile *Object,
1123861021f9SRui Ueyama                            uintptr_t Ptr, int Index) {
112415d99359SRui Ueyama   if (Object->getBytesInAddress() == 4) {
1125861021f9SRui Ueyama     auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
112615d99359SRui Ueyama     return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1127861021f9SRui Ueyama   }
1128861021f9SRui Ueyama   auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
112915d99359SRui Ueyama   return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
1130861021f9SRui Ueyama }
1131861021f9SRui Ueyama 
113215d99359SRui Ueyama static imported_symbol_iterator
113315d99359SRui Ueyama importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
1134861021f9SRui Ueyama   uintptr_t IntPtr = 0;
113515d99359SRui Ueyama   Object->getRvaPtr(RVA, IntPtr);
113615d99359SRui Ueyama   return makeImportedSymbolIterator(Object, IntPtr, 0);
1137861021f9SRui Ueyama }
1138861021f9SRui Ueyama 
113915d99359SRui Ueyama static imported_symbol_iterator
114015d99359SRui Ueyama importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
1141861021f9SRui Ueyama   uintptr_t IntPtr = 0;
114215d99359SRui Ueyama   Object->getRvaPtr(RVA, IntPtr);
1143861021f9SRui Ueyama   // Forward the pointer to the last entry which is null.
1144861021f9SRui Ueyama   int Index = 0;
114515d99359SRui Ueyama   if (Object->getBytesInAddress() == 4) {
1146861021f9SRui Ueyama     auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
1147861021f9SRui Ueyama     while (*Entry++)
1148861021f9SRui Ueyama       ++Index;
1149861021f9SRui Ueyama   } else {
1150861021f9SRui Ueyama     auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
1151861021f9SRui Ueyama     while (*Entry++)
1152861021f9SRui Ueyama       ++Index;
1153861021f9SRui Ueyama   }
115415d99359SRui Ueyama   return makeImportedSymbolIterator(Object, IntPtr, Index);
115515d99359SRui Ueyama }
115615d99359SRui Ueyama 
115715d99359SRui Ueyama imported_symbol_iterator
115815d99359SRui Ueyama ImportDirectoryEntryRef::imported_symbol_begin() const {
115915d99359SRui Ueyama   return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
116015d99359SRui Ueyama                              OwningObject);
116115d99359SRui Ueyama }
116215d99359SRui Ueyama 
116315d99359SRui Ueyama imported_symbol_iterator
116415d99359SRui Ueyama ImportDirectoryEntryRef::imported_symbol_end() const {
116515d99359SRui Ueyama   return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
116615d99359SRui Ueyama                            OwningObject);
1167861021f9SRui Ueyama }
1168861021f9SRui Ueyama 
1169979fb40bSRui Ueyama iterator_range<imported_symbol_iterator>
1170979fb40bSRui Ueyama ImportDirectoryEntryRef::imported_symbols() const {
1171979fb40bSRui Ueyama   return make_range(imported_symbol_begin(), imported_symbol_end());
1172979fb40bSRui Ueyama }
1173979fb40bSRui Ueyama 
1174db4ed0bdSRafael Espindola std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
1175c2bed429SRui Ueyama   uintptr_t IntPtr = 0;
1176db4ed0bdSRafael Espindola   if (std::error_code EC =
11771e152d5eSRui Ueyama           OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
1178a045b73aSRui Ueyama     return EC;
1179a045b73aSRui Ueyama   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
11807d099195SRui Ueyama   return std::error_code();
1181c2bed429SRui Ueyama }
1182c2bed429SRui Ueyama 
11831e152d5eSRui Ueyama std::error_code
11841e152d5eSRui Ueyama ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t  &Result) const {
11851e152d5eSRui Ueyama   Result = ImportTable[Index].ImportLookupTableRVA;
11867d099195SRui Ueyama   return std::error_code();
11871e152d5eSRui Ueyama }
11881e152d5eSRui Ueyama 
11891e152d5eSRui Ueyama std::error_code
11901e152d5eSRui Ueyama ImportDirectoryEntryRef::getImportAddressTableRVA(uint32_t &Result) const {
11911e152d5eSRui Ueyama   Result = ImportTable[Index].ImportAddressTableRVA;
11927d099195SRui Ueyama   return std::error_code();
11931e152d5eSRui Ueyama }
11941e152d5eSRui Ueyama 
1195db4ed0bdSRafael Espindola std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1196c2bed429SRui Ueyama     const import_lookup_table_entry32 *&Result) const {
1197c2bed429SRui Ueyama   uintptr_t IntPtr = 0;
11981e152d5eSRui Ueyama   uint32_t RVA = ImportTable[Index].ImportLookupTableRVA;
11991e152d5eSRui Ueyama   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1200a045b73aSRui Ueyama     return EC;
1201c2bed429SRui Ueyama   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
12027d099195SRui Ueyama   return std::error_code();
1203c2bed429SRui Ueyama }
1204c2bed429SRui Ueyama 
120515d99359SRui Ueyama bool DelayImportDirectoryEntryRef::
120615d99359SRui Ueyama operator==(const DelayImportDirectoryEntryRef &Other) const {
120715d99359SRui Ueyama   return Table == Other.Table && Index == Other.Index;
120815d99359SRui Ueyama }
120915d99359SRui Ueyama 
121015d99359SRui Ueyama void DelayImportDirectoryEntryRef::moveNext() {
121115d99359SRui Ueyama   ++Index;
121215d99359SRui Ueyama }
121315d99359SRui Ueyama 
121415d99359SRui Ueyama imported_symbol_iterator
121515d99359SRui Ueyama DelayImportDirectoryEntryRef::imported_symbol_begin() const {
121615d99359SRui Ueyama   return importedSymbolBegin(Table[Index].DelayImportNameTable,
121715d99359SRui Ueyama                              OwningObject);
121815d99359SRui Ueyama }
121915d99359SRui Ueyama 
122015d99359SRui Ueyama imported_symbol_iterator
122115d99359SRui Ueyama DelayImportDirectoryEntryRef::imported_symbol_end() const {
122215d99359SRui Ueyama   return importedSymbolEnd(Table[Index].DelayImportNameTable,
122315d99359SRui Ueyama                            OwningObject);
122415d99359SRui Ueyama }
122515d99359SRui Ueyama 
1226979fb40bSRui Ueyama iterator_range<imported_symbol_iterator>
1227979fb40bSRui Ueyama DelayImportDirectoryEntryRef::imported_symbols() const {
1228979fb40bSRui Ueyama   return make_range(imported_symbol_begin(), imported_symbol_end());
1229979fb40bSRui Ueyama }
1230979fb40bSRui Ueyama 
123115d99359SRui Ueyama std::error_code DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
123215d99359SRui Ueyama   uintptr_t IntPtr = 0;
123315d99359SRui Ueyama   if (std::error_code EC = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
123415d99359SRui Ueyama     return EC;
123515d99359SRui Ueyama   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
12367d099195SRui Ueyama   return std::error_code();
123715d99359SRui Ueyama }
123815d99359SRui Ueyama 
12391af08658SRui Ueyama std::error_code DelayImportDirectoryEntryRef::
12401af08658SRui Ueyama getDelayImportTable(const delay_import_directory_table_entry *&Result) const {
12411af08658SRui Ueyama   Result = Table;
12427d099195SRui Ueyama   return std::error_code();
12431af08658SRui Ueyama }
12441af08658SRui Ueyama 
1245ffa4cebeSRui Ueyama std::error_code DelayImportDirectoryEntryRef::
1246ffa4cebeSRui Ueyama getImportAddress(int AddrIndex, uint64_t &Result) const {
1247ffa4cebeSRui Ueyama   uint32_t RVA = Table[Index].DelayImportAddressTable +
1248ffa4cebeSRui Ueyama       AddrIndex * (OwningObject->is64() ? 8 : 4);
1249ffa4cebeSRui Ueyama   uintptr_t IntPtr = 0;
1250ffa4cebeSRui Ueyama   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1251ffa4cebeSRui Ueyama     return EC;
1252ffa4cebeSRui Ueyama   if (OwningObject->is64())
12535dcf11d1SRui Ueyama     Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
1254ffa4cebeSRui Ueyama   else
12555dcf11d1SRui Ueyama     Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
12567d099195SRui Ueyama   return std::error_code();
1257ffa4cebeSRui Ueyama }
1258ffa4cebeSRui Ueyama 
1259ad882ba8SRui Ueyama bool ExportDirectoryEntryRef::
1260ad882ba8SRui Ueyama operator==(const ExportDirectoryEntryRef &Other) const {
1261ad882ba8SRui Ueyama   return ExportTable == Other.ExportTable && Index == Other.Index;
1262ad882ba8SRui Ueyama }
1263ad882ba8SRui Ueyama 
12645e812afaSRafael Espindola void ExportDirectoryEntryRef::moveNext() {
12655e812afaSRafael Espindola   ++Index;
1266ad882ba8SRui Ueyama }
1267ad882ba8SRui Ueyama 
1268da49d0d4SRui Ueyama // Returns the name of the current export symbol. If the symbol is exported only
1269da49d0d4SRui Ueyama // by ordinal, the empty string is set as a result.
1270db4ed0bdSRafael Espindola std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1271da49d0d4SRui Ueyama   uintptr_t IntPtr = 0;
1272db4ed0bdSRafael Espindola   if (std::error_code EC =
1273db4ed0bdSRafael Espindola           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1274da49d0d4SRui Ueyama     return EC;
1275da49d0d4SRui Ueyama   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
12767d099195SRui Ueyama   return std::error_code();
1277da49d0d4SRui Ueyama }
1278da49d0d4SRui Ueyama 
1279e5df6095SRui Ueyama // Returns the starting ordinal number.
1280db4ed0bdSRafael Espindola std::error_code
1281db4ed0bdSRafael Espindola ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1282e5df6095SRui Ueyama   Result = ExportTable->OrdinalBase;
12837d099195SRui Ueyama   return std::error_code();
1284e5df6095SRui Ueyama }
1285e5df6095SRui Ueyama 
1286ad882ba8SRui Ueyama // Returns the export ordinal of the current export symbol.
1287db4ed0bdSRafael Espindola std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1288ad882ba8SRui Ueyama   Result = ExportTable->OrdinalBase + Index;
12897d099195SRui Ueyama   return std::error_code();
1290ad882ba8SRui Ueyama }
1291ad882ba8SRui Ueyama 
1292ad882ba8SRui Ueyama // Returns the address of the current export symbol.
1293db4ed0bdSRafael Espindola std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1294ad882ba8SRui Ueyama   uintptr_t IntPtr = 0;
1295db4ed0bdSRafael Espindola   if (std::error_code EC =
1296db4ed0bdSRafael Espindola           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1297ad882ba8SRui Ueyama     return EC;
129824fc2d64SRui Ueyama   const export_address_table_entry *entry =
129924fc2d64SRui Ueyama       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1300ad882ba8SRui Ueyama   Result = entry[Index].ExportRVA;
13017d099195SRui Ueyama   return std::error_code();
1302ad882ba8SRui Ueyama }
1303ad882ba8SRui Ueyama 
1304ad882ba8SRui Ueyama // Returns the name of the current export symbol. If the symbol is exported only
1305ad882ba8SRui Ueyama // by ordinal, the empty string is set as a result.
1306db4ed0bdSRafael Espindola std::error_code
1307db4ed0bdSRafael Espindola ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1308ad882ba8SRui Ueyama   uintptr_t IntPtr = 0;
1309db4ed0bdSRafael Espindola   if (std::error_code EC =
1310db4ed0bdSRafael Espindola           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1311ad882ba8SRui Ueyama     return EC;
1312ad882ba8SRui Ueyama   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1313ad882ba8SRui Ueyama 
1314ad882ba8SRui Ueyama   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1315ad882ba8SRui Ueyama   int Offset = 0;
1316ad882ba8SRui Ueyama   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1317ad882ba8SRui Ueyama        I < E; ++I, ++Offset) {
1318ad882ba8SRui Ueyama     if (*I != Index)
1319ad882ba8SRui Ueyama       continue;
1320db4ed0bdSRafael Espindola     if (std::error_code EC =
1321db4ed0bdSRafael Espindola             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1322ad882ba8SRui Ueyama       return EC;
1323ad882ba8SRui Ueyama     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1324db4ed0bdSRafael Espindola     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1325ad882ba8SRui Ueyama       return EC;
1326ad882ba8SRui Ueyama     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
13277d099195SRui Ueyama     return std::error_code();
1328ad882ba8SRui Ueyama   }
1329ad882ba8SRui Ueyama   Result = "";
13307d099195SRui Ueyama   return std::error_code();
1331ad882ba8SRui Ueyama }
1332ad882ba8SRui Ueyama 
1333861021f9SRui Ueyama bool ImportedSymbolRef::
1334861021f9SRui Ueyama operator==(const ImportedSymbolRef &Other) const {
1335861021f9SRui Ueyama   return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
1336861021f9SRui Ueyama       && Index == Other.Index;
1337861021f9SRui Ueyama }
1338861021f9SRui Ueyama 
1339861021f9SRui Ueyama void ImportedSymbolRef::moveNext() {
1340861021f9SRui Ueyama   ++Index;
1341861021f9SRui Ueyama }
1342861021f9SRui Ueyama 
1343861021f9SRui Ueyama std::error_code
1344861021f9SRui Ueyama ImportedSymbolRef::getSymbolName(StringRef &Result) const {
1345861021f9SRui Ueyama   uint32_t RVA;
1346861021f9SRui Ueyama   if (Entry32) {
1347861021f9SRui Ueyama     // If a symbol is imported only by ordinal, it has no name.
1348861021f9SRui Ueyama     if (Entry32[Index].isOrdinal())
13497d099195SRui Ueyama       return std::error_code();
1350861021f9SRui Ueyama     RVA = Entry32[Index].getHintNameRVA();
1351861021f9SRui Ueyama   } else {
1352861021f9SRui Ueyama     if (Entry64[Index].isOrdinal())
13537d099195SRui Ueyama       return std::error_code();
1354861021f9SRui Ueyama     RVA = Entry64[Index].getHintNameRVA();
1355861021f9SRui Ueyama   }
1356861021f9SRui Ueyama   uintptr_t IntPtr = 0;
1357861021f9SRui Ueyama   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1358861021f9SRui Ueyama     return EC;
1359861021f9SRui Ueyama   // +2 because the first two bytes is hint.
1360861021f9SRui Ueyama   Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
13617d099195SRui Ueyama   return std::error_code();
1362861021f9SRui Ueyama }
1363861021f9SRui Ueyama 
1364861021f9SRui Ueyama std::error_code ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
1365861021f9SRui Ueyama   uint32_t RVA;
1366861021f9SRui Ueyama   if (Entry32) {
1367861021f9SRui Ueyama     if (Entry32[Index].isOrdinal()) {
1368861021f9SRui Ueyama       Result = Entry32[Index].getOrdinal();
13697d099195SRui Ueyama       return std::error_code();
1370861021f9SRui Ueyama     }
1371861021f9SRui Ueyama     RVA = Entry32[Index].getHintNameRVA();
1372861021f9SRui Ueyama   } else {
1373861021f9SRui Ueyama     if (Entry64[Index].isOrdinal()) {
1374861021f9SRui Ueyama       Result = Entry64[Index].getOrdinal();
13757d099195SRui Ueyama       return std::error_code();
1376861021f9SRui Ueyama     }
1377861021f9SRui Ueyama     RVA = Entry64[Index].getHintNameRVA();
1378861021f9SRui Ueyama   }
1379861021f9SRui Ueyama   uintptr_t IntPtr = 0;
1380861021f9SRui Ueyama   if (std::error_code EC = OwningObject->getRvaPtr(RVA, IntPtr))
1381861021f9SRui Ueyama     return EC;
1382861021f9SRui Ueyama   Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
13837d099195SRui Ueyama   return std::error_code();
1384861021f9SRui Ueyama }
1385861021f9SRui Ueyama 
1386437b0d58SRafael Espindola ErrorOr<std::unique_ptr<COFFObjectFile>>
138748af1c2aSRafael Espindola ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1388db4ed0bdSRafael Espindola   std::error_code EC;
138948af1c2aSRafael Espindola   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1390692410efSRafael Espindola   if (EC)
1391692410efSRafael Espindola     return EC;
1392437b0d58SRafael Espindola   return std::move(Ret);
1393686738e2SRui Ueyama }
139474e85130SRui Ueyama 
139574e85130SRui Ueyama bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
139674e85130SRui Ueyama   return Header == Other.Header && Index == Other.Index;
139774e85130SRui Ueyama }
139874e85130SRui Ueyama 
139974e85130SRui Ueyama void BaseRelocRef::moveNext() {
140074e85130SRui Ueyama   // Header->BlockSize is the size of the current block, including the
140174e85130SRui Ueyama   // size of the header itself.
140274e85130SRui Ueyama   uint32_t Size = sizeof(*Header) +
1403970dda29SRui Ueyama       sizeof(coff_base_reloc_block_entry) * (Index + 1);
140474e85130SRui Ueyama   if (Size == Header->BlockSize) {
140574e85130SRui Ueyama     // .reloc contains a list of base relocation blocks. Each block
140674e85130SRui Ueyama     // consists of the header followed by entries. The header contains
140774e85130SRui Ueyama     // how many entories will follow. When we reach the end of the
140874e85130SRui Ueyama     // current block, proceed to the next block.
140974e85130SRui Ueyama     Header = reinterpret_cast<const coff_base_reloc_block_header *>(
141074e85130SRui Ueyama         reinterpret_cast<const uint8_t *>(Header) + Size);
141174e85130SRui Ueyama     Index = 0;
141274e85130SRui Ueyama   } else {
141374e85130SRui Ueyama     ++Index;
141474e85130SRui Ueyama   }
141574e85130SRui Ueyama }
141674e85130SRui Ueyama 
141774e85130SRui Ueyama std::error_code BaseRelocRef::getType(uint8_t &Type) const {
141874e85130SRui Ueyama   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
141974e85130SRui Ueyama   Type = Entry[Index].getType();
14207d099195SRui Ueyama   return std::error_code();
142174e85130SRui Ueyama }
142274e85130SRui Ueyama 
142374e85130SRui Ueyama std::error_code BaseRelocRef::getRVA(uint32_t &Result) const {
142474e85130SRui Ueyama   auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
142574e85130SRui Ueyama   Result = Header->PageRVA + Entry[Index].getOffset();
14267d099195SRui Ueyama   return std::error_code();
142774e85130SRui Ueyama }
1428