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