COFFObjectFile.cpp 65 KB

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