ELF.h 43 KB

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