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. static inline Error createError(const Twine &Err) {
  79. return make_error<StringError>(Err, object_error::parse_failed);
  80. }
  81. enum PPCInstrMasks : uint64_t {
  82. PADDI_R12_NO_DISP = 0x0610000039800000,
  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. };
  337. using ELF32LEFile = ELFFile<ELF32LE>;
  338. using ELF64LEFile = ELFFile<ELF64LE>;
  339. using ELF32BEFile = ELFFile<ELF32BE>;
  340. using ELF64BEFile = ELFFile<ELF64BE>;
  341. template <class ELFT>
  342. inline Expected<const typename ELFT::Shdr *>
  343. getSection(typename ELFT::ShdrRange Sections, uint32_t Index) {
  344. if (Index >= Sections.size())
  345. return createError("invalid section index: " + Twine(Index));
  346. return &Sections[Index];
  347. }
  348. template <class ELFT>
  349. inline Expected<uint32_t>
  350. getExtendedSymbolTableIndex(const typename ELFT::Sym &Sym, unsigned SymIndex,
  351. DataRegion<typename ELFT::Word> ShndxTable) {
  352. assert(Sym.st_shndx == ELF::SHN_XINDEX);
  353. if (!ShndxTable.First)
  354. return createError(
  355. "found an extended symbol index (" + Twine(SymIndex) +
  356. "), but unable to locate the extended symbol index table");
  357. Expected<typename ELFT::Word> TableOrErr = ShndxTable[SymIndex];
  358. if (!TableOrErr)
  359. return createError("unable to read an extended symbol table at index " +
  360. Twine(SymIndex) + ": " +
  361. toString(TableOrErr.takeError()));
  362. return *TableOrErr;
  363. }
  364. template <class ELFT>
  365. Expected<uint32_t>
  366. ELFFile<ELFT>::getSectionIndex(const Elf_Sym &Sym, Elf_Sym_Range Syms,
  367. DataRegion<Elf_Word> ShndxTable) const {
  368. uint32_t Index = Sym.st_shndx;
  369. if (Index == ELF::SHN_XINDEX) {
  370. Expected<uint32_t> ErrorOrIndex =
  371. getExtendedSymbolTableIndex<ELFT>(Sym, &Sym - Syms.begin(), ShndxTable);
  372. if (!ErrorOrIndex)
  373. return ErrorOrIndex.takeError();
  374. return *ErrorOrIndex;
  375. }
  376. if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
  377. return 0;
  378. return Index;
  379. }
  380. template <class ELFT>
  381. Expected<const typename ELFT::Shdr *>
  382. ELFFile<ELFT>::getSection(const Elf_Sym &Sym, const Elf_Shdr *SymTab,
  383. DataRegion<Elf_Word> ShndxTable) const {
  384. auto SymsOrErr = symbols(SymTab);
  385. if (!SymsOrErr)
  386. return SymsOrErr.takeError();
  387. return getSection(Sym, *SymsOrErr, ShndxTable);
  388. }
  389. template <class ELFT>
  390. Expected<const typename ELFT::Shdr *>
  391. ELFFile<ELFT>::getSection(const Elf_Sym &Sym, Elf_Sym_Range Symbols,
  392. DataRegion<Elf_Word> ShndxTable) const {
  393. auto IndexOrErr = getSectionIndex(Sym, Symbols, ShndxTable);
  394. if (!IndexOrErr)
  395. return IndexOrErr.takeError();
  396. uint32_t Index = *IndexOrErr;
  397. if (Index == 0)
  398. return nullptr;
  399. return getSection(Index);
  400. }
  401. template <class ELFT>
  402. Expected<const typename ELFT::Sym *>
  403. ELFFile<ELFT>::getSymbol(const Elf_Shdr *Sec, uint32_t Index) const {
  404. auto SymsOrErr = symbols(Sec);
  405. if (!SymsOrErr)
  406. return SymsOrErr.takeError();
  407. Elf_Sym_Range Symbols = *SymsOrErr;
  408. if (Index >= Symbols.size())
  409. return createError("unable to get symbol from section " +
  410. getSecIndexForError(*this, *Sec) +
  411. ": invalid symbol index (" + Twine(Index) + ")");
  412. return &Symbols[Index];
  413. }
  414. template <class ELFT>
  415. template <typename T>
  416. Expected<ArrayRef<T>>
  417. ELFFile<ELFT>::getSectionContentsAsArray(const Elf_Shdr &Sec) const {
  418. if (Sec.sh_entsize != sizeof(T) && sizeof(T) != 1)
  419. return createError("section " + getSecIndexForError(*this, Sec) +
  420. " has invalid sh_entsize: expected " + Twine(sizeof(T)) +
  421. ", but got " + Twine(Sec.sh_entsize));
  422. uintX_t Offset = Sec.sh_offset;
  423. uintX_t Size = Sec.sh_size;
  424. if (Size % sizeof(T))
  425. return createError("section " + getSecIndexForError(*this, Sec) +
  426. " has an invalid sh_size (" + Twine(Size) +
  427. ") which is not a multiple of its sh_entsize (" +
  428. Twine(Sec.sh_entsize) + ")");
  429. if (std::numeric_limits<uintX_t>::max() - Offset < Size)
  430. return createError("section " + getSecIndexForError(*this, Sec) +
  431. " has a sh_offset (0x" + Twine::utohexstr(Offset) +
  432. ") + sh_size (0x" + Twine::utohexstr(Size) +
  433. ") that cannot be represented");
  434. if (Offset + Size > Buf.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 is greater than the file size (0x" +
  439. Twine::utohexstr(Buf.size()) + ")");
  440. if (Offset % alignof(T))
  441. // TODO: this error is untested.
  442. return createError("unaligned data");
  443. const T *Start = reinterpret_cast<const T *>(base() + Offset);
  444. return makeArrayRef(Start, Size / sizeof(T));
  445. }
  446. template <class ELFT>
  447. Expected<ArrayRef<uint8_t>>
  448. ELFFile<ELFT>::getSegmentContents(const Elf_Phdr &Phdr) const {
  449. uintX_t Offset = Phdr.p_offset;
  450. uintX_t Size = Phdr.p_filesz;
  451. if (std::numeric_limits<uintX_t>::max() - Offset < Size)
  452. return createError("program header " + getPhdrIndexForError(*this, Phdr) +
  453. " has a p_offset (0x" + Twine::utohexstr(Offset) +
  454. ") + p_filesz (0x" + Twine::utohexstr(Size) +
  455. ") that cannot be represented");
  456. if (Offset + Size > Buf.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 is greater than the file size (0x" +
  461. Twine::utohexstr(Buf.size()) + ")");
  462. return makeArrayRef(base() + Offset, Size);
  463. }
  464. template <class ELFT>
  465. Expected<ArrayRef<uint8_t>>
  466. ELFFile<ELFT>::getSectionContents(const Elf_Shdr &Sec) const {
  467. return getSectionContentsAsArray<uint8_t>(Sec);
  468. }
  469. template <class ELFT>
  470. StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
  471. return getELFRelocationTypeName(getHeader().e_machine, Type);
  472. }
  473. template <class ELFT>
  474. void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
  475. SmallVectorImpl<char> &Result) const {
  476. if (!isMipsELF64()) {
  477. StringRef Name = getRelocationTypeName(Type);
  478. Result.append(Name.begin(), Name.end());
  479. } else {
  480. // The Mips N64 ABI allows up to three operations to be specified per
  481. // relocation record. Unfortunately there's no easy way to test for the
  482. // presence of N64 ELFs as they have no special flag that identifies them
  483. // as being N64. We can safely assume at the moment that all Mips
  484. // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
  485. // information to disambiguate between old vs new ABIs.
  486. uint8_t Type1 = (Type >> 0) & 0xFF;
  487. uint8_t Type2 = (Type >> 8) & 0xFF;
  488. uint8_t Type3 = (Type >> 16) & 0xFF;
  489. // Concat all three relocation type names.
  490. StringRef Name = getRelocationTypeName(Type1);
  491. Result.append(Name.begin(), Name.end());
  492. Name = getRelocationTypeName(Type2);
  493. Result.append(1, '/');
  494. Result.append(Name.begin(), Name.end());
  495. Name = getRelocationTypeName(Type3);
  496. Result.append(1, '/');
  497. Result.append(Name.begin(), Name.end());
  498. }
  499. }
  500. template <class ELFT>
  501. uint32_t ELFFile<ELFT>::getRelativeRelocationType() const {
  502. return getELFRelativeRelocationType(getHeader().e_machine);
  503. }
  504. template <class ELFT>
  505. Expected<SmallVector<Optional<VersionEntry>, 0>>
  506. ELFFile<ELFT>::loadVersionMap(const Elf_Shdr *VerNeedSec,
  507. const Elf_Shdr *VerDefSec) const {
  508. SmallVector<Optional<VersionEntry>, 0> VersionMap;
  509. // The first two version indexes are reserved.
  510. // Index 0 is VER_NDX_LOCAL, index 1 is VER_NDX_GLOBAL.
  511. VersionMap.push_back(VersionEntry());
  512. VersionMap.push_back(VersionEntry());
  513. auto InsertEntry = [&](unsigned N, StringRef Version, bool IsVerdef) {
  514. if (N >= VersionMap.size())
  515. VersionMap.resize(N + 1);
  516. VersionMap[N] = {std::string(Version), IsVerdef};
  517. };
  518. if (VerDefSec) {
  519. Expected<std::vector<VerDef>> Defs = getVersionDefinitions(*VerDefSec);
  520. if (!Defs)
  521. return Defs.takeError();
  522. for (const VerDef &Def : *Defs)
  523. InsertEntry(Def.Ndx & ELF::VERSYM_VERSION, Def.Name, true);
  524. }
  525. if (VerNeedSec) {
  526. Expected<std::vector<VerNeed>> Deps = getVersionDependencies(*VerNeedSec);
  527. if (!Deps)
  528. return Deps.takeError();
  529. for (const VerNeed &Dep : *Deps)
  530. for (const VernAux &Aux : Dep.AuxV)
  531. InsertEntry(Aux.Other & ELF::VERSYM_VERSION, Aux.Name, false);
  532. }
  533. return VersionMap;
  534. }
  535. template <class ELFT>
  536. Expected<const typename ELFT::Sym *>
  537. ELFFile<ELFT>::getRelocationSymbol(const Elf_Rel &Rel,
  538. const Elf_Shdr *SymTab) const {
  539. uint32_t Index = Rel.getSymbol(isMips64EL());
  540. if (Index == 0)
  541. return nullptr;
  542. return getEntry<Elf_Sym>(*SymTab, Index);
  543. }
  544. template <class ELFT>
  545. Expected<StringRef>
  546. ELFFile<ELFT>::getSectionStringTable(Elf_Shdr_Range Sections,
  547. WarningHandler WarnHandler) const {
  548. uint32_t Index = getHeader().e_shstrndx;
  549. if (Index == ELF::SHN_XINDEX) {
  550. // If the section name string table section index is greater than
  551. // or equal to SHN_LORESERVE, then the actual index of the section name
  552. // string table section is contained in the sh_link field of the section
  553. // header at index 0.
  554. if (Sections.empty())
  555. return createError(
  556. "e_shstrndx == SHN_XINDEX, but the section header table is empty");
  557. Index = Sections[0].sh_link;
  558. }
  559. if (!Index) // no section string table.
  560. return "";
  561. if (Index >= Sections.size())
  562. return createError("section header string table index " + Twine(Index) +
  563. " does not exist");
  564. return getStringTable(Sections[Index], WarnHandler);
  565. }
  566. /// This function finds the number of dynamic symbols using a GNU hash table.
  567. ///
  568. /// @param Table The GNU hash table for .dynsym.
  569. template <class ELFT>
  570. static Expected<uint64_t>
  571. getDynSymtabSizeFromGnuHash(const typename ELFT::GnuHash &Table,
  572. const void *BufEnd) {
  573. using Elf_Word = typename ELFT::Word;
  574. if (Table.nbuckets == 0)
  575. return Table.symndx + 1;
  576. uint64_t LastSymIdx = 0;
  577. // Find the index of the first symbol in the last chain.
  578. for (Elf_Word Val : Table.buckets())
  579. LastSymIdx = std::max(LastSymIdx, (uint64_t)Val);
  580. const Elf_Word *It =
  581. reinterpret_cast<const Elf_Word *>(Table.values(LastSymIdx).end());
  582. // Locate the end of the chain to find the last symbol index.
  583. while (It < BufEnd && (*It & 1) == 0) {
  584. ++LastSymIdx;
  585. ++It;
  586. }
  587. if (It >= BufEnd) {
  588. return createStringError(
  589. object_error::parse_failed,
  590. "no terminator found for GNU hash section before buffer end");
  591. }
  592. return LastSymIdx + 1;
  593. }
  594. /// This function determines the number of dynamic symbols. It reads section
  595. /// headers first. If section headers are not available, the number of
  596. /// symbols will be inferred by parsing dynamic hash tables.
  597. template <class ELFT>
  598. Expected<uint64_t> ELFFile<ELFT>::getDynSymtabSize() const {
  599. // Read .dynsym section header first if available.
  600. Expected<Elf_Shdr_Range> SectionsOrError = sections();
  601. if (!SectionsOrError)
  602. return SectionsOrError.takeError();
  603. for (const Elf_Shdr &Sec : *SectionsOrError) {
  604. if (Sec.sh_type == ELF::SHT_DYNSYM) {
  605. if (Sec.sh_size % Sec.sh_entsize != 0) {
  606. return createStringError(object_error::parse_failed,
  607. "SHT_DYNSYM section has sh_size (" +
  608. Twine(Sec.sh_size) + ") % sh_entsize (" +
  609. Twine(Sec.sh_entsize) + ") that is not 0");
  610. }
  611. return Sec.sh_size / Sec.sh_entsize;
  612. }
  613. }
  614. if (!SectionsOrError->empty()) {
  615. // Section headers are available but .dynsym header is not found.
  616. // Return 0 as .dynsym does not exist.
  617. return 0;
  618. }
  619. // Section headers do not exist. Falling back to infer
  620. // upper bound of .dynsym from .gnu.hash and .hash.
  621. Expected<Elf_Dyn_Range> DynTable = dynamicEntries();
  622. if (!DynTable)
  623. return DynTable.takeError();
  624. llvm::Optional<uint64_t> ElfHash;
  625. llvm::Optional<uint64_t> ElfGnuHash;
  626. for (const Elf_Dyn &Entry : *DynTable) {
  627. switch (Entry.d_tag) {
  628. case ELF::DT_HASH:
  629. ElfHash = Entry.d_un.d_ptr;
  630. break;
  631. case ELF::DT_GNU_HASH:
  632. ElfGnuHash = Entry.d_un.d_ptr;
  633. break;
  634. }
  635. }
  636. if (ElfGnuHash) {
  637. Expected<const uint8_t *> TablePtr = toMappedAddr(*ElfGnuHash);
  638. if (!TablePtr)
  639. return TablePtr.takeError();
  640. const Elf_GnuHash *Table =
  641. reinterpret_cast<const Elf_GnuHash *>(TablePtr.get());
  642. return getDynSymtabSizeFromGnuHash<ELFT>(*Table, this->Buf.bytes_end());
  643. }
  644. // Search SYSV hash table to try to find the upper bound of dynsym.
  645. if (ElfHash) {
  646. Expected<const uint8_t *> TablePtr = toMappedAddr(*ElfHash);
  647. if (!TablePtr)
  648. return TablePtr.takeError();
  649. const Elf_Hash *Table = reinterpret_cast<const Elf_Hash *>(TablePtr.get());
  650. return Table->nchain;
  651. }
  652. return 0;
  653. }
  654. template <class ELFT> ELFFile<ELFT>::ELFFile(StringRef Object) : Buf(Object) {}
  655. template <class ELFT>
  656. Expected<ELFFile<ELFT>> ELFFile<ELFT>::create(StringRef Object) {
  657. if (sizeof(Elf_Ehdr) > Object.size())
  658. return createError("invalid buffer: the size (" + Twine(Object.size()) +
  659. ") is smaller than an ELF header (" +
  660. Twine(sizeof(Elf_Ehdr)) + ")");
  661. return ELFFile(Object);
  662. }
  663. template <class ELFT>
  664. Expected<typename ELFT::ShdrRange> ELFFile<ELFT>::sections() const {
  665. const uintX_t SectionTableOffset = getHeader().e_shoff;
  666. if (SectionTableOffset == 0)
  667. return ArrayRef<Elf_Shdr>();
  668. if (getHeader().e_shentsize != sizeof(Elf_Shdr))
  669. return createError("invalid e_shentsize in ELF header: " +
  670. Twine(getHeader().e_shentsize));
  671. const uint64_t FileSize = Buf.size();
  672. if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize ||
  673. SectionTableOffset + (uintX_t)sizeof(Elf_Shdr) < SectionTableOffset)
  674. return createError(
  675. "section header table goes past the end of the file: e_shoff = 0x" +
  676. Twine::utohexstr(SectionTableOffset));
  677. // Invalid address alignment of section headers
  678. if (SectionTableOffset & (alignof(Elf_Shdr) - 1))
  679. // TODO: this error is untested.
  680. return createError("invalid alignment of section headers");
  681. const Elf_Shdr *First =
  682. reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
  683. uintX_t NumSections = getHeader().e_shnum;
  684. if (NumSections == 0)
  685. NumSections = First->sh_size;
  686. if (NumSections > UINT64_MAX / sizeof(Elf_Shdr))
  687. return createError("invalid number of sections specified in the NULL "
  688. "section's sh_size field (" +
  689. Twine(NumSections) + ")");
  690. const uint64_t SectionTableSize = NumSections * sizeof(Elf_Shdr);
  691. if (SectionTableOffset + SectionTableSize < SectionTableOffset)
  692. return createError(
  693. "invalid section header table offset (e_shoff = 0x" +
  694. Twine::utohexstr(SectionTableOffset) +
  695. ") or invalid number of sections specified in the first section "
  696. "header's sh_size field (0x" +
  697. Twine::utohexstr(NumSections) + ")");
  698. // Section table goes past end of file!
  699. if (SectionTableOffset + SectionTableSize > FileSize)
  700. return createError("section table goes past the end of file");
  701. return makeArrayRef(First, NumSections);
  702. }
  703. template <class ELFT>
  704. template <typename T>
  705. Expected<const T *> ELFFile<ELFT>::getEntry(uint32_t Section,
  706. uint32_t Entry) const {
  707. auto SecOrErr = getSection(Section);
  708. if (!SecOrErr)
  709. return SecOrErr.takeError();
  710. return getEntry<T>(**SecOrErr, Entry);
  711. }
  712. template <class ELFT>
  713. template <typename T>
  714. Expected<const T *> ELFFile<ELFT>::getEntry(const Elf_Shdr &Section,
  715. uint32_t Entry) const {
  716. Expected<ArrayRef<T>> EntriesOrErr = getSectionContentsAsArray<T>(Section);
  717. if (!EntriesOrErr)
  718. return EntriesOrErr.takeError();
  719. ArrayRef<T> Arr = *EntriesOrErr;
  720. if (Entry >= Arr.size())
  721. return createError(
  722. "can't read an entry at 0x" +
  723. Twine::utohexstr(Entry * static_cast<uint64_t>(sizeof(T))) +
  724. ": it goes past the end of the section (0x" +
  725. Twine::utohexstr(Section.sh_size) + ")");
  726. return &Arr[Entry];
  727. }
  728. template <typename ELFT>
  729. Expected<StringRef> ELFFile<ELFT>::getSymbolVersionByIndex(
  730. uint32_t SymbolVersionIndex, bool &IsDefault,
  731. SmallVector<Optional<VersionEntry>, 0> &VersionMap,
  732. Optional<bool> IsSymHidden) const {
  733. size_t VersionIndex = SymbolVersionIndex & llvm::ELF::VERSYM_VERSION;
  734. // Special markers for unversioned symbols.
  735. if (VersionIndex == llvm::ELF::VER_NDX_LOCAL ||
  736. VersionIndex == llvm::ELF::VER_NDX_GLOBAL) {
  737. IsDefault = false;
  738. return "";
  739. }
  740. // Lookup this symbol in the version table.
  741. if (VersionIndex >= VersionMap.size() || !VersionMap[VersionIndex])
  742. return createError("SHT_GNU_versym section refers to a version index " +
  743. Twine(VersionIndex) + " which is missing");
  744. const VersionEntry &Entry = *VersionMap[VersionIndex];
  745. // A default version (@@) is only available for defined symbols.
  746. if (!Entry.IsVerDef || IsSymHidden.getValueOr(false))
  747. IsDefault = false;
  748. else
  749. IsDefault = !(SymbolVersionIndex & llvm::ELF::VERSYM_HIDDEN);
  750. return Entry.Name.c_str();
  751. }
  752. template <class ELFT>
  753. Expected<std::vector<VerDef>>
  754. ELFFile<ELFT>::getVersionDefinitions(const Elf_Shdr &Sec) const {
  755. Expected<StringRef> StrTabOrErr = getLinkAsStrtab(Sec);
  756. if (!StrTabOrErr)
  757. return StrTabOrErr.takeError();
  758. Expected<ArrayRef<uint8_t>> ContentsOrErr = getSectionContents(Sec);
  759. if (!ContentsOrErr)
  760. return createError("cannot read content of " + describe(*this, Sec) + ": " +
  761. toString(ContentsOrErr.takeError()));
  762. const uint8_t *Start = ContentsOrErr->data();
  763. const uint8_t *End = Start + ContentsOrErr->size();
  764. auto ExtractNextAux = [&](const uint8_t *&VerdauxBuf,
  765. unsigned VerDefNdx) -> Expected<VerdAux> {
  766. if (VerdauxBuf + sizeof(Elf_Verdaux) > End)
  767. return createError("invalid " + describe(*this, Sec) +
  768. ": version definition " + Twine(VerDefNdx) +
  769. " refers to an auxiliary entry that goes past the end "
  770. "of the section");
  771. auto *Verdaux = reinterpret_cast<const Elf_Verdaux *>(VerdauxBuf);
  772. VerdauxBuf += Verdaux->vda_next;
  773. VerdAux Aux;
  774. Aux.Offset = VerdauxBuf - Start;
  775. if (Verdaux->vda_name <= StrTabOrErr->size())
  776. Aux.Name = std::string(StrTabOrErr->drop_front(Verdaux->vda_name));
  777. else
  778. Aux.Name = ("<invalid vda_name: " + Twine(Verdaux->vda_name) + ">").str();
  779. return Aux;
  780. };
  781. std::vector<VerDef> Ret;
  782. const uint8_t *VerdefBuf = Start;
  783. for (unsigned I = 1; I <= /*VerDefsNum=*/Sec.sh_info; ++I) {
  784. if (VerdefBuf + sizeof(Elf_Verdef) > End)
  785. return createError("invalid " + describe(*this, Sec) +
  786. ": version definition " + Twine(I) +
  787. " goes past the end of the section");
  788. if (reinterpret_cast<uintptr_t>(VerdefBuf) % sizeof(uint32_t) != 0)
  789. return createError(
  790. "invalid " + describe(*this, Sec) +
  791. ": found a misaligned version definition entry at offset 0x" +
  792. Twine::utohexstr(VerdefBuf - Start));
  793. unsigned Version = *reinterpret_cast<const Elf_Half *>(VerdefBuf);
  794. if (Version != 1)
  795. return createError("unable to dump " + describe(*this, Sec) +
  796. ": version " + Twine(Version) +
  797. " is not yet supported");
  798. const Elf_Verdef *D = reinterpret_cast<const Elf_Verdef *>(VerdefBuf);
  799. VerDef &VD = *Ret.emplace(Ret.end());
  800. VD.Offset = VerdefBuf - Start;
  801. VD.Version = D->vd_version;
  802. VD.Flags = D->vd_flags;
  803. VD.Ndx = D->vd_ndx;
  804. VD.Cnt = D->vd_cnt;
  805. VD.Hash = D->vd_hash;
  806. const uint8_t *VerdauxBuf = VerdefBuf + D->vd_aux;
  807. for (unsigned J = 0; J < D->vd_cnt; ++J) {
  808. if (reinterpret_cast<uintptr_t>(VerdauxBuf) % sizeof(uint32_t) != 0)
  809. return createError("invalid " + describe(*this, Sec) +
  810. ": found a misaligned auxiliary entry at offset 0x" +
  811. Twine::utohexstr(VerdauxBuf - Start));
  812. Expected<VerdAux> AuxOrErr = ExtractNextAux(VerdauxBuf, I);
  813. if (!AuxOrErr)
  814. return AuxOrErr.takeError();
  815. if (J == 0)
  816. VD.Name = AuxOrErr->Name;
  817. else
  818. VD.AuxV.push_back(*AuxOrErr);
  819. }
  820. VerdefBuf += D->vd_next;
  821. }
  822. return Ret;
  823. }
  824. template <class ELFT>
  825. Expected<std::vector<VerNeed>>
  826. ELFFile<ELFT>::getVersionDependencies(const Elf_Shdr &Sec,
  827. WarningHandler WarnHandler) const {
  828. StringRef StrTab;
  829. Expected<StringRef> StrTabOrErr = getLinkAsStrtab(Sec);
  830. if (!StrTabOrErr) {
  831. if (Error E = WarnHandler(toString(StrTabOrErr.takeError())))
  832. return std::move(E);
  833. } else {
  834. StrTab = *StrTabOrErr;
  835. }
  836. Expected<ArrayRef<uint8_t>> ContentsOrErr = getSectionContents(Sec);
  837. if (!ContentsOrErr)
  838. return createError("cannot read content of " + describe(*this, Sec) + ": " +
  839. toString(ContentsOrErr.takeError()));
  840. const uint8_t *Start = ContentsOrErr->data();
  841. const uint8_t *End = Start + ContentsOrErr->size();
  842. const uint8_t *VerneedBuf = Start;
  843. std::vector<VerNeed> Ret;
  844. for (unsigned I = 1; I <= /*VerneedNum=*/Sec.sh_info; ++I) {
  845. if (VerneedBuf + sizeof(Elf_Verdef) > End)
  846. return createError("invalid " + describe(*this, Sec) +
  847. ": version dependency " + Twine(I) +
  848. " goes past the end of the section");
  849. if (reinterpret_cast<uintptr_t>(VerneedBuf) % sizeof(uint32_t) != 0)
  850. return createError(
  851. "invalid " + describe(*this, Sec) +
  852. ": found a misaligned version dependency entry at offset 0x" +
  853. Twine::utohexstr(VerneedBuf - Start));
  854. unsigned Version = *reinterpret_cast<const Elf_Half *>(VerneedBuf);
  855. if (Version != 1)
  856. return createError("unable to dump " + describe(*this, Sec) +
  857. ": version " + Twine(Version) +
  858. " is not yet supported");
  859. const Elf_Verneed *Verneed =
  860. reinterpret_cast<const Elf_Verneed *>(VerneedBuf);
  861. VerNeed &VN = *Ret.emplace(Ret.end());
  862. VN.Version = Verneed->vn_version;
  863. VN.Cnt = Verneed->vn_cnt;
  864. VN.Offset = VerneedBuf - Start;
  865. if (Verneed->vn_file < StrTab.size())
  866. VN.File = std::string(StrTab.drop_front(Verneed->vn_file));
  867. else
  868. VN.File = ("<corrupt vn_file: " + Twine(Verneed->vn_file) + ">").str();
  869. const uint8_t *VernauxBuf = VerneedBuf + Verneed->vn_aux;
  870. for (unsigned J = 0; J < Verneed->vn_cnt; ++J) {
  871. if (reinterpret_cast<uintptr_t>(VernauxBuf) % sizeof(uint32_t) != 0)
  872. return createError("invalid " + describe(*this, Sec) +
  873. ": found a misaligned auxiliary entry at offset 0x" +
  874. Twine::utohexstr(VernauxBuf - Start));
  875. if (VernauxBuf + sizeof(Elf_Vernaux) > End)
  876. return createError(
  877. "invalid " + describe(*this, Sec) + ": version dependency " +
  878. Twine(I) +
  879. " refers to an auxiliary entry that goes past the end "
  880. "of the section");
  881. const Elf_Vernaux *Vernaux =
  882. reinterpret_cast<const Elf_Vernaux *>(VernauxBuf);
  883. VernAux &Aux = *VN.AuxV.emplace(VN.AuxV.end());
  884. Aux.Hash = Vernaux->vna_hash;
  885. Aux.Flags = Vernaux->vna_flags;
  886. Aux.Other = Vernaux->vna_other;
  887. Aux.Offset = VernauxBuf - Start;
  888. if (StrTab.size() <= Vernaux->vna_name)
  889. Aux.Name = "<corrupt>";
  890. else
  891. Aux.Name = std::string(StrTab.drop_front(Vernaux->vna_name));
  892. VernauxBuf += Vernaux->vna_next;
  893. }
  894. VerneedBuf += Verneed->vn_next;
  895. }
  896. return Ret;
  897. }
  898. template <class ELFT>
  899. Expected<const typename ELFT::Shdr *>
  900. ELFFile<ELFT>::getSection(uint32_t Index) const {
  901. auto TableOrErr = sections();
  902. if (!TableOrErr)
  903. return TableOrErr.takeError();
  904. return object::getSection<ELFT>(*TableOrErr, Index);
  905. }
  906. template <class ELFT>
  907. Expected<StringRef>
  908. ELFFile<ELFT>::getStringTable(const Elf_Shdr &Section,
  909. WarningHandler WarnHandler) const {
  910. if (Section.sh_type != ELF::SHT_STRTAB)
  911. if (Error E = WarnHandler("invalid sh_type for string table section " +
  912. getSecIndexForError(*this, Section) +
  913. ": expected SHT_STRTAB, but got " +
  914. object::getELFSectionTypeName(
  915. getHeader().e_machine, Section.sh_type)))
  916. return std::move(E);
  917. auto V = getSectionContentsAsArray<char>(Section);
  918. if (!V)
  919. return V.takeError();
  920. ArrayRef<char> Data = *V;
  921. if (Data.empty())
  922. return createError("SHT_STRTAB string table section " +
  923. getSecIndexForError(*this, Section) + " is empty");
  924. if (Data.back() != '\0')
  925. return createError("SHT_STRTAB string table section " +
  926. getSecIndexForError(*this, Section) +
  927. " is non-null terminated");
  928. return StringRef(Data.begin(), Data.size());
  929. }
  930. template <class ELFT>
  931. Expected<ArrayRef<typename ELFT::Word>>
  932. ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section) const {
  933. auto SectionsOrErr = sections();
  934. if (!SectionsOrErr)
  935. return SectionsOrErr.takeError();
  936. return getSHNDXTable(Section, *SectionsOrErr);
  937. }
  938. template <class ELFT>
  939. Expected<ArrayRef<typename ELFT::Word>>
  940. ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section,
  941. Elf_Shdr_Range Sections) const {
  942. assert(Section.sh_type == ELF::SHT_SYMTAB_SHNDX);
  943. auto VOrErr = getSectionContentsAsArray<Elf_Word>(Section);
  944. if (!VOrErr)
  945. return VOrErr.takeError();
  946. ArrayRef<Elf_Word> V = *VOrErr;
  947. auto SymTableOrErr = object::getSection<ELFT>(Sections, Section.sh_link);
  948. if (!SymTableOrErr)
  949. return SymTableOrErr.takeError();
  950. const Elf_Shdr &SymTable = **SymTableOrErr;
  951. if (SymTable.sh_type != ELF::SHT_SYMTAB &&
  952. SymTable.sh_type != ELF::SHT_DYNSYM)
  953. return createError(
  954. "SHT_SYMTAB_SHNDX section is linked with " +
  955. object::getELFSectionTypeName(getHeader().e_machine, SymTable.sh_type) +
  956. " section (expected SHT_SYMTAB/SHT_DYNSYM)");
  957. uint64_t Syms = SymTable.sh_size / sizeof(Elf_Sym);
  958. if (V.size() != Syms)
  959. return createError("SHT_SYMTAB_SHNDX has " + Twine(V.size()) +
  960. " entries, but the symbol table associated has " +
  961. Twine(Syms));
  962. return V;
  963. }
  964. template <class ELFT>
  965. Expected<StringRef>
  966. ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
  967. auto SectionsOrErr = sections();
  968. if (!SectionsOrErr)
  969. return SectionsOrErr.takeError();
  970. return getStringTableForSymtab(Sec, *SectionsOrErr);
  971. }
  972. template <class ELFT>
  973. Expected<StringRef>
  974. ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec,
  975. Elf_Shdr_Range Sections) const {
  976. if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
  977. return createError(
  978. "invalid sh_type for symbol table, expected SHT_SYMTAB or SHT_DYNSYM");
  979. Expected<const Elf_Shdr *> SectionOrErr =
  980. object::getSection<ELFT>(Sections, Sec.sh_link);
  981. if (!SectionOrErr)
  982. return SectionOrErr.takeError();
  983. return getStringTable(**SectionOrErr);
  984. }
  985. template <class ELFT>
  986. Expected<StringRef>
  987. ELFFile<ELFT>::getLinkAsStrtab(const typename ELFT::Shdr &Sec) const {
  988. Expected<const typename ELFT::Shdr *> StrTabSecOrErr =
  989. getSection(Sec.sh_link);
  990. if (!StrTabSecOrErr)
  991. return createError("invalid section linked to " + describe(*this, Sec) +
  992. ": " + toString(StrTabSecOrErr.takeError()));
  993. Expected<StringRef> StrTabOrErr = getStringTable(**StrTabSecOrErr);
  994. if (!StrTabOrErr)
  995. return createError("invalid string table linked to " +
  996. describe(*this, Sec) + ": " +
  997. toString(StrTabOrErr.takeError()));
  998. return *StrTabOrErr;
  999. }
  1000. template <class ELFT>
  1001. Expected<StringRef>
  1002. ELFFile<ELFT>::getSectionName(const Elf_Shdr &Section,
  1003. WarningHandler WarnHandler) const {
  1004. auto SectionsOrErr = sections();
  1005. if (!SectionsOrErr)
  1006. return SectionsOrErr.takeError();
  1007. auto Table = getSectionStringTable(*SectionsOrErr, WarnHandler);
  1008. if (!Table)
  1009. return Table.takeError();
  1010. return getSectionName(Section, *Table);
  1011. }
  1012. template <class ELFT>
  1013. Expected<StringRef> ELFFile<ELFT>::getSectionName(const Elf_Shdr &Section,
  1014. StringRef DotShstrtab) const {
  1015. uint32_t Offset = Section.sh_name;
  1016. if (Offset == 0)
  1017. return StringRef();
  1018. if (Offset >= DotShstrtab.size())
  1019. return createError("a section " + getSecIndexForError(*this, Section) +
  1020. " has an invalid sh_name (0x" +
  1021. Twine::utohexstr(Offset) +
  1022. ") offset which goes past the end of the "
  1023. "section name string table");
  1024. return StringRef(DotShstrtab.data() + Offset);
  1025. }
  1026. /// This function returns the hash value for a symbol in the .dynsym section
  1027. /// Name of the API remains consistent as specified in the libelf
  1028. /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
  1029. inline unsigned hashSysV(StringRef SymbolName) {
  1030. unsigned h = 0, g;
  1031. for (char C : SymbolName) {
  1032. h = (h << 4) + C;
  1033. g = h & 0xf0000000L;
  1034. if (g != 0)
  1035. h ^= g >> 24;
  1036. h &= ~g;
  1037. }
  1038. return h;
  1039. }
  1040. } // end namespace object
  1041. } // end namespace llvm
  1042. #endif // LLVM_OBJECT_ELF_H
  1043. #ifdef __GNUC__
  1044. #pragma GCC diagnostic pop
  1045. #endif