COFFObjectFile.cpp 50 KB

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