ELF.h 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049
  1. //===- ELF.h - ELF object file implementation -------------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file declares the ELFFile template class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_OBJECT_ELF_H
  14. #define LLVM_OBJECT_ELF_H
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/IntervalMap.h"
  18. #include "llvm/ADT/PointerIntPair.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/StringSwitch.h"
  21. #include "llvm/ADT/Triple.h"
  22. #include "llvm/Object/ELFTypes.h"
  23. #include "llvm/Object/Error.h"
  24. #include "llvm/Support/Casting.h"
  25. #include "llvm/Support/ELF.h"
  26. #include "llvm/Support/Endian.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/ErrorOr.h"
  29. #include "llvm/Support/MemoryBuffer.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include <algorithm>
  32. #include <limits>
  33. #include <utility>
  34. namespace llvm {
  35. namespace object {
  36. StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type);
  37. // Subclasses of ELFFile may need this for template instantiation
  38. inline std::pair<unsigned char, unsigned char>
  39. getElfArchType(StringRef Object) {
  40. if (Object.size() < ELF::EI_NIDENT)
  41. return std::make_pair((uint8_t)ELF::ELFCLASSNONE,
  42. (uint8_t)ELF::ELFDATANONE);
  43. return std::make_pair((uint8_t)Object[ELF::EI_CLASS],
  44. (uint8_t)Object[ELF::EI_DATA]);
  45. }
  46. template <class ELFT>
  47. class ELFFile {
  48. public:
  49. LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)
  50. typedef typename std::conditional<ELFT::Is64Bits,
  51. uint64_t, uint32_t>::type uintX_t;
  52. /// \brief Iterate over constant sized entities.
  53. template <class EntT>
  54. class ELFEntityIterator {
  55. public:
  56. typedef ptrdiff_t difference_type;
  57. typedef EntT value_type;
  58. typedef std::forward_iterator_tag iterator_category;
  59. typedef value_type &reference;
  60. typedef value_type *pointer;
  61. /// \brief Default construct iterator.
  62. ELFEntityIterator() : EntitySize(0), Current(nullptr) {}
  63. ELFEntityIterator(uintX_t EntSize, const char *Start)
  64. : EntitySize(EntSize), Current(Start) {}
  65. reference operator *() {
  66. assert(Current && "Attempted to dereference an invalid iterator!");
  67. return *reinterpret_cast<pointer>(Current);
  68. }
  69. pointer operator ->() {
  70. assert(Current && "Attempted to dereference an invalid iterator!");
  71. return reinterpret_cast<pointer>(Current);
  72. }
  73. bool operator ==(const ELFEntityIterator &Other) {
  74. return Current == Other.Current;
  75. }
  76. bool operator !=(const ELFEntityIterator &Other) {
  77. return !(*this == Other);
  78. }
  79. ELFEntityIterator &operator ++() {
  80. assert(Current && "Attempted to increment an invalid iterator!");
  81. Current += EntitySize;
  82. return *this;
  83. }
  84. ELFEntityIterator &operator+(difference_type n) {
  85. assert(Current && "Attempted to increment an invalid iterator!");
  86. Current += (n * EntitySize);
  87. return *this;
  88. }
  89. ELFEntityIterator &operator-(difference_type n) {
  90. assert(Current && "Attempted to subtract an invalid iterator!");
  91. Current -= (n * EntitySize);
  92. return *this;
  93. }
  94. ELFEntityIterator operator ++(int) {
  95. ELFEntityIterator Tmp = *this;
  96. ++*this;
  97. return Tmp;
  98. }
  99. difference_type operator -(const ELFEntityIterator &Other) const {
  100. assert(EntitySize == Other.EntitySize &&
  101. "Subtracting iterators of different EntitySize!");
  102. return (Current - Other.Current) / EntitySize;
  103. }
  104. const char *get() const { return Current; }
  105. uintX_t getEntSize() const { return EntitySize; }
  106. private:
  107. uintX_t EntitySize;
  108. const char *Current;
  109. };
  110. typedef Elf_Ehdr_Impl<ELFT> Elf_Ehdr;
  111. typedef Elf_Shdr_Impl<ELFT> Elf_Shdr;
  112. typedef Elf_Sym_Impl<ELFT> Elf_Sym;
  113. typedef Elf_Dyn_Impl<ELFT> Elf_Dyn;
  114. typedef Elf_Phdr_Impl<ELFT> Elf_Phdr;
  115. typedef Elf_Rel_Impl<ELFT, false> Elf_Rel;
  116. typedef Elf_Rel_Impl<ELFT, true> Elf_Rela;
  117. typedef Elf_Verdef_Impl<ELFT> Elf_Verdef;
  118. typedef Elf_Verdaux_Impl<ELFT> Elf_Verdaux;
  119. typedef Elf_Verneed_Impl<ELFT> Elf_Verneed;
  120. typedef Elf_Vernaux_Impl<ELFT> Elf_Vernaux;
  121. typedef Elf_Versym_Impl<ELFT> Elf_Versym;
  122. typedef Elf_Hash_Impl<ELFT> Elf_Hash;
  123. typedef ELFEntityIterator<const Elf_Dyn> Elf_Dyn_Iter;
  124. typedef iterator_range<Elf_Dyn_Iter> Elf_Dyn_Range;
  125. typedef ELFEntityIterator<const Elf_Rela> Elf_Rela_Iter;
  126. typedef ELFEntityIterator<const Elf_Rel> Elf_Rel_Iter;
  127. typedef iterator_range<const Elf_Shdr *> Elf_Shdr_Range;
  128. /// \brief Archive files are 2 byte aligned, so we need this for
  129. /// PointerIntPair to work.
  130. template <typename T>
  131. class ArchivePointerTypeTraits {
  132. public:
  133. static inline const void *getAsVoidPointer(T *P) { return P; }
  134. static inline T *getFromVoidPointer(const void *P) {
  135. return static_cast<T *>(P);
  136. }
  137. enum { NumLowBitsAvailable = 1 };
  138. };
  139. typedef iterator_range<const Elf_Sym *> Elf_Sym_Range;
  140. private:
  141. typedef SmallVector<const Elf_Shdr *, 2> Sections_t;
  142. typedef DenseMap<unsigned, unsigned> IndexMap_t;
  143. StringRef Buf;
  144. const uint8_t *base() const {
  145. return reinterpret_cast<const uint8_t *>(Buf.data());
  146. }
  147. const Elf_Ehdr *Header;
  148. const Elf_Shdr *SectionHeaderTable = nullptr;
  149. StringRef DotShstrtab; // Section header string table.
  150. StringRef DotStrtab; // Symbol header string table.
  151. const Elf_Shdr *dot_symtab_sec = nullptr; // Symbol table section.
  152. const Elf_Shdr *DotDynSymSec = nullptr; // Dynamic symbol table section.
  153. const Elf_Hash *HashTable = nullptr;
  154. const Elf_Shdr *SymbolTableSectionHeaderIndex = nullptr;
  155. DenseMap<const Elf_Sym *, ELF::Elf64_Word> ExtendedSymbolTable;
  156. const Elf_Shdr *dot_gnu_version_sec = nullptr; // .gnu.version
  157. const Elf_Shdr *dot_gnu_version_r_sec = nullptr; // .gnu.version_r
  158. const Elf_Shdr *dot_gnu_version_d_sec = nullptr; // .gnu.version_d
  159. /// \brief Represents a region described by entries in the .dynamic table.
  160. struct DynRegionInfo {
  161. DynRegionInfo() : Addr(nullptr), Size(0), EntSize(0) {}
  162. /// \brief Address in current address space.
  163. const void *Addr;
  164. /// \brief Size in bytes of the region.
  165. uintX_t Size;
  166. /// \brief Size of each entity in the region.
  167. uintX_t EntSize;
  168. };
  169. DynRegionInfo DynamicRegion;
  170. DynRegionInfo DynHashRegion;
  171. DynRegionInfo DynStrRegion;
  172. DynRegionInfo DynRelaRegion;
  173. // Pointer to SONAME entry in dynamic string table
  174. // This is set the first time getLoadName is called.
  175. mutable const char *dt_soname = nullptr;
  176. // Records for each version index the corresponding Verdef or Vernaux entry.
  177. // This is filled the first time LoadVersionMap() is called.
  178. class VersionMapEntry : public PointerIntPair<const void*, 1> {
  179. public:
  180. // If the integer is 0, this is an Elf_Verdef*.
  181. // If the integer is 1, this is an Elf_Vernaux*.
  182. VersionMapEntry() : PointerIntPair<const void*, 1>(nullptr, 0) { }
  183. VersionMapEntry(const Elf_Verdef *verdef)
  184. : PointerIntPair<const void*, 1>(verdef, 0) { }
  185. VersionMapEntry(const Elf_Vernaux *vernaux)
  186. : PointerIntPair<const void*, 1>(vernaux, 1) { }
  187. bool isNull() const { return getPointer() == nullptr; }
  188. bool isVerdef() const { return !isNull() && getInt() == 0; }
  189. bool isVernaux() const { return !isNull() && getInt() == 1; }
  190. const Elf_Verdef *getVerdef() const {
  191. return isVerdef() ? (const Elf_Verdef*)getPointer() : nullptr;
  192. }
  193. const Elf_Vernaux *getVernaux() const {
  194. return isVernaux() ? (const Elf_Vernaux*)getPointer() : nullptr;
  195. }
  196. };
  197. mutable SmallVector<VersionMapEntry, 16> VersionMap;
  198. void LoadVersionDefs(const Elf_Shdr *sec) const;
  199. void LoadVersionNeeds(const Elf_Shdr *ec) const;
  200. void LoadVersionMap() const;
  201. void scanDynamicTable();
  202. public:
  203. template<typename T>
  204. const T *getEntry(uint32_t Section, uint32_t Entry) const;
  205. template <typename T>
  206. const T *getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
  207. const Elf_Shdr *getDotSymtabSec() const { return dot_symtab_sec; }
  208. const Elf_Shdr *getDotDynSymSec() const { return DotDynSymSec; }
  209. const Elf_Hash *getHashTable() const { return HashTable; }
  210. ErrorOr<StringRef> getStringTable(const Elf_Shdr *Section) const;
  211. const char *getDynamicString(uintX_t Offset) const;
  212. ErrorOr<StringRef> getSymbolVersion(const Elf_Shdr *section,
  213. const Elf_Sym *Symb,
  214. bool &IsDefault) const;
  215. void VerifyStrTab(const Elf_Shdr *sh) const;
  216. StringRef getRelocationTypeName(uint32_t Type) const;
  217. void getRelocationTypeName(uint32_t Type,
  218. SmallVectorImpl<char> &Result) const;
  219. /// \brief Get the symbol table section and symbol for a given relocation.
  220. template <class RelT>
  221. std::pair<const Elf_Shdr *, const Elf_Sym *>
  222. getRelocationSymbol(const Elf_Shdr *RelSec, const RelT *Rel) const;
  223. ELFFile(StringRef Object, std::error_code &EC);
  224. bool isMipsELF64() const {
  225. return Header->e_machine == ELF::EM_MIPS &&
  226. Header->getFileClass() == ELF::ELFCLASS64;
  227. }
  228. bool isMips64EL() const {
  229. return Header->e_machine == ELF::EM_MIPS &&
  230. Header->getFileClass() == ELF::ELFCLASS64 &&
  231. Header->getDataEncoding() == ELF::ELFDATA2LSB;
  232. }
  233. const Elf_Shdr *section_begin() const;
  234. const Elf_Shdr *section_end() const;
  235. Elf_Shdr_Range sections() const {
  236. return make_range(section_begin(), section_end());
  237. }
  238. const Elf_Sym *symbol_begin() const;
  239. const Elf_Sym *symbol_end() const;
  240. Elf_Sym_Range symbols() const {
  241. return make_range(symbol_begin(), symbol_end());
  242. }
  243. Elf_Dyn_Iter dynamic_table_begin() const;
  244. /// \param NULLEnd use one past the first DT_NULL entry as the end instead of
  245. /// the section size.
  246. Elf_Dyn_Iter dynamic_table_end(bool NULLEnd = false) const;
  247. Elf_Dyn_Range dynamic_table(bool NULLEnd = false) const {
  248. return make_range(dynamic_table_begin(), dynamic_table_end(NULLEnd));
  249. }
  250. const Elf_Sym *dynamic_symbol_begin() const {
  251. if (!DotDynSymSec)
  252. return nullptr;
  253. if (DotDynSymSec->sh_entsize != sizeof(Elf_Sym))
  254. report_fatal_error("Invalid symbol size");
  255. return reinterpret_cast<const Elf_Sym *>(base() + DotDynSymSec->sh_offset);
  256. }
  257. const Elf_Sym *dynamic_symbol_end() const {
  258. if (!DotDynSymSec)
  259. return nullptr;
  260. return reinterpret_cast<const Elf_Sym *>(base() + DotDynSymSec->sh_offset +
  261. DotDynSymSec->sh_size);
  262. }
  263. Elf_Sym_Range dynamic_symbols() const {
  264. return make_range(dynamic_symbol_begin(), dynamic_symbol_end());
  265. }
  266. Elf_Rela_Iter dyn_rela_begin() const {
  267. if (DynRelaRegion.Addr)
  268. return Elf_Rela_Iter(DynRelaRegion.EntSize,
  269. (const char *)DynRelaRegion.Addr);
  270. return Elf_Rela_Iter(0, nullptr);
  271. }
  272. Elf_Rela_Iter dyn_rela_end() const {
  273. if (DynRelaRegion.Addr)
  274. return Elf_Rela_Iter(
  275. DynRelaRegion.EntSize,
  276. (const char *)DynRelaRegion.Addr + DynRelaRegion.Size);
  277. return Elf_Rela_Iter(0, nullptr);
  278. }
  279. Elf_Rela_Iter rela_begin(const Elf_Shdr *sec) const {
  280. return Elf_Rela_Iter(sec->sh_entsize,
  281. (const char *)(base() + sec->sh_offset));
  282. }
  283. Elf_Rela_Iter rela_end(const Elf_Shdr *sec) const {
  284. return Elf_Rela_Iter(
  285. sec->sh_entsize,
  286. (const char *)(base() + sec->sh_offset + sec->sh_size));
  287. }
  288. Elf_Rel_Iter rel_begin(const Elf_Shdr *sec) const {
  289. return Elf_Rel_Iter(sec->sh_entsize,
  290. (const char *)(base() + sec->sh_offset));
  291. }
  292. Elf_Rel_Iter rel_end(const Elf_Shdr *sec) const {
  293. return Elf_Rel_Iter(sec->sh_entsize,
  294. (const char *)(base() + sec->sh_offset + sec->sh_size));
  295. }
  296. /// \brief Iterate over program header table.
  297. typedef ELFEntityIterator<const Elf_Phdr> Elf_Phdr_Iter;
  298. Elf_Phdr_Iter program_header_begin() const {
  299. return Elf_Phdr_Iter(Header->e_phentsize,
  300. (const char*)base() + Header->e_phoff);
  301. }
  302. Elf_Phdr_Iter program_header_end() const {
  303. return Elf_Phdr_Iter(Header->e_phentsize,
  304. (const char*)base() +
  305. Header->e_phoff +
  306. (Header->e_phnum * Header->e_phentsize));
  307. }
  308. uint64_t getNumSections() const;
  309. uintX_t getStringTableIndex() const;
  310. ELF::Elf64_Word getExtendedSymbolTableIndex(const Elf_Sym *symb) const;
  311. const Elf_Ehdr *getHeader() const { return Header; }
  312. ErrorOr<const Elf_Shdr *> getSection(const Elf_Sym *symb) const;
  313. ErrorOr<const Elf_Shdr *> getSection(uint32_t Index) const;
  314. const Elf_Sym *getSymbol(uint32_t index) const;
  315. ErrorOr<StringRef> getStaticSymbolName(const Elf_Sym *Symb) const;
  316. ErrorOr<StringRef> getDynamicSymbolName(const Elf_Sym *Symb) const;
  317. ErrorOr<StringRef> getSymbolName(const Elf_Sym *Symb, bool IsDynamic) const;
  318. ErrorOr<StringRef> getSectionName(const Elf_Shdr *Section) const;
  319. ErrorOr<ArrayRef<uint8_t> > getSectionContents(const Elf_Shdr *Sec) const;
  320. StringRef getLoadName() const;
  321. };
  322. typedef ELFFile<ELFType<support::little, false>> ELF32LEFile;
  323. typedef ELFFile<ELFType<support::little, true>> ELF64LEFile;
  324. typedef ELFFile<ELFType<support::big, false>> ELF32BEFile;
  325. typedef ELFFile<ELFType<support::big, true>> ELF64BEFile;
  326. // Iterate through the version definitions, and place each Elf_Verdef
  327. // in the VersionMap according to its index.
  328. template <class ELFT>
  329. void ELFFile<ELFT>::LoadVersionDefs(const Elf_Shdr *sec) const {
  330. unsigned vd_size = sec->sh_size; // Size of section in bytes
  331. unsigned vd_count = sec->sh_info; // Number of Verdef entries
  332. const char *sec_start = (const char*)base() + sec->sh_offset;
  333. const char *sec_end = sec_start + vd_size;
  334. // The first Verdef entry is at the start of the section.
  335. const char *p = sec_start;
  336. for (unsigned i = 0; i < vd_count; i++) {
  337. if (p + sizeof(Elf_Verdef) > sec_end)
  338. report_fatal_error("Section ended unexpectedly while scanning "
  339. "version definitions.");
  340. const Elf_Verdef *vd = reinterpret_cast<const Elf_Verdef *>(p);
  341. if (vd->vd_version != ELF::VER_DEF_CURRENT)
  342. report_fatal_error("Unexpected verdef version");
  343. size_t index = vd->vd_ndx & ELF::VERSYM_VERSION;
  344. if (index >= VersionMap.size())
  345. VersionMap.resize(index + 1);
  346. VersionMap[index] = VersionMapEntry(vd);
  347. p += vd->vd_next;
  348. }
  349. }
  350. // Iterate through the versions needed section, and place each Elf_Vernaux
  351. // in the VersionMap according to its index.
  352. template <class ELFT>
  353. void ELFFile<ELFT>::LoadVersionNeeds(const Elf_Shdr *sec) const {
  354. unsigned vn_size = sec->sh_size; // Size of section in bytes
  355. unsigned vn_count = sec->sh_info; // Number of Verneed entries
  356. const char *sec_start = (const char *)base() + sec->sh_offset;
  357. const char *sec_end = sec_start + vn_size;
  358. // The first Verneed entry is at the start of the section.
  359. const char *p = sec_start;
  360. for (unsigned i = 0; i < vn_count; i++) {
  361. if (p + sizeof(Elf_Verneed) > sec_end)
  362. report_fatal_error("Section ended unexpectedly while scanning "
  363. "version needed records.");
  364. const Elf_Verneed *vn = reinterpret_cast<const Elf_Verneed *>(p);
  365. if (vn->vn_version != ELF::VER_NEED_CURRENT)
  366. report_fatal_error("Unexpected verneed version");
  367. // Iterate through the Vernaux entries
  368. const char *paux = p + vn->vn_aux;
  369. for (unsigned j = 0; j < vn->vn_cnt; j++) {
  370. if (paux + sizeof(Elf_Vernaux) > sec_end)
  371. report_fatal_error("Section ended unexpected while scanning auxiliary "
  372. "version needed records.");
  373. const Elf_Vernaux *vna = reinterpret_cast<const Elf_Vernaux *>(paux);
  374. size_t index = vna->vna_other & ELF::VERSYM_VERSION;
  375. if (index >= VersionMap.size())
  376. VersionMap.resize(index + 1);
  377. VersionMap[index] = VersionMapEntry(vna);
  378. paux += vna->vna_next;
  379. }
  380. p += vn->vn_next;
  381. }
  382. }
  383. template <class ELFT>
  384. void ELFFile<ELFT>::LoadVersionMap() const {
  385. // If there is no dynamic symtab or version table, there is nothing to do.
  386. if (!DotDynSymSec || !dot_gnu_version_sec)
  387. return;
  388. // Has the VersionMap already been loaded?
  389. if (VersionMap.size() > 0)
  390. return;
  391. // The first two version indexes are reserved.
  392. // Index 0 is LOCAL, index 1 is GLOBAL.
  393. VersionMap.push_back(VersionMapEntry());
  394. VersionMap.push_back(VersionMapEntry());
  395. if (dot_gnu_version_d_sec)
  396. LoadVersionDefs(dot_gnu_version_d_sec);
  397. if (dot_gnu_version_r_sec)
  398. LoadVersionNeeds(dot_gnu_version_r_sec);
  399. }
  400. template <class ELFT>
  401. ELF::Elf64_Word
  402. ELFFile<ELFT>::getExtendedSymbolTableIndex(const Elf_Sym *symb) const {
  403. assert(symb->st_shndx == ELF::SHN_XINDEX);
  404. return ExtendedSymbolTable.lookup(symb);
  405. }
  406. template <class ELFT>
  407. ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
  408. ELFFile<ELFT>::getSection(const Elf_Sym *symb) const {
  409. uint32_t Index = symb->st_shndx;
  410. if (Index == ELF::SHN_XINDEX)
  411. return getSection(ExtendedSymbolTable.lookup(symb));
  412. if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
  413. return nullptr;
  414. return getSection(symb->st_shndx);
  415. }
  416. template <class ELFT>
  417. const typename ELFFile<ELFT>::Elf_Sym *
  418. ELFFile<ELFT>::getSymbol(uint32_t Index) const {
  419. return &*(symbol_begin() + Index);
  420. }
  421. template <class ELFT>
  422. ErrorOr<ArrayRef<uint8_t> >
  423. ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
  424. if (Sec->sh_offset + Sec->sh_size > Buf.size())
  425. return object_error::parse_failed;
  426. const uint8_t *Start = base() + Sec->sh_offset;
  427. return makeArrayRef(Start, Sec->sh_size);
  428. }
  429. template <class ELFT>
  430. StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
  431. return getELFRelocationTypeName(Header->e_machine, Type);
  432. }
  433. template <class ELFT>
  434. void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
  435. SmallVectorImpl<char> &Result) const {
  436. if (!isMipsELF64()) {
  437. StringRef Name = getRelocationTypeName(Type);
  438. Result.append(Name.begin(), Name.end());
  439. } else {
  440. // The Mips N64 ABI allows up to three operations to be specified per
  441. // relocation record. Unfortunately there's no easy way to test for the
  442. // presence of N64 ELFs as they have no special flag that identifies them
  443. // as being N64. We can safely assume at the moment that all Mips
  444. // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
  445. // information to disambiguate between old vs new ABIs.
  446. uint8_t Type1 = (Type >> 0) & 0xFF;
  447. uint8_t Type2 = (Type >> 8) & 0xFF;
  448. uint8_t Type3 = (Type >> 16) & 0xFF;
  449. // Concat all three relocation type names.
  450. StringRef Name = getRelocationTypeName(Type1);
  451. Result.append(Name.begin(), Name.end());
  452. Name = getRelocationTypeName(Type2);
  453. Result.append(1, '/');
  454. Result.append(Name.begin(), Name.end());
  455. Name = getRelocationTypeName(Type3);
  456. Result.append(1, '/');
  457. Result.append(Name.begin(), Name.end());
  458. }
  459. }
  460. template <class ELFT>
  461. template <class RelT>
  462. std::pair<const typename ELFFile<ELFT>::Elf_Shdr *,
  463. const typename ELFFile<ELFT>::Elf_Sym *>
  464. ELFFile<ELFT>::getRelocationSymbol(const Elf_Shdr *Sec, const RelT *Rel) const {
  465. if (!Sec->sh_link)
  466. return std::make_pair(nullptr, nullptr);
  467. ErrorOr<const Elf_Shdr *> SymTableOrErr = getSection(Sec->sh_link);
  468. if (std::error_code EC = SymTableOrErr.getError())
  469. report_fatal_error(EC.message());
  470. const Elf_Shdr *SymTable = *SymTableOrErr;
  471. return std::make_pair(
  472. SymTable, getEntry<Elf_Sym>(SymTable, Rel->getSymbol(isMips64EL())));
  473. }
  474. template <class ELFT>
  475. uint64_t ELFFile<ELFT>::getNumSections() const {
  476. assert(Header && "Header not initialized!");
  477. if (Header->e_shnum == ELF::SHN_UNDEF && Header->e_shoff > 0) {
  478. assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
  479. return SectionHeaderTable->sh_size;
  480. }
  481. return Header->e_shnum;
  482. }
  483. template <class ELFT>
  484. typename ELFFile<ELFT>::uintX_t ELFFile<ELFT>::getStringTableIndex() const {
  485. if (Header->e_shnum == ELF::SHN_UNDEF) {
  486. if (Header->e_shstrndx == ELF::SHN_HIRESERVE)
  487. return SectionHeaderTable->sh_link;
  488. if (Header->e_shstrndx >= getNumSections())
  489. return 0;
  490. }
  491. return Header->e_shstrndx;
  492. }
  493. template <class ELFT>
  494. ELFFile<ELFT>::ELFFile(StringRef Object, std::error_code &EC)
  495. : Buf(Object) {
  496. const uint64_t FileSize = Buf.size();
  497. if (sizeof(Elf_Ehdr) > FileSize) {
  498. // File too short!
  499. EC = object_error::parse_failed;
  500. return;
  501. }
  502. Header = reinterpret_cast<const Elf_Ehdr *>(base());
  503. if (Header->e_shoff == 0) {
  504. scanDynamicTable();
  505. return;
  506. }
  507. const uint64_t SectionTableOffset = Header->e_shoff;
  508. if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize) {
  509. // Section header table goes past end of file!
  510. EC = object_error::parse_failed;
  511. return;
  512. }
  513. // The getNumSections() call below depends on SectionHeaderTable being set.
  514. SectionHeaderTable =
  515. reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
  516. const uint64_t SectionTableSize = getNumSections() * Header->e_shentsize;
  517. if (SectionTableOffset + SectionTableSize > FileSize) {
  518. // Section table goes past end of file!
  519. EC = object_error::parse_failed;
  520. return;
  521. }
  522. // Scan sections for special sections.
  523. for (const Elf_Shdr &Sec : sections()) {
  524. switch (Sec.sh_type) {
  525. case ELF::SHT_HASH:
  526. if (HashTable) {
  527. EC = object_error::parse_failed;
  528. return;
  529. }
  530. HashTable = reinterpret_cast<const Elf_Hash *>(base() + Sec.sh_offset);
  531. break;
  532. case ELF::SHT_SYMTAB_SHNDX:
  533. if (SymbolTableSectionHeaderIndex) {
  534. // More than one .symtab_shndx!
  535. EC = object_error::parse_failed;
  536. return;
  537. }
  538. SymbolTableSectionHeaderIndex = &Sec;
  539. break;
  540. case ELF::SHT_SYMTAB: {
  541. if (dot_symtab_sec) {
  542. // More than one .symtab!
  543. EC = object_error::parse_failed;
  544. return;
  545. }
  546. dot_symtab_sec = &Sec;
  547. ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
  548. if ((EC = SectionOrErr.getError()))
  549. return;
  550. ErrorOr<StringRef> SymtabOrErr = getStringTable(*SectionOrErr);
  551. if ((EC = SymtabOrErr.getError()))
  552. return;
  553. DotStrtab = *SymtabOrErr;
  554. } break;
  555. case ELF::SHT_DYNSYM: {
  556. if (DotDynSymSec) {
  557. // More than one .dynsym!
  558. EC = object_error::parse_failed;
  559. return;
  560. }
  561. DotDynSymSec = &Sec;
  562. ErrorOr<const Elf_Shdr *> SectionOrErr = getSection(Sec.sh_link);
  563. if ((EC = SectionOrErr.getError()))
  564. return;
  565. ErrorOr<StringRef> SymtabOrErr = getStringTable(*SectionOrErr);
  566. if ((EC = SymtabOrErr.getError()))
  567. return;
  568. DynStrRegion.Addr = SymtabOrErr->data();
  569. DynStrRegion.Size = SymtabOrErr->size();
  570. DynStrRegion.EntSize = 1;
  571. break;
  572. }
  573. case ELF::SHT_DYNAMIC:
  574. if (DynamicRegion.Addr) {
  575. // More than one .dynamic!
  576. EC = object_error::parse_failed;
  577. return;
  578. }
  579. DynamicRegion.Addr = base() + Sec.sh_offset;
  580. DynamicRegion.Size = Sec.sh_size;
  581. DynamicRegion.EntSize = Sec.sh_entsize;
  582. break;
  583. case ELF::SHT_GNU_versym:
  584. if (dot_gnu_version_sec != nullptr) {
  585. // More than one .gnu.version section!
  586. EC = object_error::parse_failed;
  587. return;
  588. }
  589. dot_gnu_version_sec = &Sec;
  590. break;
  591. case ELF::SHT_GNU_verdef:
  592. if (dot_gnu_version_d_sec != nullptr) {
  593. // More than one .gnu.version_d section!
  594. EC = object_error::parse_failed;
  595. return;
  596. }
  597. dot_gnu_version_d_sec = &Sec;
  598. break;
  599. case ELF::SHT_GNU_verneed:
  600. if (dot_gnu_version_r_sec != nullptr) {
  601. // More than one .gnu.version_r section!
  602. EC = object_error::parse_failed;
  603. return;
  604. }
  605. dot_gnu_version_r_sec = &Sec;
  606. break;
  607. }
  608. }
  609. // Get string table sections.
  610. ErrorOr<const Elf_Shdr *> StrTabSecOrErr = getSection(getStringTableIndex());
  611. if ((EC = StrTabSecOrErr.getError()))
  612. return;
  613. ErrorOr<StringRef> SymtabOrErr = getStringTable(*StrTabSecOrErr);
  614. if ((EC = SymtabOrErr.getError()))
  615. return;
  616. DotShstrtab = *SymtabOrErr;
  617. // Build symbol name side-mapping if there is one.
  618. if (SymbolTableSectionHeaderIndex) {
  619. const Elf_Word *ShndxTable = reinterpret_cast<const Elf_Word*>(base() +
  620. SymbolTableSectionHeaderIndex->sh_offset);
  621. for (const Elf_Sym &S : symbols()) {
  622. if (*ShndxTable != ELF::SHN_UNDEF)
  623. ExtendedSymbolTable[&S] = *ShndxTable;
  624. ++ShndxTable;
  625. }
  626. }
  627. scanDynamicTable();
  628. EC = std::error_code();
  629. }
  630. template <class ELFT>
  631. void ELFFile<ELFT>::scanDynamicTable() {
  632. // Build load-address to file-offset map.
  633. typedef IntervalMap<
  634. uintX_t, uintptr_t,
  635. IntervalMapImpl::NodeSizer<uintX_t, uintptr_t>::LeafSize,
  636. IntervalMapHalfOpenInfo<uintX_t>> LoadMapT;
  637. typename LoadMapT::Allocator Alloc;
  638. // Allocate the IntervalMap on the heap to work around MSVC bug where the
  639. // stack doesn't get realigned despite LoadMap having alignment 8 (PR24113).
  640. std::unique_ptr<LoadMapT> LoadMap(new LoadMapT(Alloc));
  641. for (Elf_Phdr_Iter PhdrI = program_header_begin(),
  642. PhdrE = program_header_end();
  643. PhdrI != PhdrE; ++PhdrI) {
  644. if (PhdrI->p_type == ELF::PT_DYNAMIC) {
  645. DynamicRegion.Addr = base() + PhdrI->p_offset;
  646. DynamicRegion.Size = PhdrI->p_filesz;
  647. DynamicRegion.EntSize = sizeof(Elf_Dyn);
  648. continue;
  649. }
  650. if (PhdrI->p_type != ELF::PT_LOAD)
  651. continue;
  652. if (PhdrI->p_filesz == 0)
  653. continue;
  654. LoadMap->insert(PhdrI->p_vaddr, PhdrI->p_vaddr + PhdrI->p_filesz,
  655. PhdrI->p_offset);
  656. }
  657. auto toMappedAddr = [&](uint64_t VAddr) -> const uint8_t * {
  658. auto I = LoadMap->find(VAddr);
  659. if (I == LoadMap->end())
  660. return nullptr;
  661. return this->base() + I.value() + (VAddr - I.start());
  662. };
  663. for (Elf_Dyn_Iter DynI = dynamic_table_begin(), DynE = dynamic_table_end();
  664. DynI != DynE; ++DynI) {
  665. switch (DynI->d_tag) {
  666. case ELF::DT_HASH:
  667. if (HashTable)
  668. continue;
  669. HashTable =
  670. reinterpret_cast<const Elf_Hash *>(toMappedAddr(DynI->getPtr()));
  671. break;
  672. case ELF::DT_STRTAB:
  673. if (!DynStrRegion.Addr)
  674. DynStrRegion.Addr = toMappedAddr(DynI->getPtr());
  675. break;
  676. case ELF::DT_STRSZ:
  677. if (!DynStrRegion.Size)
  678. DynStrRegion.Size = DynI->getVal();
  679. break;
  680. case ELF::DT_RELA:
  681. if (!DynRelaRegion.Addr)
  682. DynRelaRegion.Addr = toMappedAddr(DynI->getPtr());
  683. break;
  684. case ELF::DT_RELASZ:
  685. DynRelaRegion.Size = DynI->getVal();
  686. break;
  687. case ELF::DT_RELAENT:
  688. DynRelaRegion.EntSize = DynI->getVal();
  689. }
  690. }
  691. }
  692. template <class ELFT>
  693. const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_begin() const {
  694. if (Header->e_shentsize != sizeof(Elf_Shdr))
  695. report_fatal_error(
  696. "Invalid section header entry size (e_shentsize) in ELF header");
  697. return reinterpret_cast<const Elf_Shdr *>(base() + Header->e_shoff);
  698. }
  699. template <class ELFT>
  700. const typename ELFFile<ELFT>::Elf_Shdr *ELFFile<ELFT>::section_end() const {
  701. return section_begin() + getNumSections();
  702. }
  703. template <class ELFT>
  704. const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_begin() const {
  705. if (!dot_symtab_sec)
  706. return nullptr;
  707. if (dot_symtab_sec->sh_entsize != sizeof(Elf_Sym))
  708. report_fatal_error("Invalid symbol size");
  709. return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset);
  710. }
  711. template <class ELFT>
  712. const typename ELFFile<ELFT>::Elf_Sym *ELFFile<ELFT>::symbol_end() const {
  713. if (!dot_symtab_sec)
  714. return nullptr;
  715. return reinterpret_cast<const Elf_Sym *>(base() + dot_symtab_sec->sh_offset +
  716. dot_symtab_sec->sh_size);
  717. }
  718. template <class ELFT>
  719. typename ELFFile<ELFT>::Elf_Dyn_Iter
  720. ELFFile<ELFT>::dynamic_table_begin() const {
  721. if (DynamicRegion.Addr)
  722. return Elf_Dyn_Iter(DynamicRegion.EntSize,
  723. (const char *)DynamicRegion.Addr);
  724. return Elf_Dyn_Iter(0, nullptr);
  725. }
  726. template <class ELFT>
  727. typename ELFFile<ELFT>::Elf_Dyn_Iter
  728. ELFFile<ELFT>::dynamic_table_end(bool NULLEnd) const {
  729. if (!DynamicRegion.Addr)
  730. return Elf_Dyn_Iter(0, nullptr);
  731. Elf_Dyn_Iter Ret(DynamicRegion.EntSize,
  732. (const char *)DynamicRegion.Addr + DynamicRegion.Size);
  733. if (NULLEnd) {
  734. Elf_Dyn_Iter Start = dynamic_table_begin();
  735. while (Start != Ret && Start->getTag() != ELF::DT_NULL)
  736. ++Start;
  737. // Include the DT_NULL.
  738. if (Start != Ret)
  739. ++Start;
  740. Ret = Start;
  741. }
  742. return Ret;
  743. }
  744. template <class ELFT>
  745. StringRef ELFFile<ELFT>::getLoadName() const {
  746. if (!dt_soname) {
  747. dt_soname = "";
  748. // Find the DT_SONAME entry
  749. for (const auto &Entry : dynamic_table())
  750. if (Entry.getTag() == ELF::DT_SONAME) {
  751. dt_soname = getDynamicString(Entry.getVal());
  752. break;
  753. }
  754. }
  755. return dt_soname;
  756. }
  757. template <class ELFT>
  758. template <typename T>
  759. const T *ELFFile<ELFT>::getEntry(uint32_t Section, uint32_t Entry) const {
  760. ErrorOr<const Elf_Shdr *> Sec = getSection(Section);
  761. if (std::error_code EC = Sec.getError())
  762. report_fatal_error(EC.message());
  763. return getEntry<T>(*Sec, Entry);
  764. }
  765. template <class ELFT>
  766. template <typename T>
  767. const T *ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
  768. uint32_t Entry) const {
  769. return reinterpret_cast<const T *>(base() + Section->sh_offset +
  770. (Entry * Section->sh_entsize));
  771. }
  772. template <class ELFT>
  773. ErrorOr<const typename ELFFile<ELFT>::Elf_Shdr *>
  774. ELFFile<ELFT>::getSection(uint32_t Index) const {
  775. assert(SectionHeaderTable && "SectionHeaderTable not initialized!");
  776. if (Index >= getNumSections())
  777. return object_error::invalid_section_index;
  778. return reinterpret_cast<const Elf_Shdr *>(
  779. reinterpret_cast<const char *>(SectionHeaderTable) +
  780. (Index * Header->e_shentsize));
  781. }
  782. template <class ELFT>
  783. ErrorOr<StringRef>
  784. ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
  785. if (Section->sh_type != ELF::SHT_STRTAB)
  786. return object_error::parse_failed;
  787. uint64_t Offset = Section->sh_offset;
  788. uint64_t Size = Section->sh_size;
  789. if (Offset + Size > Buf.size())
  790. return object_error::parse_failed;
  791. StringRef Data((const char *)base() + Section->sh_offset, Size);
  792. if (Data[Size - 1] != '\0')
  793. return object_error::string_table_non_null_end;
  794. return Data;
  795. }
  796. template <class ELFT>
  797. const char *ELFFile<ELFT>::getDynamicString(uintX_t Offset) const {
  798. if (Offset >= DynStrRegion.Size)
  799. return nullptr;
  800. return (const char *)DynStrRegion.Addr + Offset;
  801. }
  802. template <class ELFT>
  803. ErrorOr<StringRef>
  804. ELFFile<ELFT>::getStaticSymbolName(const Elf_Sym *Symb) const {
  805. return Symb->getName(DotStrtab);
  806. }
  807. template <class ELFT>
  808. ErrorOr<StringRef>
  809. ELFFile<ELFT>::getDynamicSymbolName(const Elf_Sym *Symb) const {
  810. return StringRef(getDynamicString(Symb->st_name));
  811. }
  812. template <class ELFT>
  813. ErrorOr<StringRef> ELFFile<ELFT>::getSymbolName(const Elf_Sym *Symb,
  814. bool IsDynamic) const {
  815. if (IsDynamic)
  816. return getDynamicSymbolName(Symb);
  817. return getStaticSymbolName(Symb);
  818. }
  819. template <class ELFT>
  820. ErrorOr<StringRef>
  821. ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
  822. uint32_t Offset = Section->sh_name;
  823. if (Offset >= DotShstrtab.size())
  824. return object_error::parse_failed;
  825. return StringRef(DotShstrtab.data() + Offset);
  826. }
  827. template <class ELFT>
  828. ErrorOr<StringRef> ELFFile<ELFT>::getSymbolVersion(const Elf_Shdr *section,
  829. const Elf_Sym *symb,
  830. bool &IsDefault) const {
  831. StringRef StrTab;
  832. if (section) {
  833. ErrorOr<StringRef> StrTabOrErr = getStringTable(section);
  834. if (std::error_code EC = StrTabOrErr.getError())
  835. return EC;
  836. StrTab = *StrTabOrErr;
  837. }
  838. // Handle non-dynamic symbols.
  839. if (section != DotDynSymSec && section != nullptr) {
  840. // Non-dynamic symbols can have versions in their names
  841. // A name of the form 'foo@V1' indicates version 'V1', non-default.
  842. // A name of the form 'foo@@V2' indicates version 'V2', default version.
  843. ErrorOr<StringRef> SymName = symb->getName(StrTab);
  844. if (!SymName)
  845. return SymName;
  846. StringRef Name = *SymName;
  847. size_t atpos = Name.find('@');
  848. if (atpos == StringRef::npos) {
  849. IsDefault = false;
  850. return StringRef("");
  851. }
  852. ++atpos;
  853. if (atpos < Name.size() && Name[atpos] == '@') {
  854. IsDefault = true;
  855. ++atpos;
  856. } else {
  857. IsDefault = false;
  858. }
  859. return Name.substr(atpos);
  860. }
  861. // This is a dynamic symbol. Look in the GNU symbol version table.
  862. if (!dot_gnu_version_sec) {
  863. // No version table.
  864. IsDefault = false;
  865. return StringRef("");
  866. }
  867. // Determine the position in the symbol table of this entry.
  868. size_t entry_index =
  869. (reinterpret_cast<uintptr_t>(symb) - DotDynSymSec->sh_offset -
  870. reinterpret_cast<uintptr_t>(base())) /
  871. sizeof(Elf_Sym);
  872. // Get the corresponding version index entry
  873. const Elf_Versym *vs = getEntry<Elf_Versym>(dot_gnu_version_sec, entry_index);
  874. size_t version_index = vs->vs_index & ELF::VERSYM_VERSION;
  875. // Special markers for unversioned symbols.
  876. if (version_index == ELF::VER_NDX_LOCAL ||
  877. version_index == ELF::VER_NDX_GLOBAL) {
  878. IsDefault = false;
  879. return StringRef("");
  880. }
  881. // Lookup this symbol in the version table
  882. LoadVersionMap();
  883. if (version_index >= VersionMap.size() || VersionMap[version_index].isNull())
  884. return object_error::parse_failed;
  885. const VersionMapEntry &entry = VersionMap[version_index];
  886. // Get the version name string
  887. size_t name_offset;
  888. if (entry.isVerdef()) {
  889. // The first Verdaux entry holds the name.
  890. name_offset = entry.getVerdef()->getAux()->vda_name;
  891. } else {
  892. name_offset = entry.getVernaux()->vna_name;
  893. }
  894. // Set IsDefault
  895. if (entry.isVerdef()) {
  896. IsDefault = !(vs->vs_index & ELF::VERSYM_HIDDEN);
  897. } else {
  898. IsDefault = false;
  899. }
  900. if (name_offset >= DynStrRegion.Size)
  901. return object_error::parse_failed;
  902. return StringRef(getDynamicString(name_offset));
  903. }
  904. /// This function returns the hash value for a symbol in the .dynsym section
  905. /// Name of the API remains consistent as specified in the libelf
  906. /// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
  907. static inline unsigned elf_hash(StringRef &symbolName) {
  908. unsigned h = 0, g;
  909. for (unsigned i = 0, j = symbolName.size(); i < j; i++) {
  910. h = (h << 4) + symbolName[i];
  911. g = h & 0xf0000000L;
  912. if (g != 0)
  913. h ^= g >> 24;
  914. h &= ~g;
  915. }
  916. return h;
  917. }
  918. } // end namespace object
  919. } // end namespace llvm
  920. #endif