cmELF.cxx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmELF.h"
  4. #include "cmAlgorithms.h"
  5. #include "cm_kwiml.h"
  6. #include "cmsys/FStream.hxx"
  7. #include <map>
  8. #include <memory> // IWYU pragma: keep
  9. #include <sstream>
  10. #include <stddef.h>
  11. #include <utility>
  12. #include <vector>
  13. // Include the ELF format information system header.
  14. #if defined(__OpenBSD__)
  15. # include <elf_abi.h>
  16. # include <stdint.h>
  17. #elif defined(__HAIKU__)
  18. # include <elf32.h>
  19. # include <elf64.h>
  20. typedef struct Elf32_Ehdr Elf32_Ehdr;
  21. typedef struct Elf32_Shdr Elf32_Shdr;
  22. typedef struct Elf32_Sym Elf32_Sym;
  23. typedef struct Elf32_Rel Elf32_Rel;
  24. typedef struct Elf32_Rela Elf32_Rela;
  25. # define ELFMAG0 0x7F
  26. # define ELFMAG1 'E'
  27. # define ELFMAG2 'L'
  28. # define ELFMAG3 'F'
  29. # define ET_NONE 0
  30. # define ET_REL 1
  31. # define ET_EXEC 2
  32. # define ET_DYN 3
  33. # define ET_CORE 4
  34. # define EM_386 3
  35. # define EM_SPARC 2
  36. # define EM_PPC 20
  37. #else
  38. # include <elf.h>
  39. #endif
  40. #if defined(__sun)
  41. # include <sys/link.h> // For dynamic section information
  42. #endif
  43. #ifdef _SCO_DS
  44. # include <link.h> // For DT_SONAME etc.
  45. #endif
  46. #ifndef DT_RUNPATH
  47. # define DT_RUNPATH 29
  48. #endif
  49. // Low-level byte swapping implementation.
  50. template <size_t s>
  51. struct cmELFByteSwapSize
  52. {
  53. };
  54. void cmELFByteSwap(char* /*unused*/, cmELFByteSwapSize<1> /*unused*/)
  55. {
  56. }
  57. void cmELFByteSwap(char* data, cmELFByteSwapSize<2> /*unused*/)
  58. {
  59. char one_byte;
  60. one_byte = data[0];
  61. data[0] = data[1];
  62. data[1] = one_byte;
  63. }
  64. void cmELFByteSwap(char* data, cmELFByteSwapSize<4> /*unused*/)
  65. {
  66. char one_byte;
  67. one_byte = data[0];
  68. data[0] = data[3];
  69. data[3] = one_byte;
  70. one_byte = data[1];
  71. data[1] = data[2];
  72. data[2] = one_byte;
  73. }
  74. void cmELFByteSwap(char* data, cmELFByteSwapSize<8> /*unused*/)
  75. {
  76. char one_byte;
  77. one_byte = data[0];
  78. data[0] = data[7];
  79. data[7] = one_byte;
  80. one_byte = data[1];
  81. data[1] = data[6];
  82. data[6] = one_byte;
  83. one_byte = data[2];
  84. data[2] = data[5];
  85. data[5] = one_byte;
  86. one_byte = data[3];
  87. data[3] = data[4];
  88. data[4] = one_byte;
  89. }
  90. // Low-level byte swapping interface.
  91. template <typename T>
  92. void cmELFByteSwap(T& x)
  93. {
  94. cmELFByteSwap(reinterpret_cast<char*>(&x), cmELFByteSwapSize<sizeof(T)>());
  95. }
  96. class cmELFInternal
  97. {
  98. public:
  99. typedef cmELF::StringEntry StringEntry;
  100. enum ByteOrderType
  101. {
  102. ByteOrderMSB,
  103. ByteOrderLSB
  104. };
  105. // Construct and take ownership of the file stream object.
  106. cmELFInternal(cmELF* external, std::unique_ptr<cmsys::ifstream>& fin,
  107. ByteOrderType order)
  108. : External(external)
  109. , Stream(*fin.release())
  110. , ByteOrder(order)
  111. , ELFType(cmELF::FileTypeInvalid)
  112. {
  113. // In most cases the processor-specific byte order will match that
  114. // of the target execution environment. If we choose wrong here
  115. // it is fixed when the header is read.
  116. #if KWIML_ABI_ENDIAN_ID == KWIML_ABI_ENDIAN_ID_LITTLE
  117. this->NeedSwap = (this->ByteOrder == ByteOrderMSB);
  118. #elif KWIML_ABI_ENDIAN_ID == KWIML_ABI_ENDIAN_ID_BIG
  119. this->NeedSwap = (this->ByteOrder == ByteOrderLSB);
  120. #else
  121. this->NeedSwap = false; // Final decision is at runtime anyway.
  122. #endif
  123. // We have not yet loaded the section info.
  124. this->DynamicSectionIndex = -1;
  125. }
  126. // Destruct and delete the file stream object.
  127. virtual ~cmELFInternal() { delete &this->Stream; }
  128. // Forward to the per-class implementation.
  129. virtual unsigned int GetNumberOfSections() const = 0;
  130. virtual unsigned long GetDynamicEntryPosition(int j) = 0;
  131. virtual cmELF::DynamicEntryList GetDynamicEntries() = 0;
  132. virtual std::vector<char> EncodeDynamicEntries(
  133. const cmELF::DynamicEntryList&) = 0;
  134. virtual StringEntry const* GetDynamicSectionString(unsigned int tag) = 0;
  135. virtual void PrintInfo(std::ostream& os) const = 0;
  136. // Lookup the SONAME in the DYNAMIC section.
  137. StringEntry const* GetSOName()
  138. {
  139. return this->GetDynamicSectionString(DT_SONAME);
  140. }
  141. // Lookup the RPATH in the DYNAMIC section.
  142. StringEntry const* GetRPath()
  143. {
  144. return this->GetDynamicSectionString(DT_RPATH);
  145. }
  146. // Lookup the RUNPATH in the DYNAMIC section.
  147. StringEntry const* GetRunPath()
  148. {
  149. return this->GetDynamicSectionString(DT_RUNPATH);
  150. }
  151. // Return the recorded ELF type.
  152. cmELF::FileType GetFileType() const { return this->ELFType; }
  153. protected:
  154. // Data common to all ELF class implementations.
  155. // The external cmELF object.
  156. cmELF* External;
  157. // The stream from which to read.
  158. std::istream& Stream;
  159. // The byte order of the ELF file.
  160. ByteOrderType ByteOrder;
  161. // The ELF file type.
  162. cmELF::FileType ELFType;
  163. // Whether we need to byte-swap structures read from the stream.
  164. bool NeedSwap;
  165. // The section header index of the DYNAMIC section (-1 if none).
  166. int DynamicSectionIndex;
  167. // Helper methods for subclasses.
  168. void SetErrorMessage(const char* msg)
  169. {
  170. this->External->ErrorMessage = msg;
  171. this->ELFType = cmELF::FileTypeInvalid;
  172. }
  173. // Store string table entry states.
  174. std::map<unsigned int, StringEntry> DynamicSectionStrings;
  175. };
  176. // Configure the implementation template for 32-bit ELF files.
  177. struct cmELFTypes32
  178. {
  179. typedef Elf32_Ehdr ELF_Ehdr;
  180. typedef Elf32_Shdr ELF_Shdr;
  181. typedef Elf32_Dyn ELF_Dyn;
  182. typedef Elf32_Half ELF_Half;
  183. typedef KWIML_INT_uint32_t tagtype;
  184. static const char* GetName() { return "32-bit"; }
  185. };
  186. // Configure the implementation template for 64-bit ELF files.
  187. #ifndef _SCO_DS
  188. struct cmELFTypes64
  189. {
  190. typedef Elf64_Ehdr ELF_Ehdr;
  191. typedef Elf64_Shdr ELF_Shdr;
  192. typedef Elf64_Dyn ELF_Dyn;
  193. typedef Elf64_Half ELF_Half;
  194. typedef KWIML_INT_uint64_t tagtype;
  195. static const char* GetName() { return "64-bit"; }
  196. };
  197. #endif
  198. // Parser implementation template.
  199. template <class Types>
  200. class cmELFInternalImpl : public cmELFInternal
  201. {
  202. public:
  203. // Copy the ELF file format types from our configuration parameter.
  204. typedef typename Types::ELF_Ehdr ELF_Ehdr;
  205. typedef typename Types::ELF_Shdr ELF_Shdr;
  206. typedef typename Types::ELF_Dyn ELF_Dyn;
  207. typedef typename Types::ELF_Half ELF_Half;
  208. typedef typename Types::tagtype tagtype;
  209. // Construct with a stream and byte swap indicator.
  210. cmELFInternalImpl(cmELF* external, std::unique_ptr<cmsys::ifstream>& fin,
  211. ByteOrderType order);
  212. // Return the number of sections as specified by the ELF header.
  213. unsigned int GetNumberOfSections() const override
  214. {
  215. return static_cast<unsigned int>(this->ELFHeader.e_shnum);
  216. }
  217. // Get the file position of a dynamic section entry.
  218. unsigned long GetDynamicEntryPosition(int j) override;
  219. cmELF::DynamicEntryList GetDynamicEntries() override;
  220. std::vector<char> EncodeDynamicEntries(
  221. const cmELF::DynamicEntryList&) override;
  222. // Lookup a string from the dynamic section with the given tag.
  223. StringEntry const* GetDynamicSectionString(unsigned int tag) override;
  224. // Print information about the ELF file.
  225. void PrintInfo(std::ostream& os) const override
  226. {
  227. os << "ELF " << Types::GetName();
  228. if (this->ByteOrder == ByteOrderMSB) {
  229. os << " MSB";
  230. } else if (this->ByteOrder == ByteOrderLSB) {
  231. os << " LSB";
  232. }
  233. switch (this->ELFType) {
  234. case cmELF::FileTypeInvalid:
  235. os << " invalid file";
  236. break;
  237. case cmELF::FileTypeRelocatableObject:
  238. os << " relocatable object";
  239. break;
  240. case cmELF::FileTypeExecutable:
  241. os << " executable";
  242. break;
  243. case cmELF::FileTypeSharedLibrary:
  244. os << " shared library";
  245. break;
  246. case cmELF::FileTypeCore:
  247. os << " core file";
  248. break;
  249. case cmELF::FileTypeSpecificOS:
  250. os << " os-specific type";
  251. break;
  252. case cmELF::FileTypeSpecificProc:
  253. os << " processor-specific type";
  254. break;
  255. }
  256. os << "\n";
  257. }
  258. private:
  259. // ByteSwap(ELF_Dyn) assumes d_val and d_ptr are the same size
  260. typedef char dyn_size_assert
  261. [sizeof(ELF_Dyn().d_un.d_val) == sizeof(ELF_Dyn().d_un.d_ptr) ? 1 : -1];
  262. void ByteSwap(ELF_Ehdr& elf_header)
  263. {
  264. cmELFByteSwap(elf_header.e_type);
  265. cmELFByteSwap(elf_header.e_machine);
  266. cmELFByteSwap(elf_header.e_version);
  267. cmELFByteSwap(elf_header.e_entry);
  268. cmELFByteSwap(elf_header.e_phoff);
  269. cmELFByteSwap(elf_header.e_shoff);
  270. cmELFByteSwap(elf_header.e_flags);
  271. cmELFByteSwap(elf_header.e_ehsize);
  272. cmELFByteSwap(elf_header.e_phentsize);
  273. cmELFByteSwap(elf_header.e_phnum);
  274. cmELFByteSwap(elf_header.e_shentsize);
  275. cmELFByteSwap(elf_header.e_shnum);
  276. cmELFByteSwap(elf_header.e_shstrndx);
  277. }
  278. void ByteSwap(ELF_Shdr& sec_header)
  279. {
  280. cmELFByteSwap(sec_header.sh_name);
  281. cmELFByteSwap(sec_header.sh_type);
  282. cmELFByteSwap(sec_header.sh_flags);
  283. cmELFByteSwap(sec_header.sh_addr);
  284. cmELFByteSwap(sec_header.sh_offset);
  285. cmELFByteSwap(sec_header.sh_size);
  286. cmELFByteSwap(sec_header.sh_link);
  287. cmELFByteSwap(sec_header.sh_info);
  288. cmELFByteSwap(sec_header.sh_addralign);
  289. cmELFByteSwap(sec_header.sh_entsize);
  290. }
  291. void ByteSwap(ELF_Dyn& dyn)
  292. {
  293. cmELFByteSwap(dyn.d_tag);
  294. cmELFByteSwap(dyn.d_un.d_val);
  295. }
  296. bool FileTypeValid(ELF_Half et)
  297. {
  298. unsigned int eti = static_cast<unsigned int>(et);
  299. if (eti == ET_NONE || eti == ET_REL || eti == ET_EXEC || eti == ET_DYN ||
  300. eti == ET_CORE) {
  301. return true;
  302. }
  303. #if defined(ET_LOOS) && defined(ET_HIOS)
  304. if (eti >= ET_LOOS && eti <= ET_HIOS) {
  305. return true;
  306. }
  307. #endif
  308. #if defined(ET_LOPROC) && defined(ET_HIPROC)
  309. if (eti >= ET_LOPROC && eti <= ET_HIPROC) {
  310. return true;
  311. }
  312. #endif
  313. return false;
  314. }
  315. bool Read(ELF_Ehdr& x)
  316. {
  317. // Read the header from the file.
  318. if (!this->Stream.read(reinterpret_cast<char*>(&x), sizeof(x))) {
  319. return false;
  320. }
  321. // The byte order of ELF header fields may not match that of the
  322. // processor-specific data. The header fields are ordered to
  323. // match the target execution environment, so we may need to
  324. // memorize the order of all platforms based on the e_machine
  325. // value. As a heuristic, if the type is invalid but its
  326. // swapped value is okay then flip our swap mode.
  327. ELF_Half et = x.e_type;
  328. if (this->NeedSwap) {
  329. cmELFByteSwap(et);
  330. }
  331. if (!this->FileTypeValid(et)) {
  332. cmELFByteSwap(et);
  333. if (this->FileTypeValid(et)) {
  334. // The previous byte order guess was wrong. Flip it.
  335. this->NeedSwap = !this->NeedSwap;
  336. }
  337. }
  338. // Fix the byte order of the header.
  339. if (this->NeedSwap) {
  340. ByteSwap(x);
  341. }
  342. return true;
  343. }
  344. bool Read(ELF_Shdr& x)
  345. {
  346. if (this->Stream.read(reinterpret_cast<char*>(&x), sizeof(x)) &&
  347. this->NeedSwap) {
  348. ByteSwap(x);
  349. }
  350. return !this->Stream.fail();
  351. }
  352. bool Read(ELF_Dyn& x)
  353. {
  354. if (this->Stream.read(reinterpret_cast<char*>(&x), sizeof(x)) &&
  355. this->NeedSwap) {
  356. ByteSwap(x);
  357. }
  358. return !this->Stream.fail();
  359. }
  360. bool LoadSectionHeader(ELF_Half i)
  361. {
  362. // Read the section header from the file.
  363. this->Stream.seekg(this->ELFHeader.e_shoff +
  364. this->ELFHeader.e_shentsize * i);
  365. if (!this->Read(this->SectionHeaders[i])) {
  366. return false;
  367. }
  368. // Identify some important sections.
  369. if (this->SectionHeaders[i].sh_type == SHT_DYNAMIC) {
  370. this->DynamicSectionIndex = i;
  371. }
  372. return true;
  373. }
  374. bool LoadDynamicSection();
  375. // Store the main ELF header.
  376. ELF_Ehdr ELFHeader;
  377. // Store all the section headers.
  378. std::vector<ELF_Shdr> SectionHeaders;
  379. // Store all entries of the DYNAMIC section.
  380. std::vector<ELF_Dyn> DynamicSectionEntries;
  381. };
  382. template <class Types>
  383. cmELFInternalImpl<Types>::cmELFInternalImpl(
  384. cmELF* external, std::unique_ptr<cmsys::ifstream>& fin, ByteOrderType order)
  385. : cmELFInternal(external, fin, order)
  386. {
  387. // Read the main header.
  388. if (!this->Read(this->ELFHeader)) {
  389. this->SetErrorMessage("Failed to read main ELF header.");
  390. return;
  391. }
  392. // Determine the ELF file type.
  393. switch (this->ELFHeader.e_type) {
  394. case ET_NONE:
  395. this->SetErrorMessage("ELF file type is NONE.");
  396. return;
  397. case ET_REL:
  398. this->ELFType = cmELF::FileTypeRelocatableObject;
  399. break;
  400. case ET_EXEC:
  401. this->ELFType = cmELF::FileTypeExecutable;
  402. break;
  403. case ET_DYN:
  404. this->ELFType = cmELF::FileTypeSharedLibrary;
  405. break;
  406. case ET_CORE:
  407. this->ELFType = cmELF::FileTypeCore;
  408. break;
  409. default: {
  410. unsigned int eti = static_cast<unsigned int>(this->ELFHeader.e_type);
  411. #if defined(ET_LOOS) && defined(ET_HIOS)
  412. if (eti >= ET_LOOS && eti <= ET_HIOS) {
  413. this->ELFType = cmELF::FileTypeSpecificOS;
  414. break;
  415. }
  416. #endif
  417. #if defined(ET_LOPROC) && defined(ET_HIPROC)
  418. if (eti >= ET_LOPROC && eti <= ET_HIPROC) {
  419. this->ELFType = cmELF::FileTypeSpecificProc;
  420. break;
  421. }
  422. #endif
  423. std::ostringstream e;
  424. e << "Unknown ELF file type " << eti;
  425. this->SetErrorMessage(e.str().c_str());
  426. return;
  427. }
  428. }
  429. // Load the section headers.
  430. this->SectionHeaders.resize(this->ELFHeader.e_shnum);
  431. for (ELF_Half i = 0; i < this->ELFHeader.e_shnum; ++i) {
  432. if (!this->LoadSectionHeader(i)) {
  433. this->SetErrorMessage("Failed to load section headers.");
  434. return;
  435. }
  436. }
  437. }
  438. template <class Types>
  439. bool cmELFInternalImpl<Types>::LoadDynamicSection()
  440. {
  441. // If there is no dynamic section we are done.
  442. if (this->DynamicSectionIndex < 0) {
  443. return false;
  444. }
  445. // If the section was already loaded we are done.
  446. if (!this->DynamicSectionEntries.empty()) {
  447. return true;
  448. }
  449. // If there are no entries we are done.
  450. ELF_Shdr const& sec = this->SectionHeaders[this->DynamicSectionIndex];
  451. if (sec.sh_entsize == 0) {
  452. return false;
  453. }
  454. // Allocate the dynamic section entries.
  455. int n = static_cast<int>(sec.sh_size / sec.sh_entsize);
  456. this->DynamicSectionEntries.resize(n);
  457. // Read each entry.
  458. for (int j = 0; j < n; ++j) {
  459. // Seek to the beginning of the section entry.
  460. this->Stream.seekg(sec.sh_offset + sec.sh_entsize * j);
  461. ELF_Dyn& dyn = this->DynamicSectionEntries[j];
  462. // Try reading the entry.
  463. if (!this->Read(dyn)) {
  464. this->SetErrorMessage("Error reading entry from DYNAMIC section.");
  465. this->DynamicSectionIndex = -1;
  466. return false;
  467. }
  468. }
  469. return true;
  470. }
  471. template <class Types>
  472. unsigned long cmELFInternalImpl<Types>::GetDynamicEntryPosition(int j)
  473. {
  474. if (!this->LoadDynamicSection()) {
  475. return 0;
  476. }
  477. if (j < 0 || j >= static_cast<int>(this->DynamicSectionEntries.size())) {
  478. return 0;
  479. }
  480. ELF_Shdr const& sec = this->SectionHeaders[this->DynamicSectionIndex];
  481. return static_cast<unsigned long>(sec.sh_offset + sec.sh_entsize * j);
  482. }
  483. template <class Types>
  484. cmELF::DynamicEntryList cmELFInternalImpl<Types>::GetDynamicEntries()
  485. {
  486. cmELF::DynamicEntryList result;
  487. // Ensure entries have been read from file
  488. if (!this->LoadDynamicSection()) {
  489. return result;
  490. }
  491. // Copy into public array
  492. result.reserve(this->DynamicSectionEntries.size());
  493. for (ELF_Dyn& dyn : this->DynamicSectionEntries) {
  494. result.emplace_back(dyn.d_tag, dyn.d_un.d_val);
  495. }
  496. return result;
  497. }
  498. template <class Types>
  499. std::vector<char> cmELFInternalImpl<Types>::EncodeDynamicEntries(
  500. const cmELF::DynamicEntryList& entries)
  501. {
  502. std::vector<char> result;
  503. result.reserve(sizeof(ELF_Dyn) * entries.size());
  504. for (auto const& entry : entries) {
  505. // Store the entry in an ELF_Dyn, byteswap it, then serialize to chars
  506. ELF_Dyn dyn;
  507. dyn.d_tag = static_cast<tagtype>(entry.first);
  508. dyn.d_un.d_val = static_cast<tagtype>(entry.second);
  509. if (this->NeedSwap) {
  510. ByteSwap(dyn);
  511. }
  512. char* pdyn = reinterpret_cast<char*>(&dyn);
  513. cmAppend(result, pdyn, pdyn + sizeof(ELF_Dyn));
  514. }
  515. return result;
  516. }
  517. template <class Types>
  518. cmELF::StringEntry const* cmELFInternalImpl<Types>::GetDynamicSectionString(
  519. unsigned int tag)
  520. {
  521. // Short-circuit if already checked.
  522. std::map<unsigned int, StringEntry>::iterator dssi =
  523. this->DynamicSectionStrings.find(tag);
  524. if (dssi != this->DynamicSectionStrings.end()) {
  525. if (dssi->second.Position > 0) {
  526. return &dssi->second;
  527. }
  528. return nullptr;
  529. }
  530. // Create an entry for this tag. Assume it is missing until found.
  531. StringEntry& se = this->DynamicSectionStrings[tag];
  532. se.Position = 0;
  533. se.Size = 0;
  534. se.IndexInSection = -1;
  535. // Try reading the dynamic section.
  536. if (!this->LoadDynamicSection()) {
  537. return nullptr;
  538. }
  539. // Get the string table referenced by the DYNAMIC section.
  540. ELF_Shdr const& sec = this->SectionHeaders[this->DynamicSectionIndex];
  541. if (sec.sh_link >= this->SectionHeaders.size()) {
  542. this->SetErrorMessage("Section DYNAMIC has invalid string table index.");
  543. return nullptr;
  544. }
  545. ELF_Shdr const& strtab = this->SectionHeaders[sec.sh_link];
  546. // Look for the requested entry.
  547. for (typename std::vector<ELF_Dyn>::iterator di =
  548. this->DynamicSectionEntries.begin();
  549. di != this->DynamicSectionEntries.end(); ++di) {
  550. ELF_Dyn& dyn = *di;
  551. if (static_cast<tagtype>(dyn.d_tag) == static_cast<tagtype>(tag)) {
  552. // We found the tag requested.
  553. // Make sure the position given is within the string section.
  554. if (dyn.d_un.d_val >= strtab.sh_size) {
  555. this->SetErrorMessage("Section DYNAMIC references string beyond "
  556. "the end of its string section.");
  557. return nullptr;
  558. }
  559. // Seek to the position reported by the entry.
  560. unsigned long first = static_cast<unsigned long>(dyn.d_un.d_val);
  561. unsigned long last = first;
  562. unsigned long end = static_cast<unsigned long>(strtab.sh_size);
  563. this->Stream.seekg(strtab.sh_offset + first);
  564. // Read the string. It may be followed by more than one NULL
  565. // terminator. Count the total size of the region allocated to
  566. // the string. This assumes that the next string in the table
  567. // is non-empty, but the "chrpath" tool makes the same
  568. // assumption.
  569. bool terminated = false;
  570. char c;
  571. while (last != end && this->Stream.get(c) && !(terminated && c)) {
  572. ++last;
  573. if (c) {
  574. se.Value += c;
  575. } else {
  576. terminated = true;
  577. }
  578. }
  579. // Make sure the whole value was read.
  580. if (!this->Stream) {
  581. this->SetErrorMessage("Dynamic section specifies unreadable RPATH.");
  582. se.Value = "";
  583. return nullptr;
  584. }
  585. // The value has been read successfully. Report it.
  586. se.Position = static_cast<unsigned long>(strtab.sh_offset + first);
  587. se.Size = last - first;
  588. se.IndexInSection =
  589. static_cast<int>(di - this->DynamicSectionEntries.begin());
  590. return &se;
  591. }
  592. }
  593. return nullptr;
  594. }
  595. //============================================================================
  596. // External class implementation.
  597. const long cmELF::TagRPath = DT_RPATH;
  598. const long cmELF::TagRunPath = DT_RUNPATH;
  599. #ifdef DT_MIPS_RLD_MAP_REL
  600. const long cmELF::TagMipsRldMapRel = DT_MIPS_RLD_MAP_REL;
  601. #else
  602. const long cmELF::TagMipsRldMapRel = 0;
  603. #endif
  604. cmELF::cmELF(const char* fname)
  605. : Internal(nullptr)
  606. {
  607. // Try to open the file.
  608. std::unique_ptr<cmsys::ifstream> fin(new cmsys::ifstream(fname));
  609. // Quit now if the file could not be opened.
  610. if (!fin || !*fin) {
  611. this->ErrorMessage = "Error opening input file.";
  612. return;
  613. }
  614. // Read the ELF identification block.
  615. char ident[EI_NIDENT];
  616. if (!fin->read(ident, EI_NIDENT)) {
  617. this->ErrorMessage = "Error reading ELF identification.";
  618. return;
  619. }
  620. if (!fin->seekg(0)) {
  621. this->ErrorMessage = "Error seeking to beginning of file.";
  622. return;
  623. }
  624. // Verify the ELF identification.
  625. if (!(ident[EI_MAG0] == ELFMAG0 && ident[EI_MAG1] == ELFMAG1 &&
  626. ident[EI_MAG2] == ELFMAG2 && ident[EI_MAG3] == ELFMAG3)) {
  627. this->ErrorMessage = "File does not have a valid ELF identification.";
  628. return;
  629. }
  630. // Check the byte order in which the rest of the file is encoded.
  631. cmELFInternal::ByteOrderType order;
  632. if (ident[EI_DATA] == ELFDATA2LSB) {
  633. // File is LSB.
  634. order = cmELFInternal::ByteOrderLSB;
  635. } else if (ident[EI_DATA] == ELFDATA2MSB) {
  636. // File is MSB.
  637. order = cmELFInternal::ByteOrderMSB;
  638. } else {
  639. this->ErrorMessage = "ELF file is not LSB or MSB encoded.";
  640. return;
  641. }
  642. // Check the class of the file and construct the corresponding
  643. // parser implementation.
  644. if (ident[EI_CLASS] == ELFCLASS32) {
  645. // 32-bit ELF
  646. this->Internal = new cmELFInternalImpl<cmELFTypes32>(this, fin, order);
  647. }
  648. #ifndef _SCO_DS
  649. else if (ident[EI_CLASS] == ELFCLASS64) {
  650. // 64-bit ELF
  651. this->Internal = new cmELFInternalImpl<cmELFTypes64>(this, fin, order);
  652. }
  653. #endif
  654. else {
  655. this->ErrorMessage = "ELF file class is not 32-bit or 64-bit.";
  656. return;
  657. }
  658. }
  659. cmELF::~cmELF()
  660. {
  661. delete this->Internal;
  662. }
  663. bool cmELF::Valid() const
  664. {
  665. return this->Internal && this->Internal->GetFileType() != FileTypeInvalid;
  666. }
  667. cmELF::FileType cmELF::GetFileType() const
  668. {
  669. if (this->Valid()) {
  670. return this->Internal->GetFileType();
  671. }
  672. return FileTypeInvalid;
  673. }
  674. unsigned int cmELF::GetNumberOfSections() const
  675. {
  676. if (this->Valid()) {
  677. return this->Internal->GetNumberOfSections();
  678. }
  679. return 0;
  680. }
  681. unsigned long cmELF::GetDynamicEntryPosition(int index) const
  682. {
  683. if (this->Valid()) {
  684. return this->Internal->GetDynamicEntryPosition(index);
  685. }
  686. return 0;
  687. }
  688. cmELF::DynamicEntryList cmELF::GetDynamicEntries() const
  689. {
  690. if (this->Valid()) {
  691. return this->Internal->GetDynamicEntries();
  692. }
  693. return cmELF::DynamicEntryList();
  694. }
  695. std::vector<char> cmELF::EncodeDynamicEntries(
  696. const cmELF::DynamicEntryList& dentries) const
  697. {
  698. if (this->Valid()) {
  699. return this->Internal->EncodeDynamicEntries(dentries);
  700. }
  701. return std::vector<char>();
  702. }
  703. bool cmELF::GetSOName(std::string& soname)
  704. {
  705. if (StringEntry const* se = this->GetSOName()) {
  706. soname = se->Value;
  707. return true;
  708. }
  709. return false;
  710. }
  711. cmELF::StringEntry const* cmELF::GetSOName()
  712. {
  713. if (this->Valid() &&
  714. this->Internal->GetFileType() == cmELF::FileTypeSharedLibrary) {
  715. return this->Internal->GetSOName();
  716. }
  717. return nullptr;
  718. }
  719. cmELF::StringEntry const* cmELF::GetRPath()
  720. {
  721. if (this->Valid() &&
  722. (this->Internal->GetFileType() == cmELF::FileTypeExecutable ||
  723. this->Internal->GetFileType() == cmELF::FileTypeSharedLibrary)) {
  724. return this->Internal->GetRPath();
  725. }
  726. return nullptr;
  727. }
  728. cmELF::StringEntry const* cmELF::GetRunPath()
  729. {
  730. if (this->Valid() &&
  731. (this->Internal->GetFileType() == cmELF::FileTypeExecutable ||
  732. this->Internal->GetFileType() == cmELF::FileTypeSharedLibrary)) {
  733. return this->Internal->GetRunPath();
  734. }
  735. return nullptr;
  736. }
  737. void cmELF::PrintInfo(std::ostream& os) const
  738. {
  739. if (this->Valid()) {
  740. this->Internal->PrintInfo(os);
  741. } else {
  742. os << "Not a valid ELF file.\n";
  743. }
  744. }