ELF.h 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- ELF.h - ELF object file implementation -------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file declares the ELFFile template class.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_OBJECT_ELF_H
  18. #define LLVM_OBJECT_ELF_H
  19. #include "llvm/ADT/ArrayRef.h"
  20. #include "llvm/ADT/SmallString.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/BinaryFormat/ELF.h"
  24. #include "llvm/Object/ELFTypes.h"
  25. #include "llvm/Object/Error.h"
  26. #include "llvm/Support/Endian.h"
  27. #include "llvm/Support/Error.h"
  28. #include <cassert>
  29. #include <cstddef>
  30. #include <cstdint>
  31. #include <limits>
  32. #include <utility>
  33. namespace llvm {
  34. namespace object {
  35. struct VerdAux {
  36. unsigned Offset;
  37. std::string Name;
  38. };
  39. struct VerDef {
  40. unsigned Offset;
  41. unsigned Version;
  42. unsigned Flags;
  43. unsigned Ndx;
  44. unsigned Cnt;
  45. unsigned Hash;
  46. std::string Name;
  47. std::vector<VerdAux> AuxV;
  48. };
  49. struct VernAux {
  50. unsigned Hash;
  51. unsigned Flags;
  52. unsigned Other;
  53. unsigned Offset;
  54. std::string Name;
  55. };
  56. struct VerNeed {
  57. unsigned Version;
  58. unsigned Cnt;
  59. unsigned Offset;
  60. std::string File;
  61. std::vector<VernAux> AuxV;
  62. };
  63. struct VersionEntry {
  64. std::string Name;
  65. bool IsVerDef;
  66. };
  67. StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type);
  68. uint32_t getELFRelativeRelocationType(uint32_t Machine);
  69. StringRef getELFSectionTypeName(uint32_t Machine, uint32_t Type);
  70. // Subclasses of ELFFile may need this for template instantiation
  71. inline std::pair<unsigned char, unsigned char>
  72. getElfArchType(StringRef Object) {
  73. if (Object.size() < ELF::EI_NIDENT)
  74. return std::make_pair((uint8_t)ELF::ELFCLASSNONE,
  75. (uint8_t)ELF::ELFDATANONE);
  76. return std::make_pair((uint8_t)Object[ELF::EI_CLASS],
  77. (uint8_t)Object[ELF::EI_DATA]);
  78. }
  79. enum PPCInstrMasks : uint64_t {
  80. PADDI_R12_NO_DISP = 0x0610000039800000,
  81. ADDIS_R12_TO_R2_NO_DISP = 0x3D820000,
  82. ADDI_R12_TO_R2_NO_DISP = 0x39820000,
  83. ADDI_R12_TO_R12_NO_DISP = 0x398C0000,
  84. PLD_R12_NO_DISP = 0x04100000E5800000,
  85. MTCTR_R12 = 0x7D8903A6,
  86. BCTR = 0x4E800420,
  87. };
  88. template <class ELFT> class ELFFile;
  89. template <class T> struct DataRegion {
  90. // This constructor is used when we know the start and the size of a data
  91. // region. We assume that Arr does not go past the end of the file.
  92. DataRegion(ArrayRef<T> Arr) : First(Arr.data()), Size(Arr.size()) {}
  93. // Sometimes we only know the start of a data region. We still don't want to
  94. // read past the end of the file, so we provide the end of a buffer.
  95. DataRegion(const T *Data, const uint8_t *BufferEnd)
  96. : First(Data), BufEnd(BufferEnd) {}
  97. Expected<T> operator[](uint64_t N) {
  98. assert(Size || BufEnd);
  99. if (Size) {
  100. if (N >= *Size)
  101. return createError(
  102. "the index is greater than or equal to the number of entries (" +
  103. Twine(*Size) + ")");
  104. } else {
  105. const uint8_t *EntryStart = (const uint8_t *)First + N * sizeof(T);
  106. if (EntryStart + sizeof(T) > BufEnd)
  107. return createError("can't read past the end of the file");
  108. }
  109. return *(First + N);
  110. }
  111. const T *First;
  112. std::optional<uint64_t> Size;
  113. const uint8_t *BufEnd = nullptr;
  114. };
  115. template <class ELFT>
  116. std::string getSecIndexForError(const ELFFile<ELFT> &Obj,
  117. const typename ELFT::Shdr &Sec) {
  118. auto TableOrErr = Obj.sections();
  119. if (TableOrErr)
  120. return "[index " + std::to_string(&Sec - &TableOrErr->front()) + "]";
  121. // To make this helper be more convenient for error reporting purposes we
  122. // drop the error. But really it should never be triggered. Before this point,
  123. // our code should have called 'sections()' and reported a proper error on
  124. // failure.
  125. llvm::consumeError(TableOrErr.takeError());
  126. return "[unknown index]";
  127. }
  128. template <class ELFT>
  129. static std::string describe(const ELFFile<ELFT> &Obj,
  130. const typename ELFT::Shdr &Sec) {
  131. unsigned SecNdx = &Sec - &cantFail(Obj.sections()).front();
  132. return (object::getELFSectionTypeName(Obj.getHeader().e_machine,
  133. Sec.sh_type) +
  134. " section with index " + Twine(SecNdx))
  135. .str();
  136. }
  137. template <class ELFT>
  138. std::string getPhdrIndexForError(const ELFFile<ELFT> &Obj,
  139. const typename ELFT::Phdr &Phdr) {
  140. auto Headers = Obj.program_headers();
  141. if (Headers)
  142. return ("[index " + Twine(&Phdr - &Headers->front()) + "]").str();
  143. // See comment in the getSecIndexForError() above.
  144. llvm::consumeError(Headers.takeError());
  145. return "[unknown index]";
  146. }
  147. static inline Error defaultWarningHandler(const Twine &Msg) {
  148. return createError(Msg);
  149. }
  150. template <class ELFT>
  151. class ELFFile {
  152. public:
  153. LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
  154. // This is a callback that can be passed to a number of functions.
  155. // It can be used to ignore non-critical errors (warnings), which is
  156. // useful for dumpers, like llvm-readobj.
  157. // It accepts a warning message string and returns a success
  158. // when the warning should be ignored or an error otherwise.
  159. using WarningHandler = llvm::function_ref<Error(const Twine &Msg)>;
  160. const uint8_t *base() const { return Buf.bytes_begin(); }
  161. const uint8_t *end() const { return base() + getBufSize(); }
  162. size_t getBufSize() const { return Buf.size(); }
  163. private:
  164. StringRef Buf;
  165. std::vector<Elf_Shdr> FakeSections;
  166. SmallString<0> FakeSectionStrings;
  167. ELFFile(StringRef Object);
  168. public:
  169. const Elf_Ehdr &getHeader() const {
  170. return *reinterpret_cast<const Elf_Ehdr *>(base());
  171. }
  172. template <typename T>
  173. Expected<const T *> getEntry(uint32_t Section, uint32_t Entry) const;
  174. template <typename T>
  175. Expected<const T *> getEntry(const Elf_Shdr &Section, uint32_t Entry) const;
  176. Expected<std::vector<VerDef>>
  177. getVersionDefinitions(const Elf_Shdr &Sec) const;
  178. Expected<std::vector<VerNeed>> getVersionDependencies(
  179. const Elf_Shdr &Sec,
  180. WarningHandler WarnHandler = &defaultWarningHandler) const;
  181. Expected<StringRef> getSymbolVersionByIndex(
  182. uint32_t SymbolVersionIndex, bool &IsDefault,
  183. SmallVector<std::optional<VersionEntry>, 0> &VersionMap,
  184. std::optional<bool> IsSymHidden) const;
  185. Expected<StringRef>
  186. getStringTable(const Elf_Shdr &Section,
  187. WarningHandler WarnHandler = &defaultWarningHandler) const;
  188. Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section) const;
  189. Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section,
  190. Elf_Shdr_Range Sections) const;
  191. Expected<StringRef> getLinkAsStrtab(const typename ELFT::Shdr &Sec) const;
  192. Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section) const;
  193. Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section,
  194. Elf_Shdr_Range Sections) const;
  195. Expected<uint64_t> getDynSymtabSize() const;
  196. StringRef getRelocationTypeName(uint32_t Type) const;
  197. void getRelocationTypeName(uint32_t Type,
  198. SmallVectorImpl<char> &Result) const;
  199. uint32_t getRelativeRelocationType() const;
  200. std::string getDynamicTagAsString(unsigned Arch, uint64_t Type) const;
  201. std::string getDynamicTagAsString(uint64_t Type) const;
  202. /// Get the symbol for a given relocation.
  203. Expected<const Elf_Sym *> getRelocationSymbol(const Elf_Rel &Rel,
  204. const Elf_Shdr *SymTab) const;
  205. Expected<SmallVector<std::optional<VersionEntry>, 0>>
  206. loadVersionMap(const Elf_Shdr *VerNeedSec, const Elf_Shdr *VerDefSec) const;
  207. static Expected<ELFFile> create(StringRef Object);
  208. bool isLE() const {
  209. return getHeader().getDataEncoding() == ELF::ELFDATA2LSB;
  210. }
  211. bool isMipsELF64() const {
  212. return getHeader().e_machine == ELF::EM_MIPS &&
  213. getHeader().getFileClass() == ELF::ELFCLASS64;
  214. }
  215. bool isMips64EL() const { return isMipsELF64() && isLE(); }
  216. Expected<Elf_Shdr_Range> sections() const;
  217. Expected<Elf_Dyn_Range> dynamicEntries() const;
  218. Expected<const uint8_t *>
  219. toMappedAddr(uint64_t VAddr,
  220. WarningHandler WarnHandler = &defaultWarningHandler) const;
  221. Expected<Elf_Sym_Range> symbols(const Elf_Shdr *Sec) const {
  222. if (!Sec)
  223. return ArrayRef<Elf_Sym>(nullptr, nullptr);
  224. return getSectionContentsAsArray<Elf_Sym>(*Sec);
  225. }
  226. Expected<Elf_Rela_Range> relas(const Elf_Shdr &Sec) const {
  227. return getSectionContentsAsArray<Elf_Rela>(Sec);
  228. }
  229. Expected<Elf_Rel_Range> rels(const Elf_Shdr &Sec) const {
  230. return getSectionContentsAsArray<Elf_Rel>(Sec);
  231. }
  232. Expected<Elf_Relr_Range> relrs(const Elf_Shdr &Sec) const {
  233. return getSectionContentsAsArray<Elf_Relr>(Sec);
  234. }
  235. std::vector<Elf_Rel> decode_relrs(Elf_Relr_Range relrs) const;
  236. Expected<std::vector<Elf_Rela>> android_relas(const Elf_Shdr &Sec) const;
  237. /// Iterate over program header table.
  238. Expected<Elf_Phdr_Range> program_headers() const {
  239. if (getHeader().e_phnum && getHeader().e_phentsize != sizeof(Elf_Phdr))
  240. return createError("invalid e_phentsize: " +
  241. Twine(getHeader().e_phentsize));
  242. uint64_t HeadersSize =
  243. (uint64_t)getHeader().e_phnum * getHeader().e_phentsize;
  244. uint64_t PhOff = getHeader().e_phoff;
  245. if (PhOff + HeadersSize < PhOff || PhOff + HeadersSize > getBufSize())
  246. return createError("program headers are longer than binary of size " +
  247. Twine(getBufSize()) + ": e_phoff = 0x" +
  248. Twine::utohexstr(getHeader().e_phoff) +
  249. ", e_phnum = " + Twine(getHeader().e_phnum) +
  250. ", e_phentsize = " + Twine(getHeader().e_phentsize));
  251. auto *Begin = reinterpret_cast<const Elf_Phdr *>(base() + PhOff);
  252. return ArrayRef(Begin, Begin + getHeader().e_phnum);
  253. }
  254. /// Get an iterator over notes in a program header.
  255. ///
  256. /// The program header must be of type \c PT_NOTE.
  257. ///
  258. /// \param Phdr the program header to iterate over.
  259. /// \param Err [out] an error to support fallible iteration, which should
  260. /// be checked after iteration ends.
  261. Elf_Note_Iterator notes_begin(const Elf_Phdr &Phdr, Error &Err) const {
  262. assert(Phdr.p_type == ELF::PT_NOTE && "Phdr is not of type PT_NOTE");
  263. ErrorAsOutParameter ErrAsOutParam(&Err);
  264. if (Phdr.p_offset + Phdr.p_filesz > getBufSize()) {
  265. Err =
  266. createError("invalid offset (0x" + Twine::utohexstr(Phdr.p_offset) +
  267. ") or size (0x" + Twine::utohexstr(Phdr.p_filesz) + ")");
  268. return Elf_Note_Iterator(Err);
  269. }
  270. return Elf_Note_Iterator(base() + Phdr.p_offset, Phdr.p_filesz, Err);
  271. }
  272. /// Get an iterator over notes in a section.
  273. ///
  274. /// The section must be of type \c SHT_NOTE.
  275. ///
  276. /// \param Shdr the section to iterate over.
  277. /// \param Err [out] an error to support fallible iteration, which should
  278. /// be checked after iteration ends.
  279. Elf_Note_Iterator notes_begin(const Elf_Shdr &Shdr, Error &Err) const {
  280. assert(Shdr.sh_type == ELF::SHT_NOTE && "Shdr is not of type SHT_NOTE");
  281. ErrorAsOutParameter ErrAsOutParam(&Err);
  282. if (Shdr.sh_offset + Shdr.sh_size > getBufSize()) {
  283. Err =
  284. createError("invalid offset (0x" + Twine::utohexstr(Shdr.sh_offset) +
  285. ") or size (0x" + Twine::utohexstr(Shdr.sh_size) + ")");
  286. return Elf_Note_Iterator(Err);
  287. }
  288. return Elf_Note_Iterator(base() + Shdr.sh_offset, Shdr.sh_size, Err);
  289. }
  290. /// Get the end iterator for notes.
  291. Elf_Note_Iterator notes_end() const {
  292. return Elf_Note_Iterator();
  293. }
  294. /// Get an iterator range over notes of a program header.
  295. ///
  296. /// The program header must be of type \c PT_NOTE.
  297. ///
  298. /// \param Phdr the program header to iterate over.
  299. /// \param Err [out] an error to support fallible iteration, which should
  300. /// be checked after iteration ends.
  301. iterator_range<Elf_Note_Iterator> notes(const Elf_Phdr &Phdr,
  302. Error &Err) const {
  303. return make_range(notes_begin(Phdr, Err), notes_end());
  304. }
  305. /// Get an iterator range over notes of a section.
  306. ///
  307. /// The section must be of type \c SHT_NOTE.
  308. ///
  309. /// \param Shdr the section to iterate over.
  310. /// \param Err [out] an error to support fallible iteration, which should
  311. /// be checked after iteration ends.
  312. iterator_range<Elf_Note_Iterator> notes(const Elf_Shdr &Shdr,
  313. Error &Err) const {
  314. return make_range(notes_begin(Shdr, Err), notes_end());
  315. }
  316. Expected<StringRef> getSectionStringTable(
  317. Elf_Shdr_Range Sections,
  318. WarningHandler WarnHandler = &defaultWarningHandler) const;
  319. Expected<uint32_t> getSectionIndex(const Elf_Sym &Sym, Elf_Sym_Range Syms,
  320. DataRegion<Elf_Word> ShndxTable) const;
  321. Expected<const Elf_Shdr *> getSection(const Elf_Sym &Sym,
  322. const Elf_Shdr *SymTab,
  323. DataRegion<Elf_Word> ShndxTable) const;
  324. Expected<const Elf_Shdr *> getSection(const Elf_Sym &Sym,
  325. Elf_Sym_Range Symtab,
  326. DataRegion<Elf_Word> ShndxTable) const;
  327. Expected<const Elf_Shdr *> getSection(uint32_t Index) const;
  328. Expected<const Elf_Sym *> getSymbol(const Elf_Shdr *Sec,
  329. uint32_t Index) const;
  330. Expected<StringRef>
  331. getSectionName(const Elf_Shdr &Section,
  332. WarningHandler WarnHandler = &defaultWarningHandler) const;
  333. Expected<StringRef> getSectionName(const Elf_Shdr &Section,
  334. StringRef DotShstrtab) const;
  335. template <typename T>
  336. Expected<ArrayRef<T>> getSectionContentsAsArray(const Elf_Shdr &Sec) const;
  337. Expected<ArrayRef<uint8_t>> getSectionContents(const Elf_Shdr &Sec) const;
  338. Expected<ArrayRef<uint8_t>> getSegmentContents(const Elf_Phdr &Phdr) const;
  339. Expected<std::vector<BBAddrMap>> decodeBBAddrMap(const Elf_Shdr &Sec) const;
  340. void createFakeSections();
  341. };
  342. using ELF32LEFile = ELFFile<ELF32LE>;
  343. using ELF64LEFile = ELFFile<ELF64LE>;
  344. using ELF32BEFile = ELFFile<ELF32BE>;
  345. using ELF64BEFile = ELFFile<ELF64BE>;
  346. template <class ELFT>
  347. inline Expected<const typename ELFT::Shdr *>
  348. getSection(typename ELFT::ShdrRange Sections, uint32_t Index) {
  349. if (Index >= Sections.size())
  350. return createError("invalid section index: " + Twine(Index));
  351. return &Sections[Index];
  352. }
  353. template <class ELFT>
  354. inline Expected<uint32_t>
  355. getExtendedSymbolTableIndex(const typename ELFT::Sym &Sym, unsigned SymIndex,
  356. DataRegion<typename ELFT::Word> ShndxTable) {
  357. assert(Sym.st_shndx == ELF::SHN_XINDEX);
  358. if (!ShndxTable.First)
  359. return createError(
  360. "found an extended symbol index (" + Twine(SymIndex) +
  361. "), but unable to locate the extended symbol index table");
  362. Expected<typename ELFT::Word> TableOrErr = ShndxTable[SymIndex];
  363. if (!TableOrErr)
  364. return createError("unable to read an extended symbol table at index " +
  365. Twine(SymIndex) + ": " +
  366. toString(TableOrErr.takeError()));
  367. return *TableOrErr;
  368. }
  369. template <class ELFT>
  370. Expected<uint32_t>
  371. ELFFile<ELFT>::getSectionIndex(const Elf_Sym &Sym, Elf_Sym_Range Syms,
  372. DataRegion<Elf_Word> ShndxTable) const {
  373. uint32_t Index = Sym.st_shndx;
  374. if (Index == ELF::SHN_XINDEX) {
  375. Expected<uint32_t> ErrorOrIndex =
  376. getExtendedSymbolTableIndex<ELFT>(Sym, &Sym - Syms.begin(), ShndxTable);
  377. if (!ErrorOrIndex)
  378. return ErrorOrIndex.takeError();
  379. return *ErrorOrIndex;
  380. }
  381. if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
  382. return 0;
  383. return Index;
  384. }
  385. template <class ELFT>
  386. Expected<const typename ELFT::Shdr *>
  387. ELFFile<ELFT>::getSection(const Elf_Sym &Sym, const Elf_Shdr *SymTab,
  388. DataRegion<Elf_Word> ShndxTable) const {
  389. auto SymsOrErr = symbols(SymTab);
  390. if (!SymsOrErr)
  391. return SymsOrErr.takeError();
  392. return getSection(Sym, *SymsOrErr, ShndxTable);
  393. }
  394. template <class ELFT>
  395. Expected<const typename ELFT::Shdr *>
  396. ELFFile<ELFT>::getSection(const Elf_Sym &Sym, Elf_Sym_Range Symbols,
  397. DataRegion<Elf_Word> ShndxTable) const {
  398. auto IndexOrErr = getSectionIndex(Sym, Symbols, ShndxTable);
  399. if (!IndexOrErr)
  400. return IndexOrErr.takeError();
  401. uint32_t Index = *IndexOrErr;
  402. if (Index == 0)
  403. return nullptr;
  404. return getSection(Index);
  405. }
  406. template <class ELFT>
  407. Expected<const typename ELFT::Sym *>
  408. ELFFile<ELFT>::getSymbol(const Elf_Shdr *Sec, uint32_t Index) const {
  409. auto SymsOrErr = symbols(Sec);
  410. if (!SymsOrErr)
  411. return SymsOrErr.takeError();
  412. Elf_Sym_Range Symbols = *SymsOrErr;
  413. if (Index >= Symbols.size())
  414. return createError("unable to get symbol from section " +
  415. getSecIndexForError(*this, *Sec) +
  416. ": invalid symbol index (" + Twine(Index) + ")");
  417. return &Symbols[Index];
  418. }
  419. template <class ELFT>
  420. template <typename T>
  421. Expected<ArrayRef<T>>
  422. ELFFile<ELFT>::getSectionContentsAsArray(const Elf_Shdr &Sec) const {
  423. if (Sec.sh_entsize != sizeof(T) && sizeof(T) != 1)
  424. return createError("section " + getSecIndexForError(*this, Sec) +
  425. " has invalid sh_entsize: expected " + Twine(sizeof(T)) +
  426. ", but got " + Twine(Sec.sh_entsize));
  427. uintX_t Offset = Sec.sh_offset;
  428. uintX_t Size = Sec.sh_size;
  429. if (Size % sizeof(T))
  430. return createError("section " + getSecIndexForError(*this, Sec) +
  431. " has an invalid sh_size (" + Twine(Size) +
  432. ") which is not a multiple of its sh_entsize (" +
  433. Twine(Sec.sh_entsize) + ")");
  434. if (std::numeric_limits<uintX_t>::max() - Offset < Size)
  435. return createError("section " + getSecIndexForError(*this, Sec) +
  436. " has a sh_offset (0x" + Twine::utohexstr(Offset) +
  437. ") + sh_size (0x" + Twine::utohexstr(Size) +
  438. ") that cannot be represented");
  439. if (Offset + Size > Buf.size())
  440. return createError("section " + getSecIndexForError(*this, Sec) +
  441. " has a sh_offset (0x" + Twine::utohexstr(Offset) +
  442. ") + sh_size (0x" + Twine::utohexstr(Size) +
  443. ") that is greater than the file size (0x" +
  444. Twine::utohexstr(Buf.size()) + ")");
  445. if (Offset % alignof(T))
  446. // TODO: this error is untested.
  447. return createError("unaligned data");
  448. const T *Start = reinterpret_cast<const T *>(base() + Offset);
  449. return ArrayRef(Start, Size / sizeof(T));
  450. }
  451. template <class ELFT>
  452. Expected<ArrayRef<uint8_t>>
  453. ELFFile<ELFT>::getSegmentContents(const Elf_Phdr &Phdr) const {
  454. uintX_t Offset = Phdr.p_offset;
  455. uintX_t Size = Phdr.p_filesz;
  456. if (std::numeric_limits<uintX_t>::max() - Offset < Size)
  457. return createError("program header " + getPhdrIndexForError(*this, Phdr) +
  458. " has a p_offset (0x" + Twine::utohexstr(Offset) +
  459. ") + p_filesz (0x" + Twine::utohexstr(Size) +
  460. ") that cannot be represented");
  461. if (Offset + Size > Buf.size())
  462. return createError("program header " + getPhdrIndexForError(*this, Phdr) +
  463. " has a p_offset (0x" + Twine::utohexstr(Offset) +
  464. ") + p_filesz (0x" + Twine::utohexstr(Size) +
  465. ") that is greater than the file size (0x" +
  466. Twine::utohexstr(Buf.size()) + ")");
  467. return ArrayRef(base() + Offset, Size);
  468. }
  469. template <class ELFT>
  470. Expected<ArrayRef<uint8_t>>
  471. ELFFile<ELFT>::getSectionContents(const Elf_Shdr &Sec) const {
  472. return getSectionContentsAsArray<uint8_t>(Sec);
  473. }
  474. template <class ELFT>
  475. StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
  476. return getELFRelocationTypeName(getHeader().e_machine, Type);
  477. }
  478. template <class ELFT>
  479. void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
  480. SmallVectorImpl<char> &Result) const {
  481. if (!isMipsELF64()) {
  482. StringRef Name = getRelocationTypeName(Type);
  483. Result.append(Name.begin(), Name.end());
  484. } else {
  485. // The Mips N64 ABI allows up to three operations to be specified per
  486. // relocation record. Unfortunately there's no easy way to test for the
  487. // presence of N64 ELFs as they have no special flag that identifies them
  488. // as being N64. We can safely assume at the moment that all Mips
  489. // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
  490. // information to disambiguate between old vs new ABIs.
  491. uint8_t Type1 = (Type >> 0) & 0xFF;
  492. uint8_t Type2 = (Type >> 8) & 0xFF;
  493. uint8_t Type3 = (Type >> 16) & 0xFF;
  494. // Concat all three relocation type names.
  495. StringRef Name = getRelocationTypeName(Type1);
  496. Result.append(Name.begin(), Name.end());
  497. Name = getRelocationTypeName(Type2);
  498. Result.append(1, '/');
  499. Result.append(Name.begin(), Name.end());
  500. Name = getRelocationTypeName(Type3);
  501. Result.append(1, '/');
  502. Result.append(Name.begin(), Name.end());
  503. }
  504. }
  505. template <class ELFT>
  506. uint32_t ELFFile<ELFT>::getRelativeRelocationType() const {
  507. return getELFRelativeRelocationType(getHeader().e_machine);
  508. }
  509. template <class ELFT>
  510. Expected<SmallVector<std::optional<VersionEntry>, 0>>
  511. ELFFile<ELFT>::loadVersionMap(const Elf_Shdr *VerNeedSec,
  512. const Elf_Shdr *VerDefSec) const {
  513. SmallVector<std::optional<VersionEntry>, 0> VersionMap;
  514. // The first two version indexes are reserved.
  515. // Index 0 is VER_NDX_LOCAL, index 1 is VER_NDX_GLOBAL.
  516. VersionMap.push_back(VersionEntry());
  517. VersionMap.push_back(VersionEntry());
  518. auto InsertEntry = [&](unsigned N, StringRef Version, bool IsVerdef) {
  519. if (N >= VersionMap.size())
  520. VersionMap.resize(N + 1);
  521. VersionMap[N] = {std::string(Version), IsVerdef};
  522. };
  523. if (VerDefSec) {
  524. Expected<std::vector<VerDef>> Defs = getVersionDefinitions(*VerDefSec);
  525. if (!Defs)
  526. return Defs.takeError();
  527. for (const VerDef &Def : *Defs)
  528. InsertEntry(Def.Ndx & ELF::VERSYM_VERSION, Def.Name, true);
  529. }
  530. if (VerNeedSec) {
  531. Expected<std::vector<VerNeed>> Deps = getVersionDependencies(*VerNeedSec);
  532. if (!Deps)
  533. return Deps.takeError();
  534. for (const VerNeed &Dep : *Deps)
  535. for (const VernAux &Aux : Dep.AuxV)
  536. InsertEntry(Aux.Other & ELF::VERSYM_VERSION, Aux.Name, false);
  537. }
  538. return VersionMap;
  539. }
  540. template <class ELFT>
  541. Expected<const typename ELFT::Sym *>
  542. ELFFile<ELFT>::getRelocationSymbol(const Elf_Rel &Rel,
  543. const Elf_Shdr *SymTab) const {
  544. uint32_t Index = Rel.getSymbol(isMips64EL());
  545. if (Index == 0)
  546. return nullptr;
  547. return getEntry<Elf_Sym>(*SymTab, Index);
  548. }
  549. template <class ELFT>
  550. Expected<StringRef>
  551. ELFFile<ELFT>::getSectionStringTable(Elf_Shdr_Range Sections,
  552. WarningHandler WarnHandler) const {
  553. uint32_t Index = getHeader().e_shstrndx;
  554. if (Index == ELF::SHN_XINDEX) {
  555. // If the section name string table section index is greater than
  556. // or equal to SHN_LORESERVE, then the actual index of the section name
  557. // string table section is contained in the sh_link field of the section
  558. // header at index 0.
  559. if (Sections.empty())
  560. return createError(
  561. "e_shstrndx == SHN_XINDEX, but the section header table is empty");
  562. Index = Sections[0].sh_link;
  563. }
  564. // There is no section name string table. Return FakeSectionStrings which
  565. // is non-empty if we have created fake sections.
  566. if (!Index)
  567. return FakeSectionStrings;
  568. if (Index >= Sections.size())
  569. return createError("section header string table index " + Twine(Index) +
  570. " does not exist");
  571. return getStringTable(Sections[Index], WarnHandler);
  572. }
  573. /// This function finds the number of dynamic symbols using a GNU hash table.
  574. ///
  575. /// @param Table The GNU hash table for .dynsym.
  576. template <class ELFT>
  577. static Expected<uint64_t>
  578. getDynSymtabSizeFromGnuHash(const typename ELFT::GnuHash &Table,
  579. const void *BufEnd) {
  580. using Elf_Word = typename ELFT::Word;
  581. if (Table.nbuckets == 0)
  582. return Table.symndx + 1;
  583. uint64_t LastSymIdx = 0;
  584. // Find the index of the first symbol in the last chain.
  585. for (Elf_Word Val : Table.buckets())
  586. LastSymIdx = std::max(LastSymIdx, (uint64_t)Val);
  587. const Elf_Word *It =
  588. reinterpret_cast<const Elf_Word *>(Table.values(LastSymIdx).end());
  589. // Locate the end of the chain to find the last symbol index.
  590. while (It < BufEnd && (*It & 1) == 0) {
  591. ++LastSymIdx;
  592. ++It;
  593. }
  594. if (It >= BufEnd) {
  595. return createStringError(
  596. object_error::parse_failed,
  597. "no terminator found for GNU hash section before buffer end");
  598. }
  599. return LastSymIdx + 1;
  600. }
  601. /// This function determines the number of dynamic symbols. It reads section
  602. /// headers first. If section headers are not available, the number of
  603. /// symbols will be inferred by parsing dynamic hash tables.
  604. template <class ELFT>
  605. Expected<uint64_t> ELFFile<ELFT>::getDynSymtabSize() const {
  606. // Read .dynsym section header first if available.
  607. Expected<Elf_Shdr_Range> SectionsOrError = sections();
  608. if (!SectionsOrError)
  609. return SectionsOrError.takeError();
  610. for (const Elf_Shdr &Sec : *SectionsOrError) {
  611. if (Sec.sh_type == ELF::SHT_DYNSYM) {
  612. if (Sec.sh_size % Sec.sh_entsize != 0) {
  613. return createStringError(object_error::parse_failed,
  614. "SHT_DYNSYM section has sh_size (" +
  615. Twine(Sec.sh_size) + ") % sh_entsize (" +
  616. Twine(Sec.sh_entsize) + ") that is not 0");
  617. }
  618. return Sec.sh_size / Sec.sh_entsize;
  619. }
  620. }
  621. if (!SectionsOrError->empty()) {
  622. // Section headers are available but .dynsym header is not found.
  623. // Return 0 as .dynsym does not exist.
  624. return 0;
  625. }
  626. // Section headers do not exist. Falling back to infer
  627. // upper bound of .dynsym from .gnu.hash and .hash.
  628. Expected<Elf_Dyn_Range> DynTable = dynamicEntries();
  629. if (!DynTable)
  630. return DynTable.takeError();
  631. std::optional<uint64_t> ElfHash;
  632. std::optional<uint64_t> ElfGnuHash;
  633. for (const Elf_Dyn &Entry : *DynTable) {
  634. switch (Entry.d_tag) {
  635. case ELF::DT_HASH:
  636. ElfHash = Entry.d_un.d_ptr;
  637. break;
  638. case ELF::DT_GNU_HASH:
  639. ElfGnuHash = Entry.d_un.d_ptr;
  640. break;
  641. }
  642. }
  643. if (ElfGnuHash) {
  644. Expected<const uint8_t *> TablePtr = toMappedAddr(*ElfGnuHash);
  645. if (!TablePtr)
  646. return TablePtr.takeError();
  647. const Elf_GnuHash *Table =
  648. reinterpret_cast<const Elf_GnuHash *>(TablePtr.get());
  649. return getDynSymtabSizeFromGnuHash<ELFT>(*Table, this->Buf.bytes_end());
  650. }
  651. // Search SYSV hash table to try to find the upper bound of dynsym.
  652. if (ElfHash) {
  653. Expected<const uint8_t *> TablePtr = toMappedAddr(*ElfHash);
  654. if (!TablePtr)
  655. return TablePtr.takeError();
  656. const Elf_Hash *Table = reinterpret_cast<const Elf_Hash *>(TablePtr.get());
  657. return Table->nchain;
  658. }
  659. return 0;
  660. }
  661. template <class ELFT> ELFFile<ELFT>::ELFFile(StringRef Object) : Buf(Object) {}
  662. template <class ELFT>
  663. Expected<ELFFile<ELFT>> ELFFile<ELFT>::create(StringRef Object) {
  664. if (sizeof(Elf_Ehdr) > Object.size())
  665. return createError("invalid buffer: the size (" + Twine(Object.size()) +
  666. ") is smaller than an ELF header (" +
  667. Twine(sizeof(Elf_Ehdr)) + ")");
  668. return ELFFile(Object);
  669. }
  670. /// Used by llvm-objdump -d (which needs sections for disassembly) to
  671. /// disassemble objects without a section header table (e.g. ET_CORE objects
  672. /// analyzed by linux perf or ET_EXEC with llvm-strip --strip-sections).
  673. template <class ELFT> void ELFFile<ELFT>::createFakeSections() {
  674. if (!FakeSections.empty())
  675. return;
  676. auto PhdrsOrErr = program_headers();
  677. if (!PhdrsOrErr)
  678. return;
  679. FakeSectionStrings += '\0';
  680. for (auto [Idx, Phdr] : llvm::enumerate(*PhdrsOrErr)) {
  681. if (Phdr.p_type != ELF::PT_LOAD || !(Phdr.p_flags & ELF::PF_X))
  682. continue;
  683. Elf_Shdr FakeShdr = {};
  684. FakeShdr.sh_type = ELF::SHT_PROGBITS;
  685. FakeShdr.sh_flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
  686. FakeShdr.sh_addr = Phdr.p_vaddr;
  687. FakeShdr.sh_size = Phdr.p_memsz;
  688. FakeShdr.sh_offset = Phdr.p_offset;
  689. // Create a section name based on the p_type and index.
  690. FakeShdr.sh_name = FakeSectionStrings.size();
  691. FakeSectionStrings += ("PT_LOAD#" + Twine(Idx)).str();
  692. FakeSectionStrings += '\0';
  693. FakeSections.push_back(FakeShdr);
  694. }
  695. }
  696. template <class ELFT>
  697. Expected<typename ELFT::ShdrRange> ELFFile<ELFT>::sections() const {
  698. const uintX_t SectionTableOffset = getHeader().e_shoff;
  699. if (SectionTableOffset == 0) {
  700. if (!FakeSections.empty())
  701. return ArrayRef(FakeSections.data(), FakeSections.size());
  702. return ArrayRef<Elf_Shdr>();
  703. }
  704. if (getHeader().e_shentsize != sizeof(Elf_Shdr))
  705. return createError("invalid e_shentsize in ELF header: " +
  706. Twine(getHeader().e_shentsize));
  707. const uint64_t FileSize = Buf.size();
  708. if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize ||
  709. SectionTableOffset + (uintX_t)sizeof(Elf_Shdr) < SectionTableOffset)
  710. return createError(
  711. "section header table goes past the end of the file: e_shoff = 0x" +
  712. Twine::utohexstr(SectionTableOffset));
  713. // Invalid address alignment of section headers
  714. if (SectionTableOffset & (alignof(Elf_Shdr) - 1))
  715. // TODO: this error is untested.
  716. return createError("invalid alignment of section headers");
  717. const Elf_Shdr *First =
  718. reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
  719. uintX_t NumSections = getHeader().e_shnum;
  720. if (NumSections == 0)
  721. NumSections = First->sh_size;
  722. if (NumSections > UINT64_MAX / sizeof(Elf_Shdr))
  723. return createError("invalid number of sections specified in the NULL "
  724. "section's sh_size field (" +
  725. Twine(NumSections) + ")");
  726. const uint64_t SectionTableSize = NumSections * sizeof(Elf_Shdr);
  727. if (SectionTableOffset + SectionTableSize < SectionTableOffset)
  728. return createError(
  729. "invalid section header table offset (e_shoff = 0x" +
  730. Twine::utohexstr(SectionTableOffset) +
  731. ") or invalid number of sections specified in the first section "
  732. "header's sh_size field (0x" +
  733. Twine::utohexstr(NumSections) + ")");
  734. // Section table goes past end of file!
  735. if (SectionTableOffset + SectionTableSize > FileSize)
  736. return createError("section table goes past the end of file");
  737. return ArrayRef(First, NumSections);
  738. }
  739. template <class ELFT>
  740. template <typename T>
  741. Expected<const T *> ELFFile<ELFT>::getEntry(uint32_t Section,
  742. uint32_t Entry) const {
  743. auto SecOrErr = getSection(Section);
  744. if (!SecOrErr)
  745. return SecOrErr.takeError();
  746. return getEntry<T>(**SecOrErr, Entry);
  747. }
  748. template <class ELFT>
  749. template <typename T>
  750. Expected<const T *> ELFFile<ELFT>::getEntry(const Elf_Shdr &Section,
  751. uint32_t Entry) const {
  752. Expected<ArrayRef<T>> EntriesOrErr = getSectionContentsAsArray<T>(Section);
  753. if (!EntriesOrErr)
  754. return EntriesOrErr.takeError();
  755. ArrayRef<T> Arr = *EntriesOrErr;
  756. if (Entry >= Arr.size())
  757. return createError(
  758. "can't read an entry at 0x" +
  759. Twine::utohexstr(Entry * static_cast<uint64_t>(sizeof(T))) +
  760. ": it goes past the end of the section (0x" +
  761. Twine::utohexstr(Section.sh_size) + ")");
  762. return &Arr[Entry];
  763. }
  764. template <typename ELFT>
  765. Expected<StringRef> ELFFile<ELFT>::getSymbolVersionByIndex(
  766. uint32_t SymbolVersionIndex, bool &IsDefault,
  767. SmallVector<std::optional<VersionEntry>, 0> &VersionMap,
  768. std::optional<bool> IsSymHidden) const {
  769. size_t VersionIndex = SymbolVersionIndex & llvm::ELF::VERSYM_VERSION;
  770. // Special markers for unversioned symbols.
  771. if (VersionIndex == llvm::ELF::VER_NDX_LOCAL ||
  772. VersionIndex == llvm::ELF::VER_NDX_GLOBAL) {
  773. IsDefault = false;
  774. return "";
  775. }
  776. // Lookup this symbol in the version table.
  777. if (VersionIndex >= VersionMap.size() || !VersionMap[VersionIndex])
  778. return createError("SHT_GNU_versym section refers to a version index " +
  779. Twine(VersionIndex) + " which is missing");
  780. const VersionEntry &Entry = *VersionMap[VersionIndex];
  781. // A default version (@@) is only available for defined symbols.
  782. if (!Entry.IsVerDef || IsSymHidden.value_or(false))
  783. IsDefault = false;
  784. else
  785. IsDefault = !(SymbolVersionIndex & llvm::ELF::VERSYM_HIDDEN);
  786. return Entry.Name.c_str();
  787. }
  788. template <class ELFT>
  789. Expected<std::vector<VerDef>>
  790. ELFFile<ELFT>::getVersionDefinitions(const Elf_Shdr &Sec) const {
  791. Expected<StringRef> StrTabOrErr = getLinkAsStrtab(Sec);
  792. if (!StrTabOrErr)
  793. return StrTabOrErr.takeError();
  794. Expected<ArrayRef<uint8_t>> ContentsOrErr = getSectionContents(Sec);
  795. if (!ContentsOrErr)
  796. return createError("cannot read content of " + describe(*this, Sec) + ": " +
  797. toString(ContentsOrErr.takeError()));
  798. const uint8_t *Start = ContentsOrErr->data();
  799. const uint8_t *End = Start + ContentsOrErr->size();
  800. auto ExtractNextAux = [&](const uint8_t *&VerdauxBuf,
  801. unsigned VerDefNdx) -> Expected<VerdAux> {
  802. if (VerdauxBuf + sizeof(Elf_Verdaux) > End)
  803. return createError("invalid " + describe(*this, Sec) +
  804. ": version definition " + Twine(VerDefNdx) +
  805. " refers to an auxiliary entry that goes past the end "
  806. "of the section");
  807. auto *Verdaux = reinterpret_cast<const Elf_Verdaux *>(VerdauxBuf);
  808. VerdauxBuf += Verdaux->vda_next;
  809. VerdAux Aux;
  810. Aux.Offset = VerdauxBuf - Start;
  811. if (Verdaux->vda_name <= StrTabOrErr->size())
  812. Aux.Name = std::string(StrTabOrErr->drop_front(Verdaux->vda_name));
  813. else
  814. Aux.Name = ("<invalid vda_name: " + Twine(Verdaux->vda_name) + ">").str();
  815. return Aux;
  816. };
  817. std::vector<VerDef> Ret;
  818. const uint8_t *VerdefBuf = Start;
  819. for (unsigned I = 1; I <= /*VerDefsNum=*/Sec.sh_info; ++I) {
  820. if (VerdefBuf + sizeof(Elf_Verdef) > End)
  821. return createError("invalid " + describe(*this, Sec) +
  822. ": version definition " + Twine(I) +
  823. " goes past the end of the section");
  824. if (reinterpret_cast<uintptr_t>(VerdefBuf) % sizeof(uint32_t) != 0)
  825. return createError(
  826. "invalid " + describe(*this, Sec) +
  827. ": found a misaligned version definition entry at offset 0x" +
  828. Twine::utohexstr(VerdefBuf - Start));
  829. unsigned Version = *reinterpret_cast<const Elf_Half *>(VerdefBuf);
  830. if (Version != 1)
  831. return createError("unable to dump " + describe(*this, Sec) +
  832. ": version " + Twine(Version) +
  833. " is not yet supported");
  834. const Elf_Verdef *D = reinterpret_cast<const Elf_Verdef *>(VerdefBuf);
  835. VerDef &VD = *Ret.emplace(Ret.end());
  836. VD.Offset = VerdefBuf - Start;
  837. VD.Version = D->vd_version;
  838. VD.Flags = D->vd_flags;
  839. VD.Ndx = D->vd_ndx;
  840. VD.Cnt = D->vd_cnt;
  841. VD.Hash = D->vd_hash;
  842. const uint8_t *VerdauxBuf = VerdefBuf + D->vd_aux;
  843. for (unsigned J = 0; J < D->vd_cnt; ++J) {
  844. if (reinterpret_cast<uintptr_t>(VerdauxBuf) % sizeof(uint32_t) != 0)
  845. return createError("invalid " + describe(*this, Sec) +
  846. ": found a misaligned auxiliary entry at offset 0x" +
  847. Twine::utohexstr(VerdauxBuf - Start));
  848. Expected<VerdAux> AuxOrErr = ExtractNextAux(VerdauxBuf, I);
  849. if (!AuxOrErr)
  850. return AuxOrErr.takeError();
  851. if (J == 0)
  852. VD.Name = AuxOrErr->Name;
  853. else
  854. VD.AuxV.push_back(*AuxOrErr);
  855. }
  856. VerdefBuf += D->vd_next;
  857. }
  858. return Ret;
  859. }
  860. template <class ELFT>
  861. Expected<std::vector<VerNeed>>
  862. ELFFile<ELFT>::getVersionDependencies(const Elf_Shdr &Sec,
  863. WarningHandler WarnHandler) const {
  864. StringRef StrTab;
  865. Expected<StringRef> StrTabOrErr = getLinkAsStrtab(Sec);
  866. if (!StrTabOrErr) {
  867. if (Error E = WarnHandler(toString(StrTabOrErr.takeError())))
  868. return std::move(E);
  869. } else {
  870. StrTab = *StrTabOrErr;
  871. }
  872. Expected<ArrayRef<uint8_t>> ContentsOrErr = getSectionContents(Sec);
  873. if (!ContentsOrErr)
  874. return createError("cannot read content of " + describe(*this, Sec) + ": " +
  875. toString(ContentsOrErr.takeError()));
  876. const uint8_t *Start = ContentsOrErr->data();
  877. const uint8_t *End = Start + ContentsOrErr->size();
  878. const uint8_t *VerneedBuf = Start;
  879. std::vector<VerNeed> Ret;
  880. for (unsigned I = 1; I <= /*VerneedNum=*/Sec.sh_info; ++I) {
  881. if (VerneedBuf + sizeof(Elf_Verdef) > End)
  882. return createError("invalid " + describe(*this, Sec) +
  883. ": version dependency " + Twine(I) +
  884. " goes past the end of the section");
  885. if (reinterpret_cast<uintptr_t>(VerneedBuf) % sizeof(uint32_t) != 0)
  886. return createError(
  887. "invalid " + describe(*this, Sec) +
  888. ": found a misaligned version dependency entry at offset 0x" +
  889. Twine::utohexstr(VerneedBuf - Start));
  890. unsigned Version = *reinterpret_cast<const Elf_Half *>(VerneedBuf);
  891. if (Version != 1)
  892. return createError("unable to dump " + describe(*this, Sec) +
  893. ": version " + Twine(Version) +
  894. " is not yet supported");
  895. const Elf_Verneed *Verneed =
  896. reinterpret_cast<const Elf_Verneed *>(VerneedBuf);
  897. VerNeed &VN = *Ret.emplace(Ret.end());
  898. VN.Version = Verneed->vn_version;
  899. VN.Cnt = Verneed->vn_cnt;
  900. VN.Offset = VerneedBuf - Start;
  901. if (Verneed->vn_file < StrTab.size())
  902. VN.File = std::string(StrTab.data() + Verneed->vn_file);
  903. else
  904. VN.File = ("<corrupt vn_file: " + Twine(Verneed->vn_file) + ">").str();
  905. const uint8_t *VernauxBuf = VerneedBuf + Verneed->vn_aux;
  906. for (unsigned J = 0; J < Verneed->vn_cnt; ++J) {
  907. if (reinterpret_cast<uintptr_t>(VernauxBuf) % sizeof(uint32_t) != 0)
  908. return createError("invalid " + describe(*this, Sec) +
  909. ": found a misaligned auxiliary entry at offset 0x" +
  910. Twine::utohexstr(VernauxBuf - Start));
  911. if (VernauxBuf + sizeof(Elf_Vernaux) > End)
  912. return createError(
  913. "invalid " + describe(*this, Sec) + ": version dependency " +
  914. Twine(I) +
  915. " refers to an auxiliary entry that goes past the end "
  916. "of the section");
  917. const Elf_Vernaux *Vernaux =
  918. reinterpret_cast<const Elf_Vernaux *>(VernauxBuf);
  919. VernAux &Aux = *VN.AuxV.emplace(VN.AuxV.end());
  920. Aux.Hash = Vernaux->vna_hash;
  921. Aux.Flags = Vernaux->vna_flags;
  922. Aux.Other = Vernaux->vna_other;
  923. Aux.Offset = VernauxBuf - Start;
  924. if (StrTab.size() <= Vernaux->vna_name)
  925. Aux.Name = "<corrupt>";
  926. else
  927. Aux.Name = std::string(StrTab.drop_front(Vernaux->vna_name));
  928. VernauxBuf += Vernaux->vna_next;
  929. }
  930. VerneedBuf += Verneed->vn_next;
  931. }
  932. return Ret;
  933. }
  934. template <class ELFT>
  935. Expected<const typename ELFT::Shdr *>
  936. ELFFile<ELFT>::getSection(uint32_t Index) const {
  937. auto TableOrErr = sections();
  938. if (!TableOrErr)
  939. return TableOrErr.takeError();
  940. return object::getSection<ELFT>(*TableOrErr, Index);
  941. }
  942. template <class ELFT>
  943. Expected<StringRef>
  944. ELFFile<ELFT>::getStringTable(const Elf_Shdr &Section,
  945. WarningHandler WarnHandler) const {
  946. if (Section.sh_type != ELF::SHT_STRTAB)
  947. if (Error E = WarnHandler("invalid sh_type for string table section " +
  948. getSecIndexForError(*this, Section) +
  949. ": expected SHT_STRTAB, but got " +
  950. object::getELFSectionTypeName(
  951. getHeader().e_machine, Section.sh_type)))
  952. return std::move(E);
  953. auto V = getSectionContentsAsArray<char>(Section);
  954. if (!V)
  955. return V.takeError();
  956. ArrayRef<char> Data = *V;
  957. if (Data.empty())
  958. return createError("SHT_STRTAB string table section " +
  959. getSecIndexForError(*this, Section) + " is empty");
  960. if (Data.back() != '\0')
  961. return createError("SHT_STRTAB string table section " +
  962. getSecIndexForError(*this, Section) +
  963. " is non-null terminated");
  964. return StringRef(Data.begin(), Data.size());
  965. }
  966. template <class ELFT>
  967. Expected<ArrayRef<typename ELFT::Word>>
  968. ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section) const {
  969. auto SectionsOrErr = sections();
  970. if (!SectionsOrErr)
  971. return SectionsOrErr.takeError();
  972. return getSHNDXTable(Section, *SectionsOrErr);
  973. }
  974. template <class ELFT>
  975. Expected<ArrayRef<typename ELFT::Word>>
  976. ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section,
  977. Elf_Shdr_Range Sections) const {
  978. assert(Section.sh_type == ELF::SHT_SYMTAB_SHNDX);
  979. auto VOrErr = getSectionContentsAsArray<Elf_Word>(Section);
  980. if (!VOrErr)
  981. return VOrErr.takeError();
  982. ArrayRef<Elf_Word> V = *VOrErr;
  983. auto SymTableOrErr = object::getSection<ELFT>(Sections, Section.sh_link);
  984. if (!SymTableOrErr)
  985. return SymTableOrErr.takeError();
  986. const Elf_Shdr &SymTable = **SymTableOrErr;
  987. if (SymTable.sh_type != ELF::SHT_SYMTAB &&
  988. SymTable.sh_type != ELF::SHT_DYNSYM)
  989. return createError(
  990. "SHT_SYMTAB_SHNDX section is linked with " +
  991. object::getELFSectionTypeName(getHeader().e_machine, SymTable.sh_type) +
  992. " section (expected SHT_SYMTAB/SHT_DYNSYM)");
  993. uint64_t Syms = SymTable.sh_size / sizeof(Elf_Sym);
  994. if (V.size() != Syms)
  995. return createError("SHT_SYMTAB_SHNDX has " + Twine(V.size()) +
  996. " entries, but the symbol table associated has " +
  997. Twine(Syms));
  998. return V;
  999. }
  1000. template <class ELFT>
  1001. Expected<StringRef>
  1002. ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
  1003. auto SectionsOrErr = sections();
  1004. if (!SectionsOrErr)
  1005. return SectionsOrErr.takeError();
  1006. return getStringTableForSymtab(Sec, *SectionsOrErr);
  1007. }
  1008. template <class ELFT>
  1009. Expected<StringRef>
  1010. ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec,
  1011. Elf_Shdr_Range Sections) const {
  1012. if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
  1013. return createError(
  1014. "invalid sh_type for symbol table, expected SHT_SYMTAB or SHT_DYNSYM");
  1015. Expected<const Elf_Shdr *> SectionOrErr =
  1016. object::getSection<ELFT>(Sections, Sec.sh_link);
  1017. if (!SectionOrErr)
  1018. return SectionOrErr.takeError();
  1019. return getStringTable(**SectionOrErr);
  1020. }
  1021. template <class ELFT>
  1022. Expected<StringRef>
  1023. ELFFile<ELFT>::getLinkAsStrtab(const typename ELFT::Shdr &Sec) const {
  1024. Expected<const typename ELFT::Shdr *> StrTabSecOrErr =
  1025. getSection(Sec.sh_link);
  1026. if (!StrTabSecOrErr)
  1027. return createError("invalid section linked to " + describe(*this, Sec) +
  1028. ": " + toString(StrTabSecOrErr.takeError()));
  1029. Expected<StringRef> StrTabOrErr = getStringTable(**StrTabSecOrErr);
  1030. if (!StrTabOrErr)
  1031. return createError("invalid string table linked to " +
  1032. describe(*this, Sec) + ": " +
  1033. toString(StrTabOrErr.takeError()));
  1034. return *StrTabOrErr;
  1035. }
  1036. template <class ELFT>
  1037. Expected<StringRef>
  1038. ELFFile<ELFT>::getSectionName(const Elf_Shdr &Section,
  1039. WarningHandler WarnHandler) const {
  1040. auto SectionsOrErr = sections();
  1041. if (!SectionsOrErr)
  1042. return SectionsOrErr.takeError();
  1043. auto Table = getSectionStringTable(*SectionsOrErr, WarnHandler);
  1044. if (!Table)
  1045. return Table.takeError();
  1046. return getSectionName(Section, *Table);
  1047. }
  1048. template <class ELFT>
  1049. Expected<StringRef> ELFFile<ELFT>::getSectionName(const Elf_Shdr &Section,
  1050. StringRef DotShstrtab) const {
  1051. uint32_t Offset = Section.sh_name;
  1052. if (Offset == 0)
  1053. return StringRef();
  1054. if (Offset >= DotShstrtab.size())
  1055. return createError("a section " + getSecIndexForError(*this, Section) +
  1056. " has an invalid sh_name (0x" +
  1057. Twine::utohexstr(Offset) +
  1058. ") offset which goes past the end of the "
  1059. "section name string table");
  1060. return StringRef(DotShstrtab.data() + Offset);
  1061. }
  1062. /// This function returns the hash value for a symbol in the .dynsym section
  1063. /// Name of the API remains consistent as specified in the libelf
  1064. /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
  1065. inline unsigned hashSysV(StringRef SymbolName) {
  1066. unsigned h = 0, g;
  1067. for (char C : SymbolName) {
  1068. h = (h << 4) + C;
  1069. g = h & 0xf0000000L;
  1070. if (g != 0)
  1071. h ^= g >> 24;
  1072. h &= ~g;
  1073. }
  1074. return h;
  1075. }
  1076. /// This function returns the hash value for a symbol in the .dynsym section
  1077. /// for the GNU hash table. The implementation is defined in the GNU hash ABI.
  1078. /// REF : https://sourceware.org/git/?p=binutils-gdb.git;a=blob;f=bfd/elf.c#l222
  1079. inline uint32_t hashGnu(StringRef Name) {
  1080. uint32_t H = 5381;
  1081. for (uint8_t C : Name)
  1082. H = (H << 5) + H + C;
  1083. return H;
  1084. }
  1085. } // end namespace object
  1086. } // end namespace llvm
  1087. #endif // LLVM_OBJECT_ELF_H
  1088. #ifdef __GNUC__
  1089. #pragma GCC diagnostic pop
  1090. #endif