ELFObjHandler.cpp 23 KB

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