COFFObjectFile.cpp 49 KB

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