COFFObjectFile.cpp 49 KB

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