COFFObjectFile.cpp 53 KB

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