COFFObjectFile.cpp 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955
  1. //===- COFFObjectFile.cpp - COFF object file implementation ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file declares the COFFObjectFile class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/ArrayRef.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/ADT/StringSwitch.h"
  15. #include "llvm/ADT/Triple.h"
  16. #include "llvm/ADT/iterator_range.h"
  17. #include "llvm/BinaryFormat/COFF.h"
  18. #include "llvm/Object/Binary.h"
  19. #include "llvm/Object/COFF.h"
  20. #include "llvm/Object/Error.h"
  21. #include "llvm/Object/ObjectFile.h"
  22. #include "llvm/Support/BinaryStreamReader.h"
  23. #include "llvm/Support/Endian.h"
  24. #include "llvm/Support/Error.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/MathExtras.h"
  27. #include "llvm/Support/MemoryBufferRef.h"
  28. #include <algorithm>
  29. #include <cassert>
  30. #include <cinttypes>
  31. #include <cstddef>
  32. #include <cstring>
  33. #include <limits>
  34. #include <memory>
  35. #include <system_error>
  36. using namespace llvm;
  37. using namespace object;
  38. using support::ulittle16_t;
  39. using support::ulittle32_t;
  40. using support::ulittle64_t;
  41. using support::little16_t;
  42. // Returns false if size is greater than the buffer size. And sets ec.
  43. static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
  44. if (M.getBufferSize() < Size) {
  45. EC = object_error::unexpected_eof;
  46. return false;
  47. }
  48. return true;
  49. }
  50. // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
  51. // Returns unexpected_eof if error.
  52. template <typename T>
  53. static Error getObject(const T *&Obj, MemoryBufferRef M, const void *Ptr,
  54. const uint64_t Size = sizeof(T)) {
  55. uintptr_t Addr = reinterpret_cast<uintptr_t>(Ptr);
  56. if (Error E = Binary::checkOffset(M, Addr, Size))
  57. return E;
  58. Obj = reinterpret_cast<const T *>(Addr);
  59. return Error::success();
  60. }
  61. // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
  62. // prefixed slashes.
  63. static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
  64. assert(Str.size() <= 6 && "String too long, possible overflow.");
  65. if (Str.size() > 6)
  66. return true;
  67. uint64_t Value = 0;
  68. while (!Str.empty()) {
  69. unsigned CharVal;
  70. if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
  71. CharVal = Str[0] - 'A';
  72. else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
  73. CharVal = Str[0] - 'a' + 26;
  74. else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
  75. CharVal = Str[0] - '0' + 52;
  76. else if (Str[0] == '+') // 62
  77. CharVal = 62;
  78. else if (Str[0] == '/') // 63
  79. CharVal = 63;
  80. else
  81. return true;
  82. Value = (Value * 64) + CharVal;
  83. Str = Str.substr(1);
  84. }
  85. if (Value > std::numeric_limits<uint32_t>::max())
  86. return true;
  87. Result = static_cast<uint32_t>(Value);
  88. return false;
  89. }
  90. template <typename coff_symbol_type>
  91. const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
  92. const coff_symbol_type *Addr =
  93. reinterpret_cast<const coff_symbol_type *>(Ref.p);
  94. assert(!checkOffset(Data, reinterpret_cast<uintptr_t>(Addr), sizeof(*Addr)));
  95. #ifndef NDEBUG
  96. // Verify that the symbol points to a valid entry in the symbol table.
  97. uintptr_t Offset =
  98. reinterpret_cast<uintptr_t>(Addr) - reinterpret_cast<uintptr_t>(base());
  99. assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
  100. "Symbol did not point to the beginning of a symbol");
  101. #endif
  102. return Addr;
  103. }
  104. const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
  105. const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
  106. #ifndef NDEBUG
  107. // Verify that the section points to a valid entry in the section table.
  108. if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
  109. report_fatal_error("Section was outside of section table.");
  110. uintptr_t Offset = reinterpret_cast<uintptr_t>(Addr) -
  111. reinterpret_cast<uintptr_t>(SectionTable);
  112. assert(Offset % sizeof(coff_section) == 0 &&
  113. "Section did not point to the beginning of a section");
  114. #endif
  115. return Addr;
  116. }
  117. void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
  118. auto End = reinterpret_cast<uintptr_t>(StringTable);
  119. if (SymbolTable16) {
  120. const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
  121. Symb += 1 + Symb->NumberOfAuxSymbols;
  122. Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
  123. } else if (SymbolTable32) {
  124. const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
  125. Symb += 1 + Symb->NumberOfAuxSymbols;
  126. Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
  127. } else {
  128. llvm_unreachable("no symbol table pointer!");
  129. }
  130. }
  131. Expected<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
  132. return getSymbolName(getCOFFSymbol(Ref));
  133. }
  134. uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const {
  135. return getCOFFSymbol(Ref).getValue();
  136. }
  137. uint32_t COFFObjectFile::getSymbolAlignment(DataRefImpl Ref) const {
  138. // MSVC/link.exe seems to align symbols to the next-power-of-2
  139. // up to 32 bytes.
  140. COFFSymbolRef Symb = getCOFFSymbol(Ref);
  141. return std::min(uint64_t(32), PowerOf2Ceil(Symb.getValue()));
  142. }
  143. Expected<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
  144. uint64_t Result = cantFail(getSymbolValue(Ref));
  145. COFFSymbolRef Symb = getCOFFSymbol(Ref);
  146. int32_t SectionNumber = Symb.getSectionNumber();
  147. if (Symb.isAnyUndefined() || Symb.isCommon() ||
  148. COFF::isReservedSectionNumber(SectionNumber))
  149. return Result;
  150. Expected<const coff_section *> Section = getSection(SectionNumber);
  151. if (!Section)
  152. return Section.takeError();
  153. Result += (*Section)->VirtualAddress;
  154. // The section VirtualAddress does not include ImageBase, and we want to
  155. // return virtual addresses.
  156. Result += getImageBase();
  157. return Result;
  158. }
  159. Expected<SymbolRef::Type> COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
  160. COFFSymbolRef Symb = getCOFFSymbol(Ref);
  161. int32_t SectionNumber = Symb.getSectionNumber();
  162. if (Symb.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION)
  163. return SymbolRef::ST_Function;
  164. if (Symb.isAnyUndefined())
  165. return SymbolRef::ST_Unknown;
  166. if (Symb.isCommon())
  167. return SymbolRef::ST_Data;
  168. if (Symb.isFileRecord())
  169. return SymbolRef::ST_File;
  170. // TODO: perhaps we need a new symbol type ST_Section.
  171. if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
  172. return SymbolRef::ST_Debug;
  173. if (!COFF::isReservedSectionNumber(SectionNumber))
  174. return SymbolRef::ST_Data;
  175. return SymbolRef::ST_Other;
  176. }
  177. Expected<uint32_t> COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
  178. COFFSymbolRef Symb = getCOFFSymbol(Ref);
  179. uint32_t Result = SymbolRef::SF_None;
  180. if (Symb.isExternal() || Symb.isWeakExternal())
  181. Result |= SymbolRef::SF_Global;
  182. if (const coff_aux_weak_external *AWE = Symb.getWeakExternal()) {
  183. Result |= SymbolRef::SF_Weak;
  184. if (AWE->Characteristics != COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS)
  185. Result |= SymbolRef::SF_Undefined;
  186. }
  187. if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
  188. Result |= SymbolRef::SF_Absolute;
  189. if (Symb.isFileRecord())
  190. Result |= SymbolRef::SF_FormatSpecific;
  191. if (Symb.isSectionDefinition())
  192. Result |= SymbolRef::SF_FormatSpecific;
  193. if (Symb.isCommon())
  194. Result |= SymbolRef::SF_Common;
  195. if (Symb.isUndefined())
  196. Result |= SymbolRef::SF_Undefined;
  197. return Result;
  198. }
  199. uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
  200. COFFSymbolRef Symb = getCOFFSymbol(Ref);
  201. return Symb.getValue();
  202. }
  203. Expected<section_iterator>
  204. COFFObjectFile::getSymbolSection(DataRefImpl Ref) const {
  205. COFFSymbolRef Symb = getCOFFSymbol(Ref);
  206. if (COFF::isReservedSectionNumber(Symb.getSectionNumber()))
  207. return section_end();
  208. Expected<const coff_section *> Sec = getSection(Symb.getSectionNumber());
  209. if (!Sec)
  210. return Sec.takeError();
  211. DataRefImpl Ret;
  212. Ret.p = reinterpret_cast<uintptr_t>(*Sec);
  213. return section_iterator(SectionRef(Ret, this));
  214. }
  215. unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
  216. COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
  217. return Symb.getSectionNumber();
  218. }
  219. void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
  220. const coff_section *Sec = toSec(Ref);
  221. Sec += 1;
  222. Ref.p = reinterpret_cast<uintptr_t>(Sec);
  223. }
  224. Expected<StringRef> COFFObjectFile::getSectionName(DataRefImpl Ref) const {
  225. const coff_section *Sec = toSec(Ref);
  226. return getSectionName(Sec);
  227. }
  228. uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
  229. const coff_section *Sec = toSec(Ref);
  230. uint64_t Result = Sec->VirtualAddress;
  231. // The section VirtualAddress does not include ImageBase, and we want to
  232. // return virtual addresses.
  233. Result += getImageBase();
  234. return Result;
  235. }
  236. uint64_t COFFObjectFile::getSectionIndex(DataRefImpl Sec) const {
  237. return toSec(Sec) - SectionTable;
  238. }
  239. uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
  240. return getSectionSize(toSec(Ref));
  241. }
  242. Expected<ArrayRef<uint8_t>>
  243. COFFObjectFile::getSectionContents(DataRefImpl Ref) const {
  244. const coff_section *Sec = toSec(Ref);
  245. ArrayRef<uint8_t> Res;
  246. if (Error E = getSectionContents(Sec, Res))
  247. return std::move(E);
  248. return Res;
  249. }
  250. uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
  251. const coff_section *Sec = toSec(Ref);
  252. return Sec->getAlignment();
  253. }
  254. bool COFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
  255. return false;
  256. }
  257. bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
  258. const coff_section *Sec = toSec(Ref);
  259. return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
  260. }
  261. bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
  262. const coff_section *Sec = toSec(Ref);
  263. return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
  264. }
  265. bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
  266. const coff_section *Sec = toSec(Ref);
  267. const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
  268. COFF::IMAGE_SCN_MEM_READ |
  269. COFF::IMAGE_SCN_MEM_WRITE;
  270. return (Sec->Characteristics & BssFlags) == BssFlags;
  271. }
  272. // The .debug sections are the only debug sections for COFF
  273. // (\see MCObjectFileInfo.cpp).
  274. bool COFFObjectFile::isDebugSection(DataRefImpl Ref) const {
  275. Expected<StringRef> SectionNameOrErr = getSectionName(Ref);
  276. if (!SectionNameOrErr) {
  277. // TODO: Report the error message properly.
  278. consumeError(SectionNameOrErr.takeError());
  279. return false;
  280. }
  281. StringRef SectionName = SectionNameOrErr.get();
  282. return SectionName.startswith(".debug");
  283. }
  284. unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
  285. uintptr_t Offset =
  286. Sec.getRawDataRefImpl().p - reinterpret_cast<uintptr_t>(SectionTable);
  287. assert((Offset % sizeof(coff_section)) == 0);
  288. return (Offset / sizeof(coff_section)) + 1;
  289. }
  290. bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
  291. const coff_section *Sec = toSec(Ref);
  292. // In COFF, a virtual section won't have any in-file
  293. // content, so the file pointer to the content will be zero.
  294. return Sec->PointerToRawData == 0;
  295. }
  296. static uint32_t getNumberOfRelocations(const coff_section *Sec,
  297. MemoryBufferRef M, const uint8_t *base) {
  298. // The field for the number of relocations in COFF section table is only
  299. // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
  300. // NumberOfRelocations field, and the actual relocation count is stored in the
  301. // VirtualAddress field in the first relocation entry.
  302. if (Sec->hasExtendedRelocations()) {
  303. const coff_relocation *FirstReloc;
  304. if (Error E = getObject(FirstReloc, M,
  305. reinterpret_cast<const coff_relocation *>(
  306. base + Sec->PointerToRelocations))) {
  307. consumeError(std::move(E));
  308. return 0;
  309. }
  310. // -1 to exclude this first relocation entry.
  311. return FirstReloc->VirtualAddress - 1;
  312. }
  313. return Sec->NumberOfRelocations;
  314. }
  315. static const coff_relocation *
  316. getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
  317. uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
  318. if (!NumRelocs)
  319. return nullptr;
  320. auto begin = reinterpret_cast<const coff_relocation *>(
  321. Base + Sec->PointerToRelocations);
  322. if (Sec->hasExtendedRelocations()) {
  323. // Skip the first relocation entry repurposed to store the number of
  324. // relocations.
  325. begin++;
  326. }
  327. if (auto E = Binary::checkOffset(M, reinterpret_cast<uintptr_t>(begin),
  328. sizeof(coff_relocation) * NumRelocs)) {
  329. consumeError(std::move(E));
  330. return nullptr;
  331. }
  332. return begin;
  333. }
  334. relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
  335. const coff_section *Sec = toSec(Ref);
  336. const coff_relocation *begin = getFirstReloc(Sec, Data, base());
  337. if (begin && Sec->VirtualAddress != 0)
  338. report_fatal_error("Sections with relocations should have an address of 0");
  339. DataRefImpl Ret;
  340. Ret.p = reinterpret_cast<uintptr_t>(begin);
  341. return relocation_iterator(RelocationRef(Ret, this));
  342. }
  343. relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
  344. const coff_section *Sec = toSec(Ref);
  345. const coff_relocation *I = getFirstReloc(Sec, Data, base());
  346. if (I)
  347. I += getNumberOfRelocations(Sec, Data, base());
  348. DataRefImpl Ret;
  349. Ret.p = reinterpret_cast<uintptr_t>(I);
  350. return relocation_iterator(RelocationRef(Ret, this));
  351. }
  352. // Initialize the pointer to the symbol table.
  353. Error COFFObjectFile::initSymbolTablePtr() {
  354. if (COFFHeader)
  355. if (Error E = getObject(
  356. SymbolTable16, Data, base() + getPointerToSymbolTable(),
  357. (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
  358. return E;
  359. if (COFFBigObjHeader)
  360. if (Error E = getObject(
  361. SymbolTable32, Data, base() + getPointerToSymbolTable(),
  362. (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
  363. return E;
  364. // Find string table. The first four byte of the string table contains the
  365. // total size of the string table, including the size field itself. If the
  366. // string table is empty, the value of the first four byte would be 4.
  367. uint32_t StringTableOffset = getPointerToSymbolTable() +
  368. getNumberOfSymbols() * getSymbolTableEntrySize();
  369. const uint8_t *StringTableAddr = base() + StringTableOffset;
  370. const ulittle32_t *StringTableSizePtr;
  371. if (Error E = getObject(StringTableSizePtr, Data, StringTableAddr))
  372. return E;
  373. StringTableSize = *StringTableSizePtr;
  374. if (Error E = getObject(StringTable, Data, StringTableAddr, StringTableSize))
  375. return E;
  376. // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
  377. // tools like cvtres write a size of 0 for an empty table instead of 4.
  378. if (StringTableSize < 4)
  379. StringTableSize = 4;
  380. // Check that the string table is null terminated if has any in it.
  381. if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
  382. return createStringError(object_error::parse_failed,
  383. "string table missing null terminator");
  384. return Error::success();
  385. }
  386. uint64_t COFFObjectFile::getImageBase() const {
  387. if (PE32Header)
  388. return PE32Header->ImageBase;
  389. else if (PE32PlusHeader)
  390. return PE32PlusHeader->ImageBase;
  391. // This actually comes up in practice.
  392. return 0;
  393. }
  394. // Returns the file offset for the given VA.
  395. Error COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
  396. uint64_t ImageBase = getImageBase();
  397. uint64_t Rva = Addr - ImageBase;
  398. assert(Rva <= UINT32_MAX);
  399. return getRvaPtr((uint32_t)Rva, Res);
  400. }
  401. // Returns the file offset for the given RVA.
  402. Error COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res,
  403. const char *ErrorContext) const {
  404. for (const SectionRef &S : sections()) {
  405. const coff_section *Section = getCOFFSection(S);
  406. uint32_t SectionStart = Section->VirtualAddress;
  407. uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
  408. if (SectionStart <= Addr && Addr < SectionEnd) {
  409. // A table/directory entry can be pointing to somewhere in a stripped
  410. // section, in an object that went through `objcopy --only-keep-debug`.
  411. // In this case we don't want to cause the parsing of the object file to
  412. // fail, otherwise it will be impossible to use this object as debug info
  413. // in LLDB. Return SectionStrippedError here so that
  414. // COFFObjectFile::initialize can ignore the error.
  415. // Somewhat common binaries may have RVAs pointing outside of the
  416. // provided raw data. Instead of rejecting the binaries, just
  417. // treat the section as stripped for these purposes.
  418. if (Section->SizeOfRawData < Section->VirtualSize &&
  419. Addr >= SectionStart + Section->SizeOfRawData) {
  420. return make_error<SectionStrippedError>();
  421. }
  422. uint32_t Offset = Addr - SectionStart;
  423. Res = reinterpret_cast<uintptr_t>(base()) + Section->PointerToRawData +
  424. Offset;
  425. return Error::success();
  426. }
  427. }
  428. if (ErrorContext)
  429. return createStringError(object_error::parse_failed,
  430. "RVA 0x%" PRIx32 " for %s not found", Addr,
  431. ErrorContext);
  432. return createStringError(object_error::parse_failed,
  433. "RVA 0x%" PRIx32 " not found", Addr);
  434. }
  435. Error COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
  436. ArrayRef<uint8_t> &Contents,
  437. const char *ErrorContext) const {
  438. for (const SectionRef &S : sections()) {
  439. const coff_section *Section = getCOFFSection(S);
  440. uint32_t SectionStart = Section->VirtualAddress;
  441. // Check if this RVA is within the section bounds. Be careful about integer
  442. // overflow.
  443. uint32_t OffsetIntoSection = RVA - SectionStart;
  444. if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize &&
  445. Size <= Section->VirtualSize - OffsetIntoSection) {
  446. uintptr_t Begin = reinterpret_cast<uintptr_t>(base()) +
  447. Section->PointerToRawData + OffsetIntoSection;
  448. Contents =
  449. ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size);
  450. return Error::success();
  451. }
  452. }
  453. if (ErrorContext)
  454. return createStringError(object_error::parse_failed,
  455. "RVA 0x%" PRIx32 " for %s not found", RVA,
  456. ErrorContext);
  457. return createStringError(object_error::parse_failed,
  458. "RVA 0x%" PRIx32 " not found", RVA);
  459. }
  460. // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
  461. // table entry.
  462. Error COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
  463. StringRef &Name) const {
  464. uintptr_t IntPtr = 0;
  465. if (Error E = getRvaPtr(Rva, IntPtr))
  466. return E;
  467. const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
  468. Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
  469. Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
  470. return Error::success();
  471. }
  472. Error COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir,
  473. const codeview::DebugInfo *&PDBInfo,
  474. StringRef &PDBFileName) const {
  475. ArrayRef<uint8_t> InfoBytes;
  476. if (Error E =
  477. getRvaAndSizeAsBytes(DebugDir->AddressOfRawData, DebugDir->SizeOfData,
  478. InfoBytes, "PDB info"))
  479. return E;
  480. if (InfoBytes.size() < sizeof(*PDBInfo) + 1)
  481. return createStringError(object_error::parse_failed, "PDB info too small");
  482. PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data());
  483. InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo));
  484. PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()),
  485. InfoBytes.size());
  486. // Truncate the name at the first null byte. Ignore any padding.
  487. PDBFileName = PDBFileName.split('\0').first;
  488. return Error::success();
  489. }
  490. Error COFFObjectFile::getDebugPDBInfo(const codeview::DebugInfo *&PDBInfo,
  491. StringRef &PDBFileName) const {
  492. for (const debug_directory &D : debug_directories())
  493. if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW)
  494. return getDebugPDBInfo(&D, PDBInfo, PDBFileName);
  495. // If we get here, there is no PDB info to return.
  496. PDBInfo = nullptr;
  497. PDBFileName = StringRef();
  498. return Error::success();
  499. }
  500. // Find the import table.
  501. Error COFFObjectFile::initImportTablePtr() {
  502. // First, we get the RVA of the import table. If the file lacks a pointer to
  503. // the import table, do nothing.
  504. const data_directory *DataEntry = getDataDirectory(COFF::IMPORT_TABLE);
  505. if (!DataEntry)
  506. return Error::success();
  507. // Do nothing if the pointer to import table is NULL.
  508. if (DataEntry->RelativeVirtualAddress == 0)
  509. return Error::success();
  510. uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
  511. // Find the section that contains the RVA. This is needed because the RVA is
  512. // the import table's memory address which is different from its file offset.
  513. uintptr_t IntPtr = 0;
  514. if (Error E = getRvaPtr(ImportTableRva, IntPtr, "import table"))
  515. return E;
  516. if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
  517. return E;
  518. ImportDirectory = reinterpret_cast<
  519. const coff_import_directory_table_entry *>(IntPtr);
  520. return Error::success();
  521. }
  522. // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
  523. Error COFFObjectFile::initDelayImportTablePtr() {
  524. const data_directory *DataEntry =
  525. getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR);
  526. if (!DataEntry)
  527. return Error::success();
  528. if (DataEntry->RelativeVirtualAddress == 0)
  529. return Error::success();
  530. uint32_t RVA = DataEntry->RelativeVirtualAddress;
  531. NumberOfDelayImportDirectory = DataEntry->Size /
  532. sizeof(delay_import_directory_table_entry) - 1;
  533. uintptr_t IntPtr = 0;
  534. if (Error E = getRvaPtr(RVA, IntPtr, "delay import table"))
  535. return E;
  536. if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
  537. return E;
  538. DelayImportDirectory = reinterpret_cast<
  539. const delay_import_directory_table_entry *>(IntPtr);
  540. return Error::success();
  541. }
  542. // Find the export table.
  543. Error COFFObjectFile::initExportTablePtr() {
  544. // First, we get the RVA of the export table. If the file lacks a pointer to
  545. // the export table, do nothing.
  546. const data_directory *DataEntry = getDataDirectory(COFF::EXPORT_TABLE);
  547. if (!DataEntry)
  548. return Error::success();
  549. // Do nothing if the pointer to export table is NULL.
  550. if (DataEntry->RelativeVirtualAddress == 0)
  551. return Error::success();
  552. uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
  553. uintptr_t IntPtr = 0;
  554. if (Error E = getRvaPtr(ExportTableRva, IntPtr, "export table"))
  555. return E;
  556. if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
  557. return E;
  558. ExportDirectory =
  559. reinterpret_cast<const export_directory_table_entry *>(IntPtr);
  560. return Error::success();
  561. }
  562. Error COFFObjectFile::initBaseRelocPtr() {
  563. const data_directory *DataEntry =
  564. getDataDirectory(COFF::BASE_RELOCATION_TABLE);
  565. if (!DataEntry)
  566. return Error::success();
  567. if (DataEntry->RelativeVirtualAddress == 0)
  568. return Error::success();
  569. uintptr_t IntPtr = 0;
  570. if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr,
  571. "base reloc table"))
  572. return E;
  573. if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
  574. return E;
  575. BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
  576. IntPtr);
  577. BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
  578. IntPtr + DataEntry->Size);
  579. // FIXME: Verify the section containing BaseRelocHeader has at least
  580. // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress.
  581. return Error::success();
  582. }
  583. Error COFFObjectFile::initDebugDirectoryPtr() {
  584. // Get the RVA of the debug directory. Do nothing if it does not exist.
  585. const data_directory *DataEntry = getDataDirectory(COFF::DEBUG_DIRECTORY);
  586. if (!DataEntry)
  587. return Error::success();
  588. // Do nothing if the RVA is NULL.
  589. if (DataEntry->RelativeVirtualAddress == 0)
  590. return Error::success();
  591. // Check that the size is a multiple of the entry size.
  592. if (DataEntry->Size % sizeof(debug_directory) != 0)
  593. return createStringError(object_error::parse_failed,
  594. "debug directory has uneven size");
  595. uintptr_t IntPtr = 0;
  596. if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr,
  597. "debug directory"))
  598. return E;
  599. if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
  600. return E;
  601. DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
  602. DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(
  603. IntPtr + DataEntry->Size);
  604. // FIXME: Verify the section containing DebugDirectoryBegin has at least
  605. // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress.
  606. return Error::success();
  607. }
  608. Error COFFObjectFile::initTLSDirectoryPtr() {
  609. // Get the RVA of the TLS directory. Do nothing if it does not exist.
  610. const data_directory *DataEntry = getDataDirectory(COFF::TLS_TABLE);
  611. if (!DataEntry)
  612. return Error::success();
  613. // Do nothing if the RVA is NULL.
  614. if (DataEntry->RelativeVirtualAddress == 0)
  615. return Error::success();
  616. uint64_t DirSize =
  617. is64() ? sizeof(coff_tls_directory64) : sizeof(coff_tls_directory32);
  618. // Check that the size is correct.
  619. if (DataEntry->Size != DirSize)
  620. return createStringError(
  621. object_error::parse_failed,
  622. "TLS Directory size (%u) is not the expected size (%" PRIu64 ").",
  623. static_cast<uint32_t>(DataEntry->Size), DirSize);
  624. uintptr_t IntPtr = 0;
  625. if (Error E =
  626. getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr, "TLS directory"))
  627. return E;
  628. if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
  629. return E;
  630. if (is64())
  631. TLSDirectory64 = reinterpret_cast<const coff_tls_directory64 *>(IntPtr);
  632. else
  633. TLSDirectory32 = reinterpret_cast<const coff_tls_directory32 *>(IntPtr);
  634. return Error::success();
  635. }
  636. Error COFFObjectFile::initLoadConfigPtr() {
  637. // Get the RVA of the debug directory. Do nothing if it does not exist.
  638. const data_directory *DataEntry = getDataDirectory(COFF::LOAD_CONFIG_TABLE);
  639. if (!DataEntry)
  640. return Error::success();
  641. // Do nothing if the RVA is NULL.
  642. if (DataEntry->RelativeVirtualAddress == 0)
  643. return Error::success();
  644. uintptr_t IntPtr = 0;
  645. if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr,
  646. "load config table"))
  647. return E;
  648. if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
  649. return E;
  650. LoadConfig = (const void *)IntPtr;
  651. return Error::success();
  652. }
  653. Expected<std::unique_ptr<COFFObjectFile>>
  654. COFFObjectFile::create(MemoryBufferRef Object) {
  655. std::unique_ptr<COFFObjectFile> Obj(new COFFObjectFile(std::move(Object)));
  656. if (Error E = Obj->initialize())
  657. return std::move(E);
  658. return std::move(Obj);
  659. }
  660. COFFObjectFile::COFFObjectFile(MemoryBufferRef Object)
  661. : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
  662. COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
  663. DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
  664. SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
  665. ImportDirectory(nullptr), DelayImportDirectory(nullptr),
  666. NumberOfDelayImportDirectory(0), ExportDirectory(nullptr),
  667. BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
  668. DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr),
  669. TLSDirectory32(nullptr), TLSDirectory64(nullptr) {}
  670. static Error ignoreStrippedErrors(Error E) {
  671. if (E.isA<SectionStrippedError>()) {
  672. consumeError(std::move(E));
  673. return Error::success();
  674. }
  675. return E;
  676. }
  677. Error COFFObjectFile::initialize() {
  678. // Check that we at least have enough room for a header.
  679. std::error_code EC;
  680. if (!checkSize(Data, EC, sizeof(coff_file_header)))
  681. return errorCodeToError(EC);
  682. // The current location in the file where we are looking at.
  683. uint64_t CurPtr = 0;
  684. // PE header is optional and is present only in executables. If it exists,
  685. // it is placed right after COFF header.
  686. bool HasPEHeader = false;
  687. // Check if this is a PE/COFF file.
  688. if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
  689. // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
  690. // PE signature to find 'normal' COFF header.
  691. const auto *DH = reinterpret_cast<const dos_header *>(base());
  692. if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
  693. CurPtr = DH->AddressOfNewExeHeader;
  694. // Check the PE magic bytes. ("PE\0\0")
  695. if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
  696. return createStringError(object_error::parse_failed,
  697. "incorrect PE magic");
  698. }
  699. CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
  700. HasPEHeader = true;
  701. }
  702. }
  703. if (Error E = getObject(COFFHeader, Data, base() + CurPtr))
  704. return E;
  705. // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
  706. // import libraries share a common prefix but bigobj is more restrictive.
  707. if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
  708. COFFHeader->NumberOfSections == uint16_t(0xffff) &&
  709. checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
  710. if (Error E = getObject(COFFBigObjHeader, Data, base() + CurPtr))
  711. return E;
  712. // Verify that we are dealing with bigobj.
  713. if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
  714. std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
  715. sizeof(COFF::BigObjMagic)) == 0) {
  716. COFFHeader = nullptr;
  717. CurPtr += sizeof(coff_bigobj_file_header);
  718. } else {
  719. // It's not a bigobj.
  720. COFFBigObjHeader = nullptr;
  721. }
  722. }
  723. if (COFFHeader) {
  724. // The prior checkSize call may have failed. This isn't a hard error
  725. // because we were just trying to sniff out bigobj.
  726. EC = std::error_code();
  727. CurPtr += sizeof(coff_file_header);
  728. if (COFFHeader->isImportLibrary())
  729. return errorCodeToError(EC);
  730. }
  731. if (HasPEHeader) {
  732. const pe32_header *Header;
  733. if (Error E = getObject(Header, Data, base() + CurPtr))
  734. return E;
  735. const uint8_t *DataDirAddr;
  736. uint64_t DataDirSize;
  737. if (Header->Magic == COFF::PE32Header::PE32) {
  738. PE32Header = Header;
  739. DataDirAddr = base() + CurPtr + sizeof(pe32_header);
  740. DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
  741. } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
  742. PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
  743. DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
  744. DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
  745. } else {
  746. // It's neither PE32 nor PE32+.
  747. return createStringError(object_error::parse_failed,
  748. "incorrect PE magic");
  749. }
  750. if (Error E = getObject(DataDirectory, Data, DataDirAddr, DataDirSize))
  751. return E;
  752. }
  753. if (COFFHeader)
  754. CurPtr += COFFHeader->SizeOfOptionalHeader;
  755. assert(COFFHeader || COFFBigObjHeader);
  756. if (Error E =
  757. getObject(SectionTable, Data, base() + CurPtr,
  758. (uint64_t)getNumberOfSections() * sizeof(coff_section)))
  759. return E;
  760. // Initialize the pointer to the symbol table.
  761. if (getPointerToSymbolTable() != 0) {
  762. if (Error E = initSymbolTablePtr()) {
  763. // Recover from errors reading the symbol table.
  764. consumeError(std::move(E));
  765. SymbolTable16 = nullptr;
  766. SymbolTable32 = nullptr;
  767. StringTable = nullptr;
  768. StringTableSize = 0;
  769. }
  770. } else {
  771. // We had better not have any symbols if we don't have a symbol table.
  772. if (getNumberOfSymbols() != 0) {
  773. return createStringError(object_error::parse_failed,
  774. "symbol table missing");
  775. }
  776. }
  777. // Initialize the pointer to the beginning of the import table.
  778. if (Error E = ignoreStrippedErrors(initImportTablePtr()))
  779. return E;
  780. if (Error E = ignoreStrippedErrors(initDelayImportTablePtr()))
  781. return E;
  782. // Initialize the pointer to the export table.
  783. if (Error E = ignoreStrippedErrors(initExportTablePtr()))
  784. return E;
  785. // Initialize the pointer to the base relocation table.
  786. if (Error E = ignoreStrippedErrors(initBaseRelocPtr()))
  787. return E;
  788. // Initialize the pointer to the debug directory.
  789. if (Error E = ignoreStrippedErrors(initDebugDirectoryPtr()))
  790. return E;
  791. // Initialize the pointer to the TLS directory.
  792. if (Error E = ignoreStrippedErrors(initTLSDirectoryPtr()))
  793. return E;
  794. if (Error E = ignoreStrippedErrors(initLoadConfigPtr()))
  795. return E;
  796. return Error::success();
  797. }
  798. basic_symbol_iterator COFFObjectFile::symbol_begin() const {
  799. DataRefImpl Ret;
  800. Ret.p = getSymbolTable();
  801. return basic_symbol_iterator(SymbolRef(Ret, this));
  802. }
  803. basic_symbol_iterator COFFObjectFile::symbol_end() const {
  804. // The symbol table ends where the string table begins.
  805. DataRefImpl Ret;
  806. Ret.p = reinterpret_cast<uintptr_t>(StringTable);
  807. return basic_symbol_iterator(SymbolRef(Ret, this));
  808. }
  809. import_directory_iterator COFFObjectFile::import_directory_begin() const {
  810. if (!ImportDirectory)
  811. return import_directory_end();
  812. if (ImportDirectory->isNull())
  813. return import_directory_end();
  814. return import_directory_iterator(
  815. ImportDirectoryEntryRef(ImportDirectory, 0, this));
  816. }
  817. import_directory_iterator COFFObjectFile::import_directory_end() const {
  818. return import_directory_iterator(
  819. ImportDirectoryEntryRef(nullptr, -1, this));
  820. }
  821. delay_import_directory_iterator
  822. COFFObjectFile::delay_import_directory_begin() const {
  823. return delay_import_directory_iterator(
  824. DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
  825. }
  826. delay_import_directory_iterator
  827. COFFObjectFile::delay_import_directory_end() const {
  828. return delay_import_directory_iterator(
  829. DelayImportDirectoryEntryRef(
  830. DelayImportDirectory, NumberOfDelayImportDirectory, this));
  831. }
  832. export_directory_iterator COFFObjectFile::export_directory_begin() const {
  833. return export_directory_iterator(
  834. ExportDirectoryEntryRef(ExportDirectory, 0, this));
  835. }
  836. export_directory_iterator COFFObjectFile::export_directory_end() const {
  837. if (!ExportDirectory)
  838. return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
  839. ExportDirectoryEntryRef Ref(ExportDirectory,
  840. ExportDirectory->AddressTableEntries, this);
  841. return export_directory_iterator(Ref);
  842. }
  843. section_iterator COFFObjectFile::section_begin() const {
  844. DataRefImpl Ret;
  845. Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
  846. return section_iterator(SectionRef(Ret, this));
  847. }
  848. section_iterator COFFObjectFile::section_end() const {
  849. DataRefImpl Ret;
  850. int NumSections =
  851. COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
  852. Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
  853. return section_iterator(SectionRef(Ret, this));
  854. }
  855. base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
  856. return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
  857. }
  858. base_reloc_iterator COFFObjectFile::base_reloc_end() const {
  859. return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
  860. }
  861. uint8_t COFFObjectFile::getBytesInAddress() const {
  862. return getArch() == Triple::x86_64 || getArch() == Triple::aarch64 ? 8 : 4;
  863. }
  864. StringRef COFFObjectFile::getFileFormatName() const {
  865. switch(getMachine()) {
  866. case COFF::IMAGE_FILE_MACHINE_I386:
  867. return "COFF-i386";
  868. case COFF::IMAGE_FILE_MACHINE_AMD64:
  869. return "COFF-x86-64";
  870. case COFF::IMAGE_FILE_MACHINE_ARMNT:
  871. return "COFF-ARM";
  872. case COFF::IMAGE_FILE_MACHINE_ARM64:
  873. return "COFF-ARM64";
  874. case COFF::IMAGE_FILE_MACHINE_ARM64EC:
  875. return "COFF-ARM64EC";
  876. default:
  877. return "COFF-<unknown arch>";
  878. }
  879. }
  880. Triple::ArchType COFFObjectFile::getArch() const {
  881. switch (getMachine()) {
  882. case COFF::IMAGE_FILE_MACHINE_I386:
  883. return Triple::x86;
  884. case COFF::IMAGE_FILE_MACHINE_AMD64:
  885. return Triple::x86_64;
  886. case COFF::IMAGE_FILE_MACHINE_ARMNT:
  887. return Triple::thumb;
  888. case COFF::IMAGE_FILE_MACHINE_ARM64:
  889. case COFF::IMAGE_FILE_MACHINE_ARM64EC:
  890. return Triple::aarch64;
  891. default:
  892. return Triple::UnknownArch;
  893. }
  894. }
  895. Expected<uint64_t> COFFObjectFile::getStartAddress() const {
  896. if (PE32Header)
  897. return PE32Header->AddressOfEntryPoint;
  898. return 0;
  899. }
  900. iterator_range<import_directory_iterator>
  901. COFFObjectFile::import_directories() const {
  902. return make_range(import_directory_begin(), import_directory_end());
  903. }
  904. iterator_range<delay_import_directory_iterator>
  905. COFFObjectFile::delay_import_directories() const {
  906. return make_range(delay_import_directory_begin(),
  907. delay_import_directory_end());
  908. }
  909. iterator_range<export_directory_iterator>
  910. COFFObjectFile::export_directories() const {
  911. return make_range(export_directory_begin(), export_directory_end());
  912. }
  913. iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
  914. return make_range(base_reloc_begin(), base_reloc_end());
  915. }
  916. const data_directory *COFFObjectFile::getDataDirectory(uint32_t Index) const {
  917. if (!DataDirectory)
  918. return nullptr;
  919. assert(PE32Header || PE32PlusHeader);
  920. uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
  921. : PE32PlusHeader->NumberOfRvaAndSize;
  922. if (Index >= NumEnt)
  923. return nullptr;
  924. return &DataDirectory[Index];
  925. }
  926. Expected<const coff_section *> COFFObjectFile::getSection(int32_t Index) const {
  927. // Perhaps getting the section of a reserved section index should be an error,
  928. // but callers rely on this to return null.
  929. if (COFF::isReservedSectionNumber(Index))
  930. return (const coff_section *)nullptr;
  931. if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
  932. // We already verified the section table data, so no need to check again.
  933. return SectionTable + (Index - 1);
  934. }
  935. return createStringError(object_error::parse_failed,
  936. "section index out of bounds");
  937. }
  938. Expected<StringRef> COFFObjectFile::getString(uint32_t Offset) const {
  939. if (StringTableSize <= 4)
  940. // Tried to get a string from an empty string table.
  941. return createStringError(object_error::parse_failed, "string table empty");
  942. if (Offset >= StringTableSize)
  943. return errorCodeToError(object_error::unexpected_eof);
  944. return StringRef(StringTable + Offset);
  945. }
  946. Expected<StringRef> COFFObjectFile::getSymbolName(COFFSymbolRef Symbol) const {
  947. return getSymbolName(Symbol.getGeneric());
  948. }
  949. Expected<StringRef>
  950. COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol) const {
  951. // Check for string table entry. First 4 bytes are 0.
  952. if (Symbol->Name.Offset.Zeroes == 0)
  953. return getString(Symbol->Name.Offset.Offset);
  954. // Null terminated, let ::strlen figure out the length.
  955. if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
  956. return StringRef(Symbol->Name.ShortName);
  957. // Not null terminated, use all 8 bytes.
  958. return StringRef(Symbol->Name.ShortName, COFF::NameSize);
  959. }
  960. ArrayRef<uint8_t>
  961. COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
  962. const uint8_t *Aux = nullptr;
  963. size_t SymbolSize = getSymbolTableEntrySize();
  964. if (Symbol.getNumberOfAuxSymbols() > 0) {
  965. // AUX data comes immediately after the symbol in COFF
  966. Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
  967. #ifndef NDEBUG
  968. // Verify that the Aux symbol points to a valid entry in the symbol table.
  969. uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
  970. if (Offset < getPointerToSymbolTable() ||
  971. Offset >=
  972. getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
  973. report_fatal_error("Aux Symbol data was outside of symbol table.");
  974. assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
  975. "Aux Symbol data did not point to the beginning of a symbol");
  976. #endif
  977. }
  978. return ArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
  979. }
  980. uint32_t COFFObjectFile::getSymbolIndex(COFFSymbolRef Symbol) const {
  981. uintptr_t Offset =
  982. reinterpret_cast<uintptr_t>(Symbol.getRawPtr()) - getSymbolTable();
  983. assert(Offset % getSymbolTableEntrySize() == 0 &&
  984. "Symbol did not point to the beginning of a symbol");
  985. size_t Index = Offset / getSymbolTableEntrySize();
  986. assert(Index < getNumberOfSymbols());
  987. return Index;
  988. }
  989. Expected<StringRef>
  990. COFFObjectFile::getSectionName(const coff_section *Sec) const {
  991. StringRef Name = StringRef(Sec->Name, COFF::NameSize).split('\0').first;
  992. // Check for string table entry. First byte is '/'.
  993. if (Name.startswith("/")) {
  994. uint32_t Offset;
  995. if (Name.startswith("//")) {
  996. if (decodeBase64StringEntry(Name.substr(2), Offset))
  997. return createStringError(object_error::parse_failed,
  998. "invalid section name");
  999. } else {
  1000. if (Name.substr(1).getAsInteger(10, Offset))
  1001. return createStringError(object_error::parse_failed,
  1002. "invalid section name");
  1003. }
  1004. return getString(Offset);
  1005. }
  1006. return Name;
  1007. }
  1008. uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
  1009. // SizeOfRawData and VirtualSize change what they represent depending on
  1010. // whether or not we have an executable image.
  1011. //
  1012. // For object files, SizeOfRawData contains the size of section's data;
  1013. // VirtualSize should be zero but isn't due to buggy COFF writers.
  1014. //
  1015. // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
  1016. // actual section size is in VirtualSize. It is possible for VirtualSize to
  1017. // be greater than SizeOfRawData; the contents past that point should be
  1018. // considered to be zero.
  1019. if (getDOSHeader())
  1020. return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
  1021. return Sec->SizeOfRawData;
  1022. }
  1023. Error COFFObjectFile::getSectionContents(const coff_section *Sec,
  1024. ArrayRef<uint8_t> &Res) const {
  1025. // In COFF, a virtual section won't have any in-file
  1026. // content, so the file pointer to the content will be zero.
  1027. if (Sec->PointerToRawData == 0)
  1028. return Error::success();
  1029. // The only thing that we need to verify is that the contents is contained
  1030. // within the file bounds. We don't need to make sure it doesn't cover other
  1031. // data, as there's nothing that says that is not allowed.
  1032. uintptr_t ConStart =
  1033. reinterpret_cast<uintptr_t>(base()) + Sec->PointerToRawData;
  1034. uint32_t SectionSize = getSectionSize(Sec);
  1035. if (Error E = checkOffset(Data, ConStart, SectionSize))
  1036. return E;
  1037. Res = ArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
  1038. return Error::success();
  1039. }
  1040. const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
  1041. return reinterpret_cast<const coff_relocation*>(Rel.p);
  1042. }
  1043. void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
  1044. Rel.p = reinterpret_cast<uintptr_t>(
  1045. reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
  1046. }
  1047. uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
  1048. const coff_relocation *R = toRel(Rel);
  1049. return R->VirtualAddress;
  1050. }
  1051. symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
  1052. const coff_relocation *R = toRel(Rel);
  1053. DataRefImpl Ref;
  1054. if (R->SymbolTableIndex >= getNumberOfSymbols())
  1055. return symbol_end();
  1056. if (SymbolTable16)
  1057. Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
  1058. else if (SymbolTable32)
  1059. Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
  1060. else
  1061. llvm_unreachable("no symbol table pointer!");
  1062. return symbol_iterator(SymbolRef(Ref, this));
  1063. }
  1064. uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
  1065. const coff_relocation* R = toRel(Rel);
  1066. return R->Type;
  1067. }
  1068. const coff_section *
  1069. COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
  1070. return toSec(Section.getRawDataRefImpl());
  1071. }
  1072. COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
  1073. if (SymbolTable16)
  1074. return toSymb<coff_symbol16>(Ref);
  1075. if (SymbolTable32)
  1076. return toSymb<coff_symbol32>(Ref);
  1077. llvm_unreachable("no symbol table pointer!");
  1078. }
  1079. COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
  1080. return getCOFFSymbol(Symbol.getRawDataRefImpl());
  1081. }
  1082. const coff_relocation *
  1083. COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
  1084. return toRel(Reloc.getRawDataRefImpl());
  1085. }
  1086. ArrayRef<coff_relocation>
  1087. COFFObjectFile::getRelocations(const coff_section *Sec) const {
  1088. return {getFirstReloc(Sec, Data, base()),
  1089. getNumberOfRelocations(Sec, Data, base())};
  1090. }
  1091. #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
  1092. case COFF::reloc_type: \
  1093. return #reloc_type;
  1094. StringRef COFFObjectFile::getRelocationTypeName(uint16_t Type) const {
  1095. switch (getMachine()) {
  1096. case COFF::IMAGE_FILE_MACHINE_AMD64:
  1097. switch (Type) {
  1098. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
  1099. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
  1100. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
  1101. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
  1102. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
  1103. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
  1104. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
  1105. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
  1106. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
  1107. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
  1108. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
  1109. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
  1110. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
  1111. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
  1112. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
  1113. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
  1114. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
  1115. default:
  1116. return "Unknown";
  1117. }
  1118. break;
  1119. case COFF::IMAGE_FILE_MACHINE_ARMNT:
  1120. switch (Type) {
  1121. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
  1122. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
  1123. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
  1124. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
  1125. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
  1126. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
  1127. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
  1128. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
  1129. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_REL32);
  1130. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
  1131. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
  1132. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
  1133. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
  1134. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
  1135. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
  1136. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
  1137. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_PAIR);
  1138. default:
  1139. return "Unknown";
  1140. }
  1141. break;
  1142. case COFF::IMAGE_FILE_MACHINE_ARM64:
  1143. case COFF::IMAGE_FILE_MACHINE_ARM64EC:
  1144. switch (Type) {
  1145. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ABSOLUTE);
  1146. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32);
  1147. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32NB);
  1148. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH26);
  1149. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEBASE_REL21);
  1150. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL21);
  1151. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12A);
  1152. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12L);
  1153. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL);
  1154. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12A);
  1155. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_HIGH12A);
  1156. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12L);
  1157. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_TOKEN);
  1158. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECTION);
  1159. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR64);
  1160. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH19);
  1161. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH14);
  1162. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL32);
  1163. default:
  1164. return "Unknown";
  1165. }
  1166. break;
  1167. case COFF::IMAGE_FILE_MACHINE_I386:
  1168. switch (Type) {
  1169. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
  1170. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
  1171. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
  1172. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
  1173. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
  1174. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
  1175. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
  1176. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
  1177. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
  1178. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
  1179. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
  1180. default:
  1181. return "Unknown";
  1182. }
  1183. break;
  1184. default:
  1185. return "Unknown";
  1186. }
  1187. }
  1188. #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
  1189. void COFFObjectFile::getRelocationTypeName(
  1190. DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
  1191. const coff_relocation *Reloc = toRel(Rel);
  1192. StringRef Res = getRelocationTypeName(Reloc->Type);
  1193. Result.append(Res.begin(), Res.end());
  1194. }
  1195. bool COFFObjectFile::isRelocatableObject() const {
  1196. return !DataDirectory;
  1197. }
  1198. StringRef COFFObjectFile::mapDebugSectionName(StringRef Name) const {
  1199. return StringSwitch<StringRef>(Name)
  1200. .Case("eh_fram", "eh_frame")
  1201. .Default(Name);
  1202. }
  1203. bool ImportDirectoryEntryRef::
  1204. operator==(const ImportDirectoryEntryRef &Other) const {
  1205. return ImportTable == Other.ImportTable && Index == Other.Index;
  1206. }
  1207. void ImportDirectoryEntryRef::moveNext() {
  1208. ++Index;
  1209. if (ImportTable[Index].isNull()) {
  1210. Index = -1;
  1211. ImportTable = nullptr;
  1212. }
  1213. }
  1214. Error ImportDirectoryEntryRef::getImportTableEntry(
  1215. const coff_import_directory_table_entry *&Result) const {
  1216. return getObject(Result, OwningObject->Data, ImportTable + Index);
  1217. }
  1218. static imported_symbol_iterator
  1219. makeImportedSymbolIterator(const COFFObjectFile *Object,
  1220. uintptr_t Ptr, int Index) {
  1221. if (Object->getBytesInAddress() == 4) {
  1222. auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
  1223. return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
  1224. }
  1225. auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
  1226. return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
  1227. }
  1228. static imported_symbol_iterator
  1229. importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
  1230. uintptr_t IntPtr = 0;
  1231. // FIXME: Handle errors.
  1232. cantFail(Object->getRvaPtr(RVA, IntPtr));
  1233. return makeImportedSymbolIterator(Object, IntPtr, 0);
  1234. }
  1235. static imported_symbol_iterator
  1236. importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
  1237. uintptr_t IntPtr = 0;
  1238. // FIXME: Handle errors.
  1239. cantFail(Object->getRvaPtr(RVA, IntPtr));
  1240. // Forward the pointer to the last entry which is null.
  1241. int Index = 0;
  1242. if (Object->getBytesInAddress() == 4) {
  1243. auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
  1244. while (*Entry++)
  1245. ++Index;
  1246. } else {
  1247. auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
  1248. while (*Entry++)
  1249. ++Index;
  1250. }
  1251. return makeImportedSymbolIterator(Object, IntPtr, Index);
  1252. }
  1253. imported_symbol_iterator
  1254. ImportDirectoryEntryRef::imported_symbol_begin() const {
  1255. return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
  1256. OwningObject);
  1257. }
  1258. imported_symbol_iterator
  1259. ImportDirectoryEntryRef::imported_symbol_end() const {
  1260. return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
  1261. OwningObject);
  1262. }
  1263. iterator_range<imported_symbol_iterator>
  1264. ImportDirectoryEntryRef::imported_symbols() const {
  1265. return make_range(imported_symbol_begin(), imported_symbol_end());
  1266. }
  1267. imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
  1268. return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
  1269. OwningObject);
  1270. }
  1271. imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
  1272. return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
  1273. OwningObject);
  1274. }
  1275. iterator_range<imported_symbol_iterator>
  1276. ImportDirectoryEntryRef::lookup_table_symbols() const {
  1277. return make_range(lookup_table_begin(), lookup_table_end());
  1278. }
  1279. Error ImportDirectoryEntryRef::getName(StringRef &Result) const {
  1280. uintptr_t IntPtr = 0;
  1281. if (Error E = OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr,
  1282. "import directory name"))
  1283. return E;
  1284. Result = StringRef(reinterpret_cast<const char *>(IntPtr));
  1285. return Error::success();
  1286. }
  1287. Error
  1288. ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
  1289. Result = ImportTable[Index].ImportLookupTableRVA;
  1290. return Error::success();
  1291. }
  1292. Error ImportDirectoryEntryRef::getImportAddressTableRVA(
  1293. uint32_t &Result) const {
  1294. Result = ImportTable[Index].ImportAddressTableRVA;
  1295. return Error::success();
  1296. }
  1297. bool DelayImportDirectoryEntryRef::
  1298. operator==(const DelayImportDirectoryEntryRef &Other) const {
  1299. return Table == Other.Table && Index == Other.Index;
  1300. }
  1301. void DelayImportDirectoryEntryRef::moveNext() {
  1302. ++Index;
  1303. }
  1304. imported_symbol_iterator
  1305. DelayImportDirectoryEntryRef::imported_symbol_begin() const {
  1306. return importedSymbolBegin(Table[Index].DelayImportNameTable,
  1307. OwningObject);
  1308. }
  1309. imported_symbol_iterator
  1310. DelayImportDirectoryEntryRef::imported_symbol_end() const {
  1311. return importedSymbolEnd(Table[Index].DelayImportNameTable,
  1312. OwningObject);
  1313. }
  1314. iterator_range<imported_symbol_iterator>
  1315. DelayImportDirectoryEntryRef::imported_symbols() const {
  1316. return make_range(imported_symbol_begin(), imported_symbol_end());
  1317. }
  1318. Error DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
  1319. uintptr_t IntPtr = 0;
  1320. if (Error E = OwningObject->getRvaPtr(Table[Index].Name, IntPtr,
  1321. "delay import directory name"))
  1322. return E;
  1323. Result = StringRef(reinterpret_cast<const char *>(IntPtr));
  1324. return Error::success();
  1325. }
  1326. Error DelayImportDirectoryEntryRef::getDelayImportTable(
  1327. const delay_import_directory_table_entry *&Result) const {
  1328. Result = &Table[Index];
  1329. return Error::success();
  1330. }
  1331. Error DelayImportDirectoryEntryRef::getImportAddress(int AddrIndex,
  1332. uint64_t &Result) const {
  1333. uint32_t RVA = Table[Index].DelayImportAddressTable +
  1334. AddrIndex * (OwningObject->is64() ? 8 : 4);
  1335. uintptr_t IntPtr = 0;
  1336. if (Error E = OwningObject->getRvaPtr(RVA, IntPtr, "import address"))
  1337. return E;
  1338. if (OwningObject->is64())
  1339. Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
  1340. else
  1341. Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
  1342. return Error::success();
  1343. }
  1344. bool ExportDirectoryEntryRef::
  1345. operator==(const ExportDirectoryEntryRef &Other) const {
  1346. return ExportTable == Other.ExportTable && Index == Other.Index;
  1347. }
  1348. void ExportDirectoryEntryRef::moveNext() {
  1349. ++Index;
  1350. }
  1351. // Returns the name of the current export symbol. If the symbol is exported only
  1352. // by ordinal, the empty string is set as a result.
  1353. Error ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
  1354. uintptr_t IntPtr = 0;
  1355. if (Error E =
  1356. OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr, "dll name"))
  1357. return E;
  1358. Result = StringRef(reinterpret_cast<const char *>(IntPtr));
  1359. return Error::success();
  1360. }
  1361. // Returns the starting ordinal number.
  1362. Error ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
  1363. Result = ExportTable->OrdinalBase;
  1364. return Error::success();
  1365. }
  1366. // Returns the export ordinal of the current export symbol.
  1367. Error ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
  1368. Result = ExportTable->OrdinalBase + Index;
  1369. return Error::success();
  1370. }
  1371. // Returns the address of the current export symbol.
  1372. Error ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
  1373. uintptr_t IntPtr = 0;
  1374. if (Error EC = OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA,
  1375. IntPtr, "export address"))
  1376. return EC;
  1377. const export_address_table_entry *entry =
  1378. reinterpret_cast<const export_address_table_entry *>(IntPtr);
  1379. Result = entry[Index].ExportRVA;
  1380. return Error::success();
  1381. }
  1382. // Returns the name of the current export symbol. If the symbol is exported only
  1383. // by ordinal, the empty string is set as a result.
  1384. Error
  1385. ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
  1386. uintptr_t IntPtr = 0;
  1387. if (Error EC = OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr,
  1388. "export ordinal table"))
  1389. return EC;
  1390. const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
  1391. uint32_t NumEntries = ExportTable->NumberOfNamePointers;
  1392. int Offset = 0;
  1393. for (const ulittle16_t *I = Start, *E = Start + NumEntries;
  1394. I < E; ++I, ++Offset) {
  1395. if (*I != Index)
  1396. continue;
  1397. if (Error EC = OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr,
  1398. "export table entry"))
  1399. return EC;
  1400. const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
  1401. if (Error EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr,
  1402. "export symbol name"))
  1403. return EC;
  1404. Result = StringRef(reinterpret_cast<const char *>(IntPtr));
  1405. return Error::success();
  1406. }
  1407. Result = "";
  1408. return Error::success();
  1409. }
  1410. Error ExportDirectoryEntryRef::isForwarder(bool &Result) const {
  1411. const data_directory *DataEntry =
  1412. OwningObject->getDataDirectory(COFF::EXPORT_TABLE);
  1413. if (!DataEntry)
  1414. return createStringError(object_error::parse_failed,
  1415. "export table missing");
  1416. uint32_t RVA;
  1417. if (auto EC = getExportRVA(RVA))
  1418. return EC;
  1419. uint32_t Begin = DataEntry->RelativeVirtualAddress;
  1420. uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
  1421. Result = (Begin <= RVA && RVA < End);
  1422. return Error::success();
  1423. }
  1424. Error ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
  1425. uint32_t RVA;
  1426. if (auto EC = getExportRVA(RVA))
  1427. return EC;
  1428. uintptr_t IntPtr = 0;
  1429. if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr, "export forward target"))
  1430. return EC;
  1431. Result = StringRef(reinterpret_cast<const char *>(IntPtr));
  1432. return Error::success();
  1433. }
  1434. bool ImportedSymbolRef::
  1435. operator==(const ImportedSymbolRef &Other) const {
  1436. return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
  1437. && Index == Other.Index;
  1438. }
  1439. void ImportedSymbolRef::moveNext() {
  1440. ++Index;
  1441. }
  1442. Error ImportedSymbolRef::getSymbolName(StringRef &Result) const {
  1443. uint32_t RVA;
  1444. if (Entry32) {
  1445. // If a symbol is imported only by ordinal, it has no name.
  1446. if (Entry32[Index].isOrdinal())
  1447. return Error::success();
  1448. RVA = Entry32[Index].getHintNameRVA();
  1449. } else {
  1450. if (Entry64[Index].isOrdinal())
  1451. return Error::success();
  1452. RVA = Entry64[Index].getHintNameRVA();
  1453. }
  1454. uintptr_t IntPtr = 0;
  1455. if (Error EC = OwningObject->getRvaPtr(RVA, IntPtr, "import symbol name"))
  1456. return EC;
  1457. // +2 because the first two bytes is hint.
  1458. Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
  1459. return Error::success();
  1460. }
  1461. Error ImportedSymbolRef::isOrdinal(bool &Result) const {
  1462. if (Entry32)
  1463. Result = Entry32[Index].isOrdinal();
  1464. else
  1465. Result = Entry64[Index].isOrdinal();
  1466. return Error::success();
  1467. }
  1468. Error ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
  1469. if (Entry32)
  1470. Result = Entry32[Index].getHintNameRVA();
  1471. else
  1472. Result = Entry64[Index].getHintNameRVA();
  1473. return Error::success();
  1474. }
  1475. Error ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
  1476. uint32_t RVA;
  1477. if (Entry32) {
  1478. if (Entry32[Index].isOrdinal()) {
  1479. Result = Entry32[Index].getOrdinal();
  1480. return Error::success();
  1481. }
  1482. RVA = Entry32[Index].getHintNameRVA();
  1483. } else {
  1484. if (Entry64[Index].isOrdinal()) {
  1485. Result = Entry64[Index].getOrdinal();
  1486. return Error::success();
  1487. }
  1488. RVA = Entry64[Index].getHintNameRVA();
  1489. }
  1490. uintptr_t IntPtr = 0;
  1491. if (Error EC = OwningObject->getRvaPtr(RVA, IntPtr, "import symbol ordinal"))
  1492. return EC;
  1493. Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
  1494. return Error::success();
  1495. }
  1496. Expected<std::unique_ptr<COFFObjectFile>>
  1497. ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
  1498. return COFFObjectFile::create(Object);
  1499. }
  1500. bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
  1501. return Header == Other.Header && Index == Other.Index;
  1502. }
  1503. void BaseRelocRef::moveNext() {
  1504. // Header->BlockSize is the size of the current block, including the
  1505. // size of the header itself.
  1506. uint32_t Size = sizeof(*Header) +
  1507. sizeof(coff_base_reloc_block_entry) * (Index + 1);
  1508. if (Size == Header->BlockSize) {
  1509. // .reloc contains a list of base relocation blocks. Each block
  1510. // consists of the header followed by entries. The header contains
  1511. // how many entories will follow. When we reach the end of the
  1512. // current block, proceed to the next block.
  1513. Header = reinterpret_cast<const coff_base_reloc_block_header *>(
  1514. reinterpret_cast<const uint8_t *>(Header) + Size);
  1515. Index = 0;
  1516. } else {
  1517. ++Index;
  1518. }
  1519. }
  1520. Error BaseRelocRef::getType(uint8_t &Type) const {
  1521. auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
  1522. Type = Entry[Index].getType();
  1523. return Error::success();
  1524. }
  1525. Error BaseRelocRef::getRVA(uint32_t &Result) const {
  1526. auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
  1527. Result = Header->PageRVA + Entry[Index].getOffset();
  1528. return Error::success();
  1529. }
  1530. #define RETURN_IF_ERROR(Expr) \
  1531. do { \
  1532. Error E = (Expr); \
  1533. if (E) \
  1534. return std::move(E); \
  1535. } while (0)
  1536. Expected<ArrayRef<UTF16>>
  1537. ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) {
  1538. BinaryStreamReader Reader = BinaryStreamReader(BBS);
  1539. Reader.setOffset(Offset);
  1540. uint16_t Length;
  1541. RETURN_IF_ERROR(Reader.readInteger(Length));
  1542. ArrayRef<UTF16> RawDirString;
  1543. RETURN_IF_ERROR(Reader.readArray(RawDirString, Length));
  1544. return RawDirString;
  1545. }
  1546. Expected<ArrayRef<UTF16>>
  1547. ResourceSectionRef::getEntryNameString(const coff_resource_dir_entry &Entry) {
  1548. return getDirStringAtOffset(Entry.Identifier.getNameOffset());
  1549. }
  1550. Expected<const coff_resource_dir_table &>
  1551. ResourceSectionRef::getTableAtOffset(uint32_t Offset) {
  1552. const coff_resource_dir_table *Table = nullptr;
  1553. BinaryStreamReader Reader(BBS);
  1554. Reader.setOffset(Offset);
  1555. RETURN_IF_ERROR(Reader.readObject(Table));
  1556. assert(Table != nullptr);
  1557. return *Table;
  1558. }
  1559. Expected<const coff_resource_dir_entry &>
  1560. ResourceSectionRef::getTableEntryAtOffset(uint32_t Offset) {
  1561. const coff_resource_dir_entry *Entry = nullptr;
  1562. BinaryStreamReader Reader(BBS);
  1563. Reader.setOffset(Offset);
  1564. RETURN_IF_ERROR(Reader.readObject(Entry));
  1565. assert(Entry != nullptr);
  1566. return *Entry;
  1567. }
  1568. Expected<const coff_resource_data_entry &>
  1569. ResourceSectionRef::getDataEntryAtOffset(uint32_t Offset) {
  1570. const coff_resource_data_entry *Entry = nullptr;
  1571. BinaryStreamReader Reader(BBS);
  1572. Reader.setOffset(Offset);
  1573. RETURN_IF_ERROR(Reader.readObject(Entry));
  1574. assert(Entry != nullptr);
  1575. return *Entry;
  1576. }
  1577. Expected<const coff_resource_dir_table &>
  1578. ResourceSectionRef::getEntrySubDir(const coff_resource_dir_entry &Entry) {
  1579. assert(Entry.Offset.isSubDir());
  1580. return getTableAtOffset(Entry.Offset.value());
  1581. }
  1582. Expected<const coff_resource_data_entry &>
  1583. ResourceSectionRef::getEntryData(const coff_resource_dir_entry &Entry) {
  1584. assert(!Entry.Offset.isSubDir());
  1585. return getDataEntryAtOffset(Entry.Offset.value());
  1586. }
  1587. Expected<const coff_resource_dir_table &> ResourceSectionRef::getBaseTable() {
  1588. return getTableAtOffset(0);
  1589. }
  1590. Expected<const coff_resource_dir_entry &>
  1591. ResourceSectionRef::getTableEntry(const coff_resource_dir_table &Table,
  1592. uint32_t Index) {
  1593. if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries))
  1594. return createStringError(object_error::parse_failed, "index out of range");
  1595. const uint8_t *TablePtr = reinterpret_cast<const uint8_t *>(&Table);
  1596. ptrdiff_t TableOffset = TablePtr - BBS.data().data();
  1597. return getTableEntryAtOffset(TableOffset + sizeof(Table) +
  1598. Index * sizeof(coff_resource_dir_entry));
  1599. }
  1600. Error ResourceSectionRef::load(const COFFObjectFile *O) {
  1601. for (const SectionRef &S : O->sections()) {
  1602. Expected<StringRef> Name = S.getName();
  1603. if (!Name)
  1604. return Name.takeError();
  1605. if (*Name == ".rsrc" || *Name == ".rsrc$01")
  1606. return load(O, S);
  1607. }
  1608. return createStringError(object_error::parse_failed,
  1609. "no resource section found");
  1610. }
  1611. Error ResourceSectionRef::load(const COFFObjectFile *O, const SectionRef &S) {
  1612. Obj = O;
  1613. Section = S;
  1614. Expected<StringRef> Contents = Section.getContents();
  1615. if (!Contents)
  1616. return Contents.takeError();
  1617. BBS = BinaryByteStream(*Contents, support::little);
  1618. const coff_section *COFFSect = Obj->getCOFFSection(Section);
  1619. ArrayRef<coff_relocation> OrigRelocs = Obj->getRelocations(COFFSect);
  1620. Relocs.reserve(OrigRelocs.size());
  1621. for (const coff_relocation &R : OrigRelocs)
  1622. Relocs.push_back(&R);
  1623. llvm::sort(Relocs, [](const coff_relocation *A, const coff_relocation *B) {
  1624. return A->VirtualAddress < B->VirtualAddress;
  1625. });
  1626. return Error::success();
  1627. }
  1628. Expected<StringRef>
  1629. ResourceSectionRef::getContents(const coff_resource_data_entry &Entry) {
  1630. if (!Obj)
  1631. return createStringError(object_error::parse_failed, "no object provided");
  1632. // Find a potential relocation at the DataRVA field (first member of
  1633. // the coff_resource_data_entry struct).
  1634. const uint8_t *EntryPtr = reinterpret_cast<const uint8_t *>(&Entry);
  1635. ptrdiff_t EntryOffset = EntryPtr - BBS.data().data();
  1636. coff_relocation RelocTarget{ulittle32_t(EntryOffset), ulittle32_t(0),
  1637. ulittle16_t(0)};
  1638. auto RelocsForOffset =
  1639. std::equal_range(Relocs.begin(), Relocs.end(), &RelocTarget,
  1640. [](const coff_relocation *A, const coff_relocation *B) {
  1641. return A->VirtualAddress < B->VirtualAddress;
  1642. });
  1643. if (RelocsForOffset.first != RelocsForOffset.second) {
  1644. // We found a relocation with the right offset. Check that it does have
  1645. // the expected type.
  1646. const coff_relocation &R = **RelocsForOffset.first;
  1647. uint16_t RVAReloc;
  1648. switch (Obj->getMachine()) {
  1649. case COFF::IMAGE_FILE_MACHINE_I386:
  1650. RVAReloc = COFF::IMAGE_REL_I386_DIR32NB;
  1651. break;
  1652. case COFF::IMAGE_FILE_MACHINE_AMD64:
  1653. RVAReloc = COFF::IMAGE_REL_AMD64_ADDR32NB;
  1654. break;
  1655. case COFF::IMAGE_FILE_MACHINE_ARMNT:
  1656. RVAReloc = COFF::IMAGE_REL_ARM_ADDR32NB;
  1657. break;
  1658. case COFF::IMAGE_FILE_MACHINE_ARM64:
  1659. case COFF::IMAGE_FILE_MACHINE_ARM64EC:
  1660. RVAReloc = COFF::IMAGE_REL_ARM64_ADDR32NB;
  1661. break;
  1662. default:
  1663. return createStringError(object_error::parse_failed,
  1664. "unsupported architecture");
  1665. }
  1666. if (R.Type != RVAReloc)
  1667. return createStringError(object_error::parse_failed,
  1668. "unexpected relocation type");
  1669. // Get the relocation's symbol
  1670. Expected<COFFSymbolRef> Sym = Obj->getSymbol(R.SymbolTableIndex);
  1671. if (!Sym)
  1672. return Sym.takeError();
  1673. // And the symbol's section
  1674. Expected<const coff_section *> Section =
  1675. Obj->getSection(Sym->getSectionNumber());
  1676. if (!Section)
  1677. return Section.takeError();
  1678. // Add the initial value of DataRVA to the symbol's offset to find the
  1679. // data it points at.
  1680. uint64_t Offset = Entry.DataRVA + Sym->getValue();
  1681. ArrayRef<uint8_t> Contents;
  1682. if (Error E = Obj->getSectionContents(*Section, Contents))
  1683. return std::move(E);
  1684. if (Offset + Entry.DataSize > Contents.size())
  1685. return createStringError(object_error::parse_failed,
  1686. "data outside of section");
  1687. // Return a reference to the data inside the section.
  1688. return StringRef(reinterpret_cast<const char *>(Contents.data()) + Offset,
  1689. Entry.DataSize);
  1690. } else {
  1691. // Relocatable objects need a relocation for the DataRVA field.
  1692. if (Obj->isRelocatableObject())
  1693. return createStringError(object_error::parse_failed,
  1694. "no relocation found for DataRVA");
  1695. // Locate the section that contains the address that DataRVA points at.
  1696. uint64_t VA = Entry.DataRVA + Obj->getImageBase();
  1697. for (const SectionRef &S : Obj->sections()) {
  1698. if (VA >= S.getAddress() &&
  1699. VA + Entry.DataSize <= S.getAddress() + S.getSize()) {
  1700. uint64_t Offset = VA - S.getAddress();
  1701. Expected<StringRef> Contents = S.getContents();
  1702. if (!Contents)
  1703. return Contents.takeError();
  1704. return Contents->slice(Offset, Offset + Entry.DataSize);
  1705. }
  1706. }
  1707. return createStringError(object_error::parse_failed,
  1708. "address not found in image");
  1709. }
  1710. }