COFFObjectFile.cpp 48 KB

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