ELFObjHandler.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. //===- ELFObjHandler.cpp --------------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===-----------------------------------------------------------------------===/
  8. #include "llvm/InterfaceStub/ELFObjHandler.h"
  9. #include "llvm/InterfaceStub/ELFStub.h"
  10. #include "llvm/MC/StringTableBuilder.h"
  11. #include "llvm/Object/Binary.h"
  12. #include "llvm/Object/ELFObjectFile.h"
  13. #include "llvm/Object/ELFTypes.h"
  14. #include "llvm/Support/Errc.h"
  15. #include "llvm/Support/Error.h"
  16. #include "llvm/Support/FileOutputBuffer.h"
  17. #include "llvm/Support/MathExtras.h"
  18. #include "llvm/Support/MemoryBuffer.h"
  19. #include "llvm/Support/Process.h"
  20. using llvm::MemoryBufferRef;
  21. using llvm::object::ELFObjectFile;
  22. using namespace llvm;
  23. using namespace llvm::object;
  24. using namespace llvm::ELF;
  25. namespace llvm {
  26. namespace elfabi {
  27. // Simple struct to hold relevant .dynamic entries.
  28. struct DynamicEntries {
  29. uint64_t StrTabAddr = 0;
  30. uint64_t StrSize = 0;
  31. Optional<uint64_t> SONameOffset;
  32. std::vector<uint64_t> NeededLibNames;
  33. // Symbol table:
  34. uint64_t DynSymAddr = 0;
  35. // Hash tables:
  36. Optional<uint64_t> ElfHash;
  37. Optional<uint64_t> GnuHash;
  38. };
  39. /// This initializes an ELF file header with information specific to a binary
  40. /// dynamic shared object.
  41. /// Offsets, indexes, links, etc. for section and program headers are just
  42. /// zero-initialized as they will be updated elsewhere.
  43. ///
  44. /// @param ElfHeader Target ELFT::Ehdr to populate.
  45. /// @param Machine Target architecture (e_machine from ELF specifications).
  46. template <class ELFT>
  47. static void initELFHeader(typename ELFT::Ehdr &ElfHeader, uint16_t Machine) {
  48. memset(&ElfHeader, 0, sizeof(ElfHeader));
  49. // ELF identification.
  50. ElfHeader.e_ident[EI_MAG0] = ElfMagic[EI_MAG0];
  51. ElfHeader.e_ident[EI_MAG1] = ElfMagic[EI_MAG1];
  52. ElfHeader.e_ident[EI_MAG2] = ElfMagic[EI_MAG2];
  53. ElfHeader.e_ident[EI_MAG3] = ElfMagic[EI_MAG3];
  54. ElfHeader.e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
  55. bool IsLittleEndian = ELFT::TargetEndianness == support::little;
  56. ElfHeader.e_ident[EI_DATA] = IsLittleEndian ? ELFDATA2LSB : ELFDATA2MSB;
  57. ElfHeader.e_ident[EI_VERSION] = EV_CURRENT;
  58. ElfHeader.e_ident[EI_OSABI] = ELFOSABI_NONE;
  59. // Remainder of ELF header.
  60. ElfHeader.e_type = ET_DYN;
  61. ElfHeader.e_machine = Machine;
  62. ElfHeader.e_version = EV_CURRENT;
  63. ElfHeader.e_ehsize = sizeof(typename ELFT::Ehdr);
  64. ElfHeader.e_phentsize = sizeof(typename ELFT::Phdr);
  65. ElfHeader.e_shentsize = sizeof(typename ELFT::Shdr);
  66. }
  67. namespace {
  68. template <class ELFT> struct OutputSection {
  69. using Elf_Shdr = typename ELFT::Shdr;
  70. std::string Name;
  71. Elf_Shdr Shdr;
  72. uint64_t Addr;
  73. uint64_t Offset;
  74. uint64_t Size;
  75. uint64_t Align;
  76. uint32_t Index;
  77. bool NoBits = true;
  78. };
  79. template <class T, class ELFT>
  80. struct ContentSection : public OutputSection<ELFT> {
  81. T Content;
  82. ContentSection() { this->NoBits = false; }
  83. };
  84. // This class just wraps StringTableBuilder for the purpose of adding a
  85. // default constructor.
  86. class ELFStringTableBuilder : public StringTableBuilder {
  87. public:
  88. ELFStringTableBuilder() : StringTableBuilder(StringTableBuilder::ELF) {}
  89. };
  90. template <class ELFT> class ELFSymbolTableBuilder {
  91. public:
  92. using Elf_Sym = typename ELFT::Sym;
  93. ELFSymbolTableBuilder() { Symbols.push_back({}); }
  94. void add(size_t StNameOffset, uint64_t StSize, uint8_t StBind, uint8_t StType,
  95. uint8_t StOther, uint16_t StShndx) {
  96. Elf_Sym S{};
  97. S.st_name = StNameOffset;
  98. S.st_size = StSize;
  99. S.st_info = (StBind << 4) | (StType & 0xf);
  100. S.st_other = StOther;
  101. S.st_shndx = StShndx;
  102. Symbols.push_back(S);
  103. }
  104. size_t getSize() const { return Symbols.size() * sizeof(Elf_Sym); }
  105. void write(uint8_t *Buf) const {
  106. memcpy(Buf, Symbols.data(), sizeof(Elf_Sym) * Symbols.size());
  107. }
  108. private:
  109. llvm::SmallVector<Elf_Sym, 8> Symbols;
  110. };
  111. template <class ELFT> class ELFDynamicTableBuilder {
  112. public:
  113. using Elf_Dyn = typename ELFT::Dyn;
  114. size_t addAddr(uint64_t Tag, uint64_t Addr) {
  115. Elf_Dyn Entry;
  116. Entry.d_tag = Tag;
  117. Entry.d_un.d_ptr = Addr;
  118. Entries.push_back(Entry);
  119. return Entries.size() - 1;
  120. }
  121. void modifyAddr(size_t Index, uint64_t Addr) {
  122. Entries[Index].d_un.d_ptr = Addr;
  123. }
  124. size_t addValue(uint64_t Tag, uint64_t Value) {
  125. Elf_Dyn Entry;
  126. Entry.d_tag = Tag;
  127. Entry.d_un.d_val = Value;
  128. Entries.push_back(Entry);
  129. return Entries.size() - 1;
  130. }
  131. void modifyValue(size_t Index, uint64_t Value) {
  132. Entries[Index].d_un.d_val = Value;
  133. }
  134. size_t getSize() const {
  135. // Add DT_NULL entry at the end.
  136. return (Entries.size() + 1) * sizeof(Elf_Dyn);
  137. }
  138. void write(uint8_t *Buf) const {
  139. memcpy(Buf, Entries.data(), sizeof(Elf_Dyn) * Entries.size());
  140. // Add DT_NULL entry at the end.
  141. memset(Buf + sizeof(Elf_Dyn) * Entries.size(), 0, sizeof(Elf_Dyn));
  142. }
  143. private:
  144. llvm::SmallVector<Elf_Dyn, 8> Entries;
  145. };
  146. template <class ELFT> class ELFStubBuilder {
  147. public:
  148. using Elf_Ehdr = typename ELFT::Ehdr;
  149. using Elf_Shdr = typename ELFT::Shdr;
  150. using Elf_Phdr = typename ELFT::Phdr;
  151. using Elf_Sym = typename ELFT::Sym;
  152. using Elf_Addr = typename ELFT::Addr;
  153. using Elf_Dyn = typename ELFT::Dyn;
  154. ELFStubBuilder(const ELFStubBuilder &) = delete;
  155. ELFStubBuilder(ELFStubBuilder &&) = default;
  156. explicit ELFStubBuilder(const ELFStub &Stub) {
  157. DynSym.Name = ".dynsym";
  158. DynSym.Align = sizeof(Elf_Addr);
  159. DynStr.Name = ".dynstr";
  160. DynStr.Align = 1;
  161. DynTab.Name = ".dynamic";
  162. DynTab.Align = sizeof(Elf_Addr);
  163. ShStrTab.Name = ".shstrtab";
  164. ShStrTab.Align = 1;
  165. // Populate string tables.
  166. for (const ELFSymbol &Sym : Stub.Symbols)
  167. DynStr.Content.add(Sym.Name);
  168. for (const std::string &Lib : Stub.NeededLibs)
  169. DynStr.Content.add(Lib);
  170. if (Stub.SoName)
  171. DynStr.Content.add(Stub.SoName.getValue());
  172. std::vector<OutputSection<ELFT> *> Sections = {&DynSym, &DynStr, &DynTab,
  173. &ShStrTab};
  174. const OutputSection<ELFT> *LastSection = Sections.back();
  175. // Now set the Index and put sections names into ".shstrtab".
  176. uint64_t Index = 1;
  177. for (OutputSection<ELFT> *Sec : Sections) {
  178. Sec->Index = Index++;
  179. ShStrTab.Content.add(Sec->Name);
  180. }
  181. ShStrTab.Content.finalize();
  182. ShStrTab.Size = ShStrTab.Content.getSize();
  183. DynStr.Content.finalize();
  184. DynStr.Size = DynStr.Content.getSize();
  185. // Populate dynamic symbol table.
  186. for (const ELFSymbol &Sym : Stub.Symbols) {
  187. uint8_t Bind = Sym.Weak ? STB_WEAK : STB_GLOBAL;
  188. // For non-undefined symbols, value of the shndx is not relevant at link
  189. // time as long as it is not SHN_UNDEF. Set shndx to 1, which
  190. // points to ".dynsym".
  191. uint16_t Shndx = Sym.Undefined ? SHN_UNDEF : 1;
  192. DynSym.Content.add(DynStr.Content.getOffset(Sym.Name), Sym.Size, Bind,
  193. (uint8_t)Sym.Type, 0, Shndx);
  194. }
  195. DynSym.Size = DynSym.Content.getSize();
  196. // Poplulate dynamic table.
  197. size_t DynSymIndex = DynTab.Content.addAddr(DT_SYMTAB, 0);
  198. size_t DynStrIndex = DynTab.Content.addAddr(DT_STRTAB, 0);
  199. for (const std::string &Lib : Stub.NeededLibs)
  200. DynTab.Content.addValue(DT_NEEDED, DynStr.Content.getOffset(Lib));
  201. if (Stub.SoName)
  202. DynTab.Content.addValue(DT_SONAME,
  203. DynStr.Content.getOffset(Stub.SoName.getValue()));
  204. DynTab.Size = DynTab.Content.getSize();
  205. // Calculate sections' addresses and offsets.
  206. uint64_t CurrentOffset = sizeof(Elf_Ehdr);
  207. for (OutputSection<ELFT> *Sec : Sections) {
  208. Sec->Offset = alignTo(CurrentOffset, Sec->Align);
  209. Sec->Addr = Sec->Offset;
  210. CurrentOffset = Sec->Offset + Sec->Size;
  211. }
  212. // Fill Addr back to dynamic table.
  213. DynTab.Content.modifyAddr(DynSymIndex, DynSym.Addr);
  214. DynTab.Content.modifyAddr(DynStrIndex, DynStr.Addr);
  215. // Write section headers of string tables.
  216. fillSymTabShdr(DynSym, SHT_DYNSYM);
  217. fillStrTabShdr(DynStr, SHF_ALLOC);
  218. fillDynTabShdr(DynTab);
  219. fillStrTabShdr(ShStrTab);
  220. // Finish initializing the ELF header.
  221. initELFHeader<ELFT>(ElfHeader, Stub.Arch);
  222. ElfHeader.e_shstrndx = ShStrTab.Index;
  223. ElfHeader.e_shnum = LastSection->Index + 1;
  224. ElfHeader.e_shoff =
  225. alignTo(LastSection->Offset + LastSection->Size, sizeof(Elf_Addr));
  226. }
  227. size_t getSize() const {
  228. return ElfHeader.e_shoff + ElfHeader.e_shnum * sizeof(Elf_Shdr);
  229. }
  230. void write(uint8_t *Data) const {
  231. write(Data, ElfHeader);
  232. DynSym.Content.write(Data + DynSym.Shdr.sh_offset);
  233. DynStr.Content.write(Data + DynStr.Shdr.sh_offset);
  234. DynTab.Content.write(Data + DynTab.Shdr.sh_offset);
  235. ShStrTab.Content.write(Data + ShStrTab.Shdr.sh_offset);
  236. writeShdr(Data, DynSym);
  237. writeShdr(Data, DynStr);
  238. writeShdr(Data, DynTab);
  239. writeShdr(Data, ShStrTab);
  240. }
  241. private:
  242. Elf_Ehdr ElfHeader;
  243. ContentSection<ELFStringTableBuilder, ELFT> DynStr;
  244. ContentSection<ELFStringTableBuilder, ELFT> ShStrTab;
  245. ContentSection<ELFSymbolTableBuilder<ELFT>, ELFT> DynSym;
  246. ContentSection<ELFDynamicTableBuilder<ELFT>, ELFT> DynTab;
  247. template <class T> static void write(uint8_t *Data, const T &Value) {
  248. *reinterpret_cast<T *>(Data) = Value;
  249. }
  250. void fillStrTabShdr(ContentSection<ELFStringTableBuilder, ELFT> &StrTab,
  251. uint32_t ShFlags = 0) const {
  252. StrTab.Shdr.sh_type = SHT_STRTAB;
  253. StrTab.Shdr.sh_flags = ShFlags;
  254. StrTab.Shdr.sh_addr = StrTab.Addr;
  255. StrTab.Shdr.sh_offset = StrTab.Offset;
  256. StrTab.Shdr.sh_info = 0;
  257. StrTab.Shdr.sh_size = StrTab.Size;
  258. StrTab.Shdr.sh_name = ShStrTab.Content.getOffset(StrTab.Name);
  259. StrTab.Shdr.sh_addralign = StrTab.Align;
  260. StrTab.Shdr.sh_entsize = 0;
  261. StrTab.Shdr.sh_link = 0;
  262. }
  263. void fillSymTabShdr(ContentSection<ELFSymbolTableBuilder<ELFT>, ELFT> &SymTab,
  264. uint32_t ShType) const {
  265. SymTab.Shdr.sh_type = ShType;
  266. SymTab.Shdr.sh_flags = SHF_ALLOC;
  267. SymTab.Shdr.sh_addr = SymTab.Addr;
  268. SymTab.Shdr.sh_offset = SymTab.Offset;
  269. SymTab.Shdr.sh_info = SymTab.Size / sizeof(Elf_Sym) > 1 ? 1 : 0;
  270. SymTab.Shdr.sh_size = SymTab.Size;
  271. SymTab.Shdr.sh_name = this->ShStrTab.Content.getOffset(SymTab.Name);
  272. SymTab.Shdr.sh_addralign = SymTab.Align;
  273. SymTab.Shdr.sh_entsize = sizeof(Elf_Sym);
  274. SymTab.Shdr.sh_link = this->DynStr.Index;
  275. }
  276. void fillDynTabShdr(
  277. ContentSection<ELFDynamicTableBuilder<ELFT>, ELFT> &DynTab) const {
  278. DynTab.Shdr.sh_type = SHT_DYNAMIC;
  279. DynTab.Shdr.sh_flags = SHF_ALLOC;
  280. DynTab.Shdr.sh_addr = DynTab.Addr;
  281. DynTab.Shdr.sh_offset = DynTab.Offset;
  282. DynTab.Shdr.sh_info = 0;
  283. DynTab.Shdr.sh_size = DynTab.Size;
  284. DynTab.Shdr.sh_name = this->ShStrTab.Content.getOffset(DynTab.Name);
  285. DynTab.Shdr.sh_addralign = DynTab.Align;
  286. DynTab.Shdr.sh_entsize = sizeof(Elf_Dyn);
  287. DynTab.Shdr.sh_link = this->DynStr.Index;
  288. }
  289. uint64_t shdrOffset(const OutputSection<ELFT> &Sec) const {
  290. return ElfHeader.e_shoff + Sec.Index * sizeof(Elf_Shdr);
  291. }
  292. void writeShdr(uint8_t *Data, const OutputSection<ELFT> &Sec) const {
  293. write(Data + shdrOffset(Sec), Sec.Shdr);
  294. }
  295. };
  296. } // end anonymous namespace
  297. /// This function behaves similarly to StringRef::substr(), but attempts to
  298. /// terminate the returned StringRef at the first null terminator. If no null
  299. /// terminator is found, an error is returned.
  300. ///
  301. /// @param Str Source string to create a substring from.
  302. /// @param Offset The start index of the desired substring.
  303. static Expected<StringRef> terminatedSubstr(StringRef Str, size_t Offset) {
  304. size_t StrEnd = Str.find('\0', Offset);
  305. if (StrEnd == StringLiteral::npos) {
  306. return createError(
  307. "String overran bounds of string table (no null terminator)");
  308. }
  309. size_t StrLen = StrEnd - Offset;
  310. return Str.substr(Offset, StrLen);
  311. }
  312. /// This function takes an error, and appends a string of text to the end of
  313. /// that error. Since "appending" to an Error isn't supported behavior of an
  314. /// Error, this function technically creates a new error with the combined
  315. /// message and consumes the old error.
  316. ///
  317. /// @param Err Source error.
  318. /// @param After Text to append at the end of Err's error message.
  319. Error appendToError(Error Err, StringRef After) {
  320. std::string Message;
  321. raw_string_ostream Stream(Message);
  322. Stream << Err;
  323. Stream << " " << After;
  324. consumeError(std::move(Err));
  325. return createError(Stream.str().c_str());
  326. }
  327. /// This function populates a DynamicEntries struct using an ELFT::DynRange.
  328. /// After populating the struct, the members are validated with
  329. /// some basic sanity checks.
  330. ///
  331. /// @param Dyn Target DynamicEntries struct to populate.
  332. /// @param DynTable Source dynamic table.
  333. template <class ELFT>
  334. static Error populateDynamic(DynamicEntries &Dyn,
  335. typename ELFT::DynRange DynTable) {
  336. if (DynTable.empty())
  337. return createError("No .dynamic section found");
  338. // Search .dynamic for relevant entries.
  339. bool FoundDynStr = false;
  340. bool FoundDynStrSz = false;
  341. bool FoundDynSym = false;
  342. for (auto &Entry : DynTable) {
  343. switch (Entry.d_tag) {
  344. case DT_SONAME:
  345. Dyn.SONameOffset = Entry.d_un.d_val;
  346. break;
  347. case DT_STRTAB:
  348. Dyn.StrTabAddr = Entry.d_un.d_ptr;
  349. FoundDynStr = true;
  350. break;
  351. case DT_STRSZ:
  352. Dyn.StrSize = Entry.d_un.d_val;
  353. FoundDynStrSz = true;
  354. break;
  355. case DT_NEEDED:
  356. Dyn.NeededLibNames.push_back(Entry.d_un.d_val);
  357. break;
  358. case DT_SYMTAB:
  359. Dyn.DynSymAddr = Entry.d_un.d_ptr;
  360. FoundDynSym = true;
  361. break;
  362. case DT_HASH:
  363. Dyn.ElfHash = Entry.d_un.d_ptr;
  364. break;
  365. case DT_GNU_HASH:
  366. Dyn.GnuHash = Entry.d_un.d_ptr;
  367. }
  368. }
  369. if (!FoundDynStr) {
  370. return createError(
  371. "Couldn't locate dynamic string table (no DT_STRTAB entry)");
  372. }
  373. if (!FoundDynStrSz) {
  374. return createError(
  375. "Couldn't determine dynamic string table size (no DT_STRSZ entry)");
  376. }
  377. if (!FoundDynSym) {
  378. return createError(
  379. "Couldn't locate dynamic symbol table (no DT_SYMTAB entry)");
  380. }
  381. if (Dyn.SONameOffset.hasValue() && *Dyn.SONameOffset >= Dyn.StrSize) {
  382. return createStringError(object_error::parse_failed,
  383. "DT_SONAME string offset (0x%016" PRIx64
  384. ") outside of dynamic string table",
  385. *Dyn.SONameOffset);
  386. }
  387. for (uint64_t Offset : Dyn.NeededLibNames) {
  388. if (Offset >= Dyn.StrSize) {
  389. return createStringError(object_error::parse_failed,
  390. "DT_NEEDED string offset (0x%016" PRIx64
  391. ") outside of dynamic string table",
  392. Offset);
  393. }
  394. }
  395. return Error::success();
  396. }
  397. /// This function extracts symbol type from a symbol's st_info member and
  398. /// maps it to an ELFSymbolType enum.
  399. /// Currently, STT_NOTYPE, STT_OBJECT, STT_FUNC, and STT_TLS are supported.
  400. /// Other symbol types are mapped to ELFSymbolType::Unknown.
  401. ///
  402. /// @param Info Binary symbol st_info to extract symbol type from.
  403. static ELFSymbolType convertInfoToType(uint8_t Info) {
  404. Info = Info & 0xf;
  405. switch (Info) {
  406. case ELF::STT_NOTYPE:
  407. return ELFSymbolType::NoType;
  408. case ELF::STT_OBJECT:
  409. return ELFSymbolType::Object;
  410. case ELF::STT_FUNC:
  411. return ELFSymbolType::Func;
  412. case ELF::STT_TLS:
  413. return ELFSymbolType::TLS;
  414. default:
  415. return ELFSymbolType::Unknown;
  416. }
  417. }
  418. /// This function creates an ELFSymbol and populates all members using
  419. /// information from a binary ELFT::Sym.
  420. ///
  421. /// @param SymName The desired name of the ELFSymbol.
  422. /// @param RawSym ELFT::Sym to extract symbol information from.
  423. template <class ELFT>
  424. static ELFSymbol createELFSym(StringRef SymName,
  425. const typename ELFT::Sym &RawSym) {
  426. ELFSymbol TargetSym{std::string(SymName)};
  427. uint8_t Binding = RawSym.getBinding();
  428. if (Binding == STB_WEAK)
  429. TargetSym.Weak = true;
  430. else
  431. TargetSym.Weak = false;
  432. TargetSym.Undefined = RawSym.isUndefined();
  433. TargetSym.Type = convertInfoToType(RawSym.st_info);
  434. if (TargetSym.Type == ELFSymbolType::Func) {
  435. TargetSym.Size = 0;
  436. } else {
  437. TargetSym.Size = RawSym.st_size;
  438. }
  439. return TargetSym;
  440. }
  441. /// This function populates an ELFStub with symbols using information read
  442. /// from an ELF binary.
  443. ///
  444. /// @param TargetStub ELFStub to add symbols to.
  445. /// @param DynSym Range of dynamic symbols to add to TargetStub.
  446. /// @param DynStr StringRef to the dynamic string table.
  447. template <class ELFT>
  448. static Error populateSymbols(ELFStub &TargetStub,
  449. const typename ELFT::SymRange DynSym,
  450. StringRef DynStr) {
  451. // Skips the first symbol since it's the NULL symbol.
  452. for (auto RawSym : DynSym.drop_front(1)) {
  453. // If a symbol does not have global or weak binding, ignore it.
  454. uint8_t Binding = RawSym.getBinding();
  455. if (!(Binding == STB_GLOBAL || Binding == STB_WEAK))
  456. continue;
  457. // If a symbol doesn't have default or protected visibility, ignore it.
  458. uint8_t Visibility = RawSym.getVisibility();
  459. if (!(Visibility == STV_DEFAULT || Visibility == STV_PROTECTED))
  460. continue;
  461. // Create an ELFSymbol and populate it with information from the symbol
  462. // table entry.
  463. Expected<StringRef> SymName = terminatedSubstr(DynStr, RawSym.st_name);
  464. if (!SymName)
  465. return SymName.takeError();
  466. ELFSymbol Sym = createELFSym<ELFT>(*SymName, RawSym);
  467. TargetStub.Symbols.insert(std::move(Sym));
  468. // TODO: Populate symbol warning.
  469. }
  470. return Error::success();
  471. }
  472. /// Returns a new ELFStub with all members populated from an ELFObjectFile.
  473. /// @param ElfObj Source ELFObjectFile.
  474. template <class ELFT>
  475. static Expected<std::unique_ptr<ELFStub>>
  476. buildStub(const ELFObjectFile<ELFT> &ElfObj) {
  477. using Elf_Dyn_Range = typename ELFT::DynRange;
  478. using Elf_Phdr_Range = typename ELFT::PhdrRange;
  479. using Elf_Sym_Range = typename ELFT::SymRange;
  480. using Elf_Sym = typename ELFT::Sym;
  481. std::unique_ptr<ELFStub> DestStub = std::make_unique<ELFStub>();
  482. const ELFFile<ELFT> &ElfFile = ElfObj.getELFFile();
  483. // Fetch .dynamic table.
  484. Expected<Elf_Dyn_Range> DynTable = ElfFile.dynamicEntries();
  485. if (!DynTable) {
  486. return DynTable.takeError();
  487. }
  488. // Fetch program headers.
  489. Expected<Elf_Phdr_Range> PHdrs = ElfFile.program_headers();
  490. if (!PHdrs) {
  491. return PHdrs.takeError();
  492. }
  493. // Collect relevant .dynamic entries.
  494. DynamicEntries DynEnt;
  495. if (Error Err = populateDynamic<ELFT>(DynEnt, *DynTable))
  496. return std::move(Err);
  497. // Get pointer to in-memory location of .dynstr section.
  498. Expected<const uint8_t *> DynStrPtr = ElfFile.toMappedAddr(DynEnt.StrTabAddr);
  499. if (!DynStrPtr)
  500. return appendToError(DynStrPtr.takeError(),
  501. "when locating .dynstr section contents");
  502. StringRef DynStr(reinterpret_cast<const char *>(DynStrPtr.get()),
  503. DynEnt.StrSize);
  504. // Populate Arch from ELF header.
  505. DestStub->Arch = ElfFile.getHeader().e_machine;
  506. // Populate SoName from .dynamic entries and dynamic string table.
  507. if (DynEnt.SONameOffset.hasValue()) {
  508. Expected<StringRef> NameOrErr =
  509. terminatedSubstr(DynStr, *DynEnt.SONameOffset);
  510. if (!NameOrErr) {
  511. return appendToError(NameOrErr.takeError(), "when reading DT_SONAME");
  512. }
  513. DestStub->SoName = std::string(*NameOrErr);
  514. }
  515. // Populate NeededLibs from .dynamic entries and dynamic string table.
  516. for (uint64_t NeededStrOffset : DynEnt.NeededLibNames) {
  517. Expected<StringRef> LibNameOrErr =
  518. terminatedSubstr(DynStr, NeededStrOffset);
  519. if (!LibNameOrErr) {
  520. return appendToError(LibNameOrErr.takeError(), "when reading DT_NEEDED");
  521. }
  522. DestStub->NeededLibs.push_back(std::string(*LibNameOrErr));
  523. }
  524. // Populate Symbols from .dynsym table and dynamic string table.
  525. Expected<uint64_t> SymCount = ElfFile.getDynSymtabSize();
  526. if (!SymCount)
  527. return SymCount.takeError();
  528. if (*SymCount > 0) {
  529. // Get pointer to in-memory location of .dynsym section.
  530. Expected<const uint8_t *> DynSymPtr =
  531. ElfFile.toMappedAddr(DynEnt.DynSymAddr);
  532. if (!DynSymPtr)
  533. return appendToError(DynSymPtr.takeError(),
  534. "when locating .dynsym section contents");
  535. Elf_Sym_Range DynSyms = ArrayRef<Elf_Sym>(
  536. reinterpret_cast<const Elf_Sym *>(*DynSymPtr), *SymCount);
  537. Error SymReadError = populateSymbols<ELFT>(*DestStub, DynSyms, DynStr);
  538. if (SymReadError)
  539. return appendToError(std::move(SymReadError),
  540. "when reading dynamic symbols");
  541. }
  542. return std::move(DestStub);
  543. }
  544. /// This function opens a file for writing and then writes a binary ELF stub to
  545. /// the file.
  546. ///
  547. /// @param FilePath File path for writing the ELF binary.
  548. /// @param Stub Source ELFStub to generate a binary ELF stub from.
  549. template <class ELFT>
  550. static Error writeELFBinaryToFile(StringRef FilePath, const ELFStub &Stub,
  551. bool WriteIfChanged) {
  552. ELFStubBuilder<ELFT> Builder{Stub};
  553. // Write Stub to memory first.
  554. std::vector<uint8_t> Buf(Builder.getSize());
  555. Builder.write(Buf.data());
  556. if (WriteIfChanged) {
  557. if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrError =
  558. MemoryBuffer::getFile(FilePath)) {
  559. // Compare Stub output with existing Stub file.
  560. // If Stub file unchanged, abort updating.
  561. if ((*BufOrError)->getBufferSize() == Builder.getSize() &&
  562. !memcmp((*BufOrError)->getBufferStart(), Buf.data(),
  563. Builder.getSize()))
  564. return Error::success();
  565. }
  566. }
  567. Expected<std::unique_ptr<FileOutputBuffer>> BufOrError =
  568. FileOutputBuffer::create(FilePath, Builder.getSize());
  569. if (!BufOrError)
  570. return createStringError(errc::invalid_argument,
  571. toString(BufOrError.takeError()) +
  572. " when trying to open `" + FilePath +
  573. "` for writing");
  574. // Write binary to file.
  575. std::unique_ptr<FileOutputBuffer> FileBuf = std::move(*BufOrError);
  576. memcpy(FileBuf->getBufferStart(), Buf.data(), Buf.size());
  577. return FileBuf->commit();
  578. }
  579. Expected<std::unique_ptr<ELFStub>> readELFFile(MemoryBufferRef Buf) {
  580. Expected<std::unique_ptr<Binary>> BinOrErr = createBinary(Buf);
  581. if (!BinOrErr) {
  582. return BinOrErr.takeError();
  583. }
  584. Binary *Bin = BinOrErr->get();
  585. if (auto Obj = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
  586. return buildStub(*Obj);
  587. } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
  588. return buildStub(*Obj);
  589. } else if (auto Obj = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
  590. return buildStub(*Obj);
  591. } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
  592. return buildStub(*Obj);
  593. }
  594. return createStringError(errc::not_supported, "unsupported binary format");
  595. }
  596. // This function wraps the ELFT writeELFBinaryToFile() so writeBinaryStub()
  597. // can be called without having to use ELFType templates directly.
  598. Error writeBinaryStub(StringRef FilePath, const ELFStub &Stub,
  599. ELFTarget OutputFormat, bool WriteIfChanged) {
  600. if (OutputFormat == ELFTarget::ELF32LE)
  601. return writeELFBinaryToFile<ELF32LE>(FilePath, Stub, WriteIfChanged);
  602. if (OutputFormat == ELFTarget::ELF32BE)
  603. return writeELFBinaryToFile<ELF32BE>(FilePath, Stub, WriteIfChanged);
  604. if (OutputFormat == ELFTarget::ELF64LE)
  605. return writeELFBinaryToFile<ELF64LE>(FilePath, Stub, WriteIfChanged);
  606. if (OutputFormat == ELFTarget::ELF64BE)
  607. return writeELFBinaryToFile<ELF64BE>(FilePath, Stub, WriteIfChanged);
  608. llvm_unreachable("invalid binary output target");
  609. }
  610. } // end namespace elfabi
  611. } // end namespace llvm