COFFObjectFile.cpp 49 KB

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