COFFObjectFile.cpp 49 KB

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