ELFObjHandler.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  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 <optional>
  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. std::optional<uint64_t> SONameOffset;
  31. std::vector<uint64_t> NeededLibNames;
  32. // Symbol table:
  33. uint64_t DynSymAddr = 0;
  34. // Hash tables:
  35. std::optional<uint64_t> ElfHash;
  36. std::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);
  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. uint64_t Size = Sym.Size.value_or(0);
  192. DynSym.Content.add(DynStr.Content.getOffset(Sym.Name), Size, Bind,
  193. convertIFSSymbolTypeToELF(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. DynTab.Content.addValue(DT_STRSZ, DynSym.Size);
  200. for (const std::string &Lib : Stub.NeededLibs)
  201. DynTab.Content.addValue(DT_NEEDED, DynStr.Content.getOffset(Lib));
  202. if (Stub.SoName)
  203. DynTab.Content.addValue(DT_SONAME,
  204. DynStr.Content.getOffset(*Stub.SoName));
  205. DynTab.Size = DynTab.Content.getSize();
  206. // Calculate sections' addresses and offsets.
  207. uint64_t CurrentOffset = sizeof(Elf_Ehdr);
  208. for (OutputSection<ELFT> *Sec : Sections) {
  209. Sec->Offset = alignTo(CurrentOffset, Sec->Align);
  210. Sec->Addr = Sec->Offset;
  211. CurrentOffset = Sec->Offset + Sec->Size;
  212. }
  213. // Fill Addr back to dynamic table.
  214. DynTab.Content.modifyAddr(DynSymIndex, DynSym.Addr);
  215. DynTab.Content.modifyAddr(DynStrIndex, DynStr.Addr);
  216. // Write section headers of string tables.
  217. fillSymTabShdr(DynSym, SHT_DYNSYM);
  218. fillStrTabShdr(DynStr, SHF_ALLOC);
  219. fillDynTabShdr(DynTab);
  220. fillStrTabShdr(ShStrTab);
  221. // Finish initializing the ELF header.
  222. initELFHeader<ELFT>(ElfHeader, static_cast<uint16_t>(*Stub.Target.Arch));
  223. ElfHeader.e_shstrndx = ShStrTab.Index;
  224. ElfHeader.e_shnum = LastSection->Index + 1;
  225. ElfHeader.e_shoff =
  226. alignTo(LastSection->Offset + LastSection->Size, sizeof(Elf_Addr));
  227. }
  228. size_t getSize() const {
  229. return ElfHeader.e_shoff + ElfHeader.e_shnum * sizeof(Elf_Shdr);
  230. }
  231. void write(uint8_t *Data) const {
  232. write(Data, ElfHeader);
  233. DynSym.Content.write(Data + DynSym.Shdr.sh_offset);
  234. DynStr.Content.write(Data + DynStr.Shdr.sh_offset);
  235. DynTab.Content.write(Data + DynTab.Shdr.sh_offset);
  236. ShStrTab.Content.write(Data + ShStrTab.Shdr.sh_offset);
  237. writeShdr(Data, DynSym);
  238. writeShdr(Data, DynStr);
  239. writeShdr(Data, DynTab);
  240. writeShdr(Data, ShStrTab);
  241. }
  242. private:
  243. Elf_Ehdr ElfHeader;
  244. ContentSection<ELFStringTableBuilder, ELFT> DynStr;
  245. ContentSection<ELFStringTableBuilder, ELFT> ShStrTab;
  246. ContentSection<ELFSymbolTableBuilder<ELFT>, ELFT> DynSym;
  247. ContentSection<ELFDynamicTableBuilder<ELFT>, ELFT> DynTab;
  248. template <class T> static void write(uint8_t *Data, const T &Value) {
  249. *reinterpret_cast<T *>(Data) = Value;
  250. }
  251. void fillStrTabShdr(ContentSection<ELFStringTableBuilder, ELFT> &StrTab,
  252. uint32_t ShFlags = 0) const {
  253. StrTab.Shdr.sh_type = SHT_STRTAB;
  254. StrTab.Shdr.sh_flags = ShFlags;
  255. StrTab.Shdr.sh_addr = StrTab.Addr;
  256. StrTab.Shdr.sh_offset = StrTab.Offset;
  257. StrTab.Shdr.sh_info = 0;
  258. StrTab.Shdr.sh_size = StrTab.Size;
  259. StrTab.Shdr.sh_name = ShStrTab.Content.getOffset(StrTab.Name);
  260. StrTab.Shdr.sh_addralign = StrTab.Align;
  261. StrTab.Shdr.sh_entsize = 0;
  262. StrTab.Shdr.sh_link = 0;
  263. }
  264. void fillSymTabShdr(ContentSection<ELFSymbolTableBuilder<ELFT>, ELFT> &SymTab,
  265. uint32_t ShType) const {
  266. SymTab.Shdr.sh_type = ShType;
  267. SymTab.Shdr.sh_flags = SHF_ALLOC;
  268. SymTab.Shdr.sh_addr = SymTab.Addr;
  269. SymTab.Shdr.sh_offset = SymTab.Offset;
  270. // Only non-local symbols are included in the tbe file, so .dynsym only
  271. // contains 1 local symbol (the undefined symbol at index 0). The sh_info
  272. // should always be 1.
  273. SymTab.Shdr.sh_info = 1;
  274. SymTab.Shdr.sh_size = SymTab.Size;
  275. SymTab.Shdr.sh_name = this->ShStrTab.Content.getOffset(SymTab.Name);
  276. SymTab.Shdr.sh_addralign = SymTab.Align;
  277. SymTab.Shdr.sh_entsize = sizeof(Elf_Sym);
  278. SymTab.Shdr.sh_link = this->DynStr.Index;
  279. }
  280. void fillDynTabShdr(
  281. ContentSection<ELFDynamicTableBuilder<ELFT>, ELFT> &DynTab) const {
  282. DynTab.Shdr.sh_type = SHT_DYNAMIC;
  283. DynTab.Shdr.sh_flags = SHF_ALLOC;
  284. DynTab.Shdr.sh_addr = DynTab.Addr;
  285. DynTab.Shdr.sh_offset = DynTab.Offset;
  286. DynTab.Shdr.sh_info = 0;
  287. DynTab.Shdr.sh_size = DynTab.Size;
  288. DynTab.Shdr.sh_name = this->ShStrTab.Content.getOffset(DynTab.Name);
  289. DynTab.Shdr.sh_addralign = DynTab.Align;
  290. DynTab.Shdr.sh_entsize = sizeof(Elf_Dyn);
  291. DynTab.Shdr.sh_link = this->DynStr.Index;
  292. }
  293. uint64_t shdrOffset(const OutputSection<ELFT> &Sec) const {
  294. return ElfHeader.e_shoff + Sec.Index * sizeof(Elf_Shdr);
  295. }
  296. void writeShdr(uint8_t *Data, const OutputSection<ELFT> &Sec) const {
  297. write(Data + shdrOffset(Sec), Sec.Shdr);
  298. }
  299. };
  300. /// This function takes an error, and appends a string of text to the end of
  301. /// that error. Since "appending" to an Error isn't supported behavior of an
  302. /// Error, this function technically creates a new error with the combined
  303. /// message and consumes the old error.
  304. ///
  305. /// @param Err Source error.
  306. /// @param After Text to append at the end of Err's error message.
  307. Error appendToError(Error Err, StringRef After) {
  308. std::string Message;
  309. raw_string_ostream Stream(Message);
  310. Stream << Err;
  311. Stream << " " << After;
  312. consumeError(std::move(Err));
  313. return createError(Stream.str());
  314. }
  315. template <class ELFT> class DynSym {
  316. using Elf_Shdr_Range = typename ELFT::ShdrRange;
  317. using Elf_Shdr = typename ELFT::Shdr;
  318. public:
  319. static Expected<DynSym> create(const ELFFile<ELFT> &ElfFile,
  320. const DynamicEntries &DynEnt) {
  321. Expected<Elf_Shdr_Range> Shdrs = ElfFile.sections();
  322. if (!Shdrs)
  323. return Shdrs.takeError();
  324. return DynSym(ElfFile, DynEnt, *Shdrs);
  325. }
  326. Expected<const uint8_t *> getDynSym() {
  327. if (DynSymHdr)
  328. return ElfFile.base() + DynSymHdr->sh_offset;
  329. return getDynamicData(DynEnt.DynSymAddr, "dynamic symbol table");
  330. }
  331. Expected<StringRef> getDynStr() {
  332. if (DynSymHdr)
  333. return ElfFile.getStringTableForSymtab(*DynSymHdr, Shdrs);
  334. Expected<const uint8_t *> DataOrErr = getDynamicData(
  335. DynEnt.StrTabAddr, "dynamic string table", DynEnt.StrSize);
  336. if (!DataOrErr)
  337. return DataOrErr.takeError();
  338. return StringRef(reinterpret_cast<const char *>(*DataOrErr),
  339. DynEnt.StrSize);
  340. }
  341. private:
  342. DynSym(const ELFFile<ELFT> &ElfFile, const DynamicEntries &DynEnt,
  343. Elf_Shdr_Range Shdrs)
  344. : ElfFile(ElfFile), DynEnt(DynEnt), Shdrs(Shdrs),
  345. DynSymHdr(findDynSymHdr()) {}
  346. const Elf_Shdr *findDynSymHdr() {
  347. for (const Elf_Shdr &Sec : Shdrs)
  348. if (Sec.sh_type == SHT_DYNSYM) {
  349. // If multiple .dynsym are present, use the first one.
  350. // This behavior aligns with llvm::object::ELFFile::getDynSymtabSize()
  351. return &Sec;
  352. }
  353. return nullptr;
  354. }
  355. Expected<const uint8_t *> getDynamicData(uint64_t EntAddr, StringRef Name,
  356. uint64_t Size = 0) {
  357. Expected<const uint8_t *> SecPtr = ElfFile.toMappedAddr(EntAddr);
  358. if (!SecPtr)
  359. return appendToError(
  360. SecPtr.takeError(),
  361. ("when locating " + Name + " section contents").str());
  362. Expected<const uint8_t *> SecEndPtr = ElfFile.toMappedAddr(EntAddr + Size);
  363. if (!SecEndPtr)
  364. return appendToError(
  365. SecEndPtr.takeError(),
  366. ("when locating " + Name + " section contents").str());
  367. return *SecPtr;
  368. }
  369. const ELFFile<ELFT> &ElfFile;
  370. const DynamicEntries &DynEnt;
  371. Elf_Shdr_Range Shdrs;
  372. const Elf_Shdr *DynSymHdr;
  373. };
  374. } // end anonymous namespace
  375. /// This function behaves similarly to StringRef::substr(), but attempts to
  376. /// terminate the returned StringRef at the first null terminator. If no null
  377. /// terminator is found, an error is returned.
  378. ///
  379. /// @param Str Source string to create a substring from.
  380. /// @param Offset The start index of the desired substring.
  381. static Expected<StringRef> terminatedSubstr(StringRef Str, size_t Offset) {
  382. size_t StrEnd = Str.find('\0', Offset);
  383. if (StrEnd == StringLiteral::npos) {
  384. return createError(
  385. "String overran bounds of string table (no null terminator)");
  386. }
  387. size_t StrLen = StrEnd - Offset;
  388. return Str.substr(Offset, StrLen);
  389. }
  390. /// This function populates a DynamicEntries struct using an ELFT::DynRange.
  391. /// After populating the struct, the members are validated with
  392. /// some basic correctness checks.
  393. ///
  394. /// @param Dyn Target DynamicEntries struct to populate.
  395. /// @param DynTable Source dynamic table.
  396. template <class ELFT>
  397. static Error populateDynamic(DynamicEntries &Dyn,
  398. typename ELFT::DynRange DynTable) {
  399. if (DynTable.empty())
  400. return createError("No .dynamic section found");
  401. // Search .dynamic for relevant entries.
  402. bool FoundDynStr = false;
  403. bool FoundDynStrSz = false;
  404. bool FoundDynSym = false;
  405. for (auto &Entry : DynTable) {
  406. switch (Entry.d_tag) {
  407. case DT_SONAME:
  408. Dyn.SONameOffset = Entry.d_un.d_val;
  409. break;
  410. case DT_STRTAB:
  411. Dyn.StrTabAddr = Entry.d_un.d_ptr;
  412. FoundDynStr = true;
  413. break;
  414. case DT_STRSZ:
  415. Dyn.StrSize = Entry.d_un.d_val;
  416. FoundDynStrSz = true;
  417. break;
  418. case DT_NEEDED:
  419. Dyn.NeededLibNames.push_back(Entry.d_un.d_val);
  420. break;
  421. case DT_SYMTAB:
  422. Dyn.DynSymAddr = Entry.d_un.d_ptr;
  423. FoundDynSym = true;
  424. break;
  425. case DT_HASH:
  426. Dyn.ElfHash = Entry.d_un.d_ptr;
  427. break;
  428. case DT_GNU_HASH:
  429. Dyn.GnuHash = Entry.d_un.d_ptr;
  430. }
  431. }
  432. if (!FoundDynStr) {
  433. return createError(
  434. "Couldn't locate dynamic string table (no DT_STRTAB entry)");
  435. }
  436. if (!FoundDynStrSz) {
  437. return createError(
  438. "Couldn't determine dynamic string table size (no DT_STRSZ entry)");
  439. }
  440. if (!FoundDynSym) {
  441. return createError(
  442. "Couldn't locate dynamic symbol table (no DT_SYMTAB entry)");
  443. }
  444. if (Dyn.SONameOffset && *Dyn.SONameOffset >= Dyn.StrSize) {
  445. return createStringError(object_error::parse_failed,
  446. "DT_SONAME string offset (0x%016" PRIx64
  447. ") outside of dynamic string table",
  448. *Dyn.SONameOffset);
  449. }
  450. for (uint64_t Offset : Dyn.NeededLibNames) {
  451. if (Offset >= Dyn.StrSize) {
  452. return createStringError(object_error::parse_failed,
  453. "DT_NEEDED string offset (0x%016" PRIx64
  454. ") outside of dynamic string table",
  455. Offset);
  456. }
  457. }
  458. return Error::success();
  459. }
  460. /// This function creates an IFSSymbol and populates all members using
  461. /// information from a binary ELFT::Sym.
  462. ///
  463. /// @param SymName The desired name of the IFSSymbol.
  464. /// @param RawSym ELFT::Sym to extract symbol information from.
  465. template <class ELFT>
  466. static IFSSymbol createELFSym(StringRef SymName,
  467. const typename ELFT::Sym &RawSym) {
  468. IFSSymbol TargetSym{std::string(SymName)};
  469. uint8_t Binding = RawSym.getBinding();
  470. if (Binding == STB_WEAK)
  471. TargetSym.Weak = true;
  472. else
  473. TargetSym.Weak = false;
  474. TargetSym.Undefined = RawSym.isUndefined();
  475. TargetSym.Type = convertELFSymbolTypeToIFS(RawSym.st_info);
  476. if (TargetSym.Type == IFSSymbolType::Func) {
  477. TargetSym.Size = 0;
  478. } else {
  479. TargetSym.Size = RawSym.st_size;
  480. }
  481. return TargetSym;
  482. }
  483. /// This function populates an IFSStub with symbols using information read
  484. /// from an ELF binary.
  485. ///
  486. /// @param TargetStub IFSStub to add symbols to.
  487. /// @param DynSym Range of dynamic symbols to add to TargetStub.
  488. /// @param DynStr StringRef to the dynamic string table.
  489. template <class ELFT>
  490. static Error populateSymbols(IFSStub &TargetStub,
  491. const typename ELFT::SymRange DynSym,
  492. StringRef DynStr) {
  493. // Skips the first symbol since it's the NULL symbol.
  494. for (auto RawSym : DynSym.drop_front(1)) {
  495. // If a symbol does not have global or weak binding, ignore it.
  496. uint8_t Binding = RawSym.getBinding();
  497. if (!(Binding == STB_GLOBAL || Binding == STB_WEAK))
  498. continue;
  499. // If a symbol doesn't have default or protected visibility, ignore it.
  500. uint8_t Visibility = RawSym.getVisibility();
  501. if (!(Visibility == STV_DEFAULT || Visibility == STV_PROTECTED))
  502. continue;
  503. // Create an IFSSymbol and populate it with information from the symbol
  504. // table entry.
  505. Expected<StringRef> SymName = terminatedSubstr(DynStr, RawSym.st_name);
  506. if (!SymName)
  507. return SymName.takeError();
  508. IFSSymbol Sym = createELFSym<ELFT>(*SymName, RawSym);
  509. TargetStub.Symbols.push_back(std::move(Sym));
  510. // TODO: Populate symbol warning.
  511. }
  512. return Error::success();
  513. }
  514. /// Returns a new IFSStub with all members populated from an ELFObjectFile.
  515. /// @param ElfObj Source ELFObjectFile.
  516. template <class ELFT>
  517. static Expected<std::unique_ptr<IFSStub>>
  518. buildStub(const ELFObjectFile<ELFT> &ElfObj) {
  519. using Elf_Dyn_Range = typename ELFT::DynRange;
  520. using Elf_Sym_Range = typename ELFT::SymRange;
  521. using Elf_Sym = typename ELFT::Sym;
  522. std::unique_ptr<IFSStub> DestStub = std::make_unique<IFSStub>();
  523. const ELFFile<ELFT> &ElfFile = ElfObj.getELFFile();
  524. // Fetch .dynamic table.
  525. Expected<Elf_Dyn_Range> DynTable = ElfFile.dynamicEntries();
  526. if (!DynTable) {
  527. return DynTable.takeError();
  528. }
  529. // Collect relevant .dynamic entries.
  530. DynamicEntries DynEnt;
  531. if (Error Err = populateDynamic<ELFT>(DynEnt, *DynTable))
  532. return std::move(Err);
  533. Expected<DynSym<ELFT>> EDynSym = DynSym<ELFT>::create(ElfFile, DynEnt);
  534. if (!EDynSym)
  535. return EDynSym.takeError();
  536. Expected<StringRef> EDynStr = EDynSym->getDynStr();
  537. if (!EDynStr)
  538. return EDynStr.takeError();
  539. StringRef DynStr = *EDynStr;
  540. // Populate Arch from ELF header.
  541. DestStub->Target.Arch = static_cast<IFSArch>(ElfFile.getHeader().e_machine);
  542. DestStub->Target.BitWidth =
  543. convertELFBitWidthToIFS(ElfFile.getHeader().e_ident[EI_CLASS]);
  544. DestStub->Target.Endianness =
  545. convertELFEndiannessToIFS(ElfFile.getHeader().e_ident[EI_DATA]);
  546. DestStub->Target.ObjectFormat = "ELF";
  547. // Populate SoName from .dynamic entries and dynamic string table.
  548. if (DynEnt.SONameOffset) {
  549. Expected<StringRef> NameOrErr =
  550. terminatedSubstr(DynStr, *DynEnt.SONameOffset);
  551. if (!NameOrErr) {
  552. return appendToError(NameOrErr.takeError(), "when reading DT_SONAME");
  553. }
  554. DestStub->SoName = std::string(*NameOrErr);
  555. }
  556. // Populate NeededLibs from .dynamic entries and dynamic string table.
  557. for (uint64_t NeededStrOffset : DynEnt.NeededLibNames) {
  558. Expected<StringRef> LibNameOrErr =
  559. terminatedSubstr(DynStr, NeededStrOffset);
  560. if (!LibNameOrErr) {
  561. return appendToError(LibNameOrErr.takeError(), "when reading DT_NEEDED");
  562. }
  563. DestStub->NeededLibs.push_back(std::string(*LibNameOrErr));
  564. }
  565. // Populate Symbols from .dynsym table and dynamic string table.
  566. Expected<uint64_t> SymCount = ElfFile.getDynSymtabSize();
  567. if (!SymCount)
  568. return SymCount.takeError();
  569. if (*SymCount > 0) {
  570. // Get pointer to in-memory location of .dynsym section.
  571. Expected<const uint8_t *> DynSymPtr = EDynSym->getDynSym();
  572. if (!DynSymPtr)
  573. return appendToError(DynSymPtr.takeError(),
  574. "when locating .dynsym section contents");
  575. Elf_Sym_Range DynSyms = ArrayRef<Elf_Sym>(
  576. reinterpret_cast<const Elf_Sym *>(*DynSymPtr), *SymCount);
  577. Error SymReadError = populateSymbols<ELFT>(*DestStub, DynSyms, DynStr);
  578. if (SymReadError)
  579. return appendToError(std::move(SymReadError),
  580. "when reading dynamic symbols");
  581. }
  582. return std::move(DestStub);
  583. }
  584. /// This function opens a file for writing and then writes a binary ELF stub to
  585. /// the file.
  586. ///
  587. /// @param FilePath File path for writing the ELF binary.
  588. /// @param Stub Source InterFace Stub to generate a binary ELF stub from.
  589. template <class ELFT>
  590. static Error writeELFBinaryToFile(StringRef FilePath, const IFSStub &Stub,
  591. bool WriteIfChanged) {
  592. ELFStubBuilder<ELFT> Builder{Stub};
  593. // Write Stub to memory first.
  594. std::vector<uint8_t> Buf(Builder.getSize());
  595. Builder.write(Buf.data());
  596. if (WriteIfChanged) {
  597. if (ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrError =
  598. MemoryBuffer::getFile(FilePath)) {
  599. // Compare Stub output with existing Stub file.
  600. // If Stub file unchanged, abort updating.
  601. if ((*BufOrError)->getBufferSize() == Builder.getSize() &&
  602. !memcmp((*BufOrError)->getBufferStart(), Buf.data(),
  603. Builder.getSize()))
  604. return Error::success();
  605. }
  606. }
  607. Expected<std::unique_ptr<FileOutputBuffer>> BufOrError =
  608. FileOutputBuffer::create(FilePath, Builder.getSize());
  609. if (!BufOrError)
  610. return createStringError(errc::invalid_argument,
  611. toString(BufOrError.takeError()) +
  612. " when trying to open `" + FilePath +
  613. "` for writing");
  614. // Write binary to file.
  615. std::unique_ptr<FileOutputBuffer> FileBuf = std::move(*BufOrError);
  616. memcpy(FileBuf->getBufferStart(), Buf.data(), Buf.size());
  617. return FileBuf->commit();
  618. }
  619. Expected<std::unique_ptr<IFSStub>> readELFFile(MemoryBufferRef Buf) {
  620. Expected<std::unique_ptr<Binary>> BinOrErr = createBinary(Buf);
  621. if (!BinOrErr) {
  622. return BinOrErr.takeError();
  623. }
  624. Binary *Bin = BinOrErr->get();
  625. if (auto Obj = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) {
  626. return buildStub(*Obj);
  627. } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) {
  628. return buildStub(*Obj);
  629. } else if (auto Obj = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) {
  630. return buildStub(*Obj);
  631. } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) {
  632. return buildStub(*Obj);
  633. }
  634. return createStringError(errc::not_supported, "unsupported binary format");
  635. }
  636. // This function wraps the ELFT writeELFBinaryToFile() so writeBinaryStub()
  637. // can be called without having to use ELFType templates directly.
  638. Error writeBinaryStub(StringRef FilePath, const IFSStub &Stub,
  639. bool WriteIfChanged) {
  640. assert(Stub.Target.Arch);
  641. assert(Stub.Target.BitWidth);
  642. assert(Stub.Target.Endianness);
  643. if (Stub.Target.BitWidth == IFSBitWidthType::IFS32) {
  644. if (Stub.Target.Endianness == IFSEndiannessType::Little) {
  645. return writeELFBinaryToFile<ELF32LE>(FilePath, Stub, WriteIfChanged);
  646. } else {
  647. return writeELFBinaryToFile<ELF32BE>(FilePath, Stub, WriteIfChanged);
  648. }
  649. } else {
  650. if (Stub.Target.Endianness == IFSEndiannessType::Little) {
  651. return writeELFBinaryToFile<ELF64LE>(FilePath, Stub, WriteIfChanged);
  652. } else {
  653. return writeELFBinaryToFile<ELF64BE>(FilePath, Stub, WriteIfChanged);
  654. }
  655. }
  656. llvm_unreachable("invalid binary output target");
  657. }
  658. } // end namespace ifs
  659. } // end namespace llvm