COFFObjectFile.cpp 56 KB

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