DynamicObject.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. /*
  2. * Copyright (c) 2019-2020, Andrew Kaster <akaster@serenityos.org>
  3. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Debug.h>
  8. #include <AK/DeprecatedString.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibELF/DynamicLoader.h>
  11. #include <LibELF/DynamicObject.h>
  12. #include <LibELF/ELFABI.h>
  13. #include <LibELF/Hashes.h>
  14. #include <string.h>
  15. namespace ELF {
  16. DynamicObject::DynamicObject(DeprecatedString const& filepath, VirtualAddress base_address, VirtualAddress dynamic_section_address)
  17. : m_filepath(filepath)
  18. , m_base_address(base_address)
  19. , m_dynamic_address(dynamic_section_address)
  20. {
  21. auto* header = (ElfW(Ehdr)*)base_address.as_ptr();
  22. auto* const phdrs = program_headers();
  23. // Calculate the base address using the PT_LOAD element with the lowest `p_vaddr` (which is the first element)
  24. for (size_t i = 0; i < program_header_count(); ++i) {
  25. auto pheader = phdrs[i];
  26. if (pheader.p_type == PT_LOAD) {
  27. m_elf_base_address = VirtualAddress { pheader.p_vaddr - pheader.p_offset };
  28. break;
  29. }
  30. if (i == program_header_count() - 1) {
  31. VERIFY_NOT_REACHED();
  32. }
  33. }
  34. if (header->e_type == ET_DYN)
  35. m_is_elf_dynamic = true;
  36. else
  37. m_is_elf_dynamic = false;
  38. parse();
  39. }
  40. DynamicObject::~DynamicObject()
  41. {
  42. // TODO: unmap the object
  43. }
  44. void DynamicObject::dump() const
  45. {
  46. if constexpr (DYNAMIC_LOAD_DEBUG) {
  47. StringBuilder builder;
  48. builder.append("\nd_tag tag_name value\n"sv);
  49. size_t num_dynamic_sections = 0;
  50. for_each_dynamic_entry([&](DynamicObject::DynamicEntry const& entry) {
  51. DeprecatedString name_field = DeprecatedString::formatted("({})", name_for_dtag(entry.tag()));
  52. builder.appendff("{:#08x} {:17} {:#08x}\n", entry.tag(), name_field, entry.val());
  53. num_dynamic_sections++;
  54. });
  55. if (m_has_soname)
  56. builder.appendff("DT_SONAME: {}\n", soname()); // FIXME: Validate that this string is null terminated?
  57. if (m_has_rpath)
  58. builder.appendff("DT_RPATH: {}\n", rpath());
  59. if (m_has_runpath)
  60. builder.appendff("DT_RUNPATH: {}\n", runpath());
  61. dbgln("Dynamic section at address {} contains {} entries:", m_dynamic_address.as_ptr(), num_dynamic_sections);
  62. dbgln("{}", builder.string_view());
  63. }
  64. }
  65. void DynamicObject::parse()
  66. {
  67. for_each_dynamic_entry([&](DynamicEntry const& entry) {
  68. switch (entry.tag()) {
  69. case DT_INIT:
  70. m_init_offset = entry.ptr() - m_elf_base_address.get();
  71. break;
  72. case DT_FINI:
  73. m_fini_offset = entry.ptr() - m_elf_base_address.get();
  74. break;
  75. case DT_INIT_ARRAY:
  76. m_init_array_offset = entry.ptr() - m_elf_base_address.get();
  77. break;
  78. case DT_INIT_ARRAYSZ:
  79. m_init_array_size = entry.val();
  80. break;
  81. case DT_FINI_ARRAY:
  82. m_fini_array_offset = entry.ptr() - m_elf_base_address.get();
  83. break;
  84. case DT_FINI_ARRAYSZ:
  85. m_fini_array_size = entry.val();
  86. break;
  87. case DT_HASH:
  88. // Use SYSV hash only if GNU hash is not available
  89. if (m_hash_type == HashType::SYSV) {
  90. m_hash_table_offset = entry.ptr() - m_elf_base_address.get();
  91. }
  92. break;
  93. case DT_GNU_HASH:
  94. m_hash_type = HashType::GNU;
  95. m_hash_table_offset = entry.ptr() - m_elf_base_address.get();
  96. break;
  97. case DT_SYMTAB:
  98. m_symbol_table_offset = entry.ptr() - m_elf_base_address.get();
  99. break;
  100. case DT_STRTAB:
  101. m_string_table_offset = entry.ptr() - m_elf_base_address.get();
  102. break;
  103. case DT_STRSZ:
  104. m_size_of_string_table = entry.val();
  105. break;
  106. case DT_SYMENT:
  107. m_size_of_symbol_table_entry = entry.val();
  108. break;
  109. case DT_PLTGOT:
  110. m_procedure_linkage_table_offset = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  111. break;
  112. case DT_PLTRELSZ:
  113. m_size_of_plt_relocation_entry_list = entry.val();
  114. break;
  115. case DT_PLTREL:
  116. m_procedure_linkage_table_relocation_type = entry.val();
  117. VERIFY(m_procedure_linkage_table_relocation_type & (DT_REL | DT_RELA));
  118. break;
  119. case DT_JMPREL:
  120. m_plt_relocation_offset_location = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  121. break;
  122. case DT_RELA:
  123. m_addend_used = true;
  124. [[fallthrough]];
  125. case DT_REL:
  126. m_relocation_table_offset = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  127. break;
  128. case DT_RELASZ:
  129. case DT_RELSZ:
  130. m_size_of_relocation_table = entry.val();
  131. break;
  132. case DT_RELAENT:
  133. case DT_RELENT:
  134. m_size_of_relocation_entry = entry.val();
  135. break;
  136. case DT_RELACOUNT:
  137. case DT_RELCOUNT:
  138. m_number_of_relocations = entry.val();
  139. break;
  140. case DT_RELR:
  141. m_relr_relocation_table_offset = entry.ptr() - m_elf_base_address.get();
  142. break;
  143. case DT_RELRSZ:
  144. m_size_of_relr_relocation_table = entry.val();
  145. break;
  146. case DT_RELRENT:
  147. m_size_of_relr_relocations_entry = entry.val();
  148. break;
  149. case DT_FLAGS:
  150. m_dt_flags = entry.val();
  151. break;
  152. case DT_TEXTREL:
  153. m_dt_flags |= DF_TEXTREL; // This tag seems to exist for legacy reasons only?
  154. break;
  155. case DT_SONAME:
  156. m_soname_index = entry.val();
  157. m_has_soname = true;
  158. break;
  159. case DT_BIND_NOW:
  160. m_dt_flags |= DF_BIND_NOW;
  161. break;
  162. case DT_RPATH:
  163. m_rpath_index = entry.val();
  164. m_has_rpath = true;
  165. break;
  166. case DT_RUNPATH:
  167. m_runpath_index = entry.val();
  168. m_has_runpath = true;
  169. break;
  170. case DT_DEBUG:
  171. break;
  172. case DT_FLAGS_1:
  173. break;
  174. case DT_NEEDED:
  175. // We handle these in for_each_needed_library
  176. break;
  177. case DT_SYMBOLIC:
  178. break;
  179. default:
  180. dbgln("DynamicObject: DYNAMIC tag handling not implemented for DT_{} ({}) in {}", name_for_dtag(entry.tag()), entry.tag(), m_filepath);
  181. break;
  182. }
  183. });
  184. if (!m_size_of_relocation_entry) {
  185. // TODO: FIXME, this shouldn't be hardcoded
  186. // The reason we need this here is that for some reason, when there only PLT relocations, the compiler
  187. // doesn't insert a 'PLTRELSZ' entry to the dynamic section
  188. m_size_of_relocation_entry = sizeof(ElfW(Rel));
  189. }
  190. auto hash_section_address = hash_section().address().as_ptr();
  191. // TODO: consider base address - it might not be zero
  192. auto num_hash_chains = ((u32*)hash_section_address)[1];
  193. m_symbol_count = num_hash_chains;
  194. }
  195. DynamicObject::Relocation DynamicObject::RelocationSection::relocation(unsigned index) const
  196. {
  197. VERIFY(index < entry_count());
  198. unsigned offset_in_section = index * entry_size();
  199. auto relocation_address = (ElfW(Rela)*)address().offset(offset_in_section).as_ptr();
  200. return Relocation(m_dynamic, *relocation_address, offset_in_section, m_addend_used);
  201. }
  202. DynamicObject::Relocation DynamicObject::RelocationSection::relocation_at_offset(unsigned offset) const
  203. {
  204. VERIFY(offset <= (m_section_size_bytes - m_entry_size));
  205. auto relocation_address = (ElfW(Rela)*)address().offset(offset).as_ptr();
  206. return Relocation(m_dynamic, *relocation_address, offset, m_addend_used);
  207. }
  208. DynamicObject::Symbol DynamicObject::symbol(unsigned index) const
  209. {
  210. auto symbol_section = Section(*this, m_symbol_table_offset, (m_symbol_count * m_size_of_symbol_table_entry), m_size_of_symbol_table_entry, "DT_SYMTAB"sv);
  211. auto symbol_entry = (ElfW(Sym)*)symbol_section.address().offset(index * symbol_section.entry_size()).as_ptr();
  212. return Symbol(*this, index, *symbol_entry);
  213. }
  214. DynamicObject::Section DynamicObject::init_section() const
  215. {
  216. return Section(*this, m_init_offset, sizeof(void (*)()), sizeof(void (*)()), "DT_INIT"sv);
  217. }
  218. DynamicObject::Section DynamicObject::fini_section() const
  219. {
  220. return Section(*this, m_fini_offset, sizeof(void (*)()), sizeof(void (*)()), "DT_FINI"sv);
  221. }
  222. DynamicObject::Section DynamicObject::init_array_section() const
  223. {
  224. return Section(*this, m_init_array_offset, m_init_array_size, sizeof(void (*)()), "DT_INIT_ARRAY"sv);
  225. }
  226. DynamicObject::Section DynamicObject::fini_array_section() const
  227. {
  228. return Section(*this, m_fini_array_offset, m_fini_array_size, sizeof(void (*)()), "DT_FINI_ARRAY"sv);
  229. }
  230. DynamicObject::RelocationSection DynamicObject::relocation_section() const
  231. {
  232. return RelocationSection(Section(*this, m_relocation_table_offset, m_size_of_relocation_table, m_size_of_relocation_entry, "DT_REL"sv), m_addend_used);
  233. }
  234. DynamicObject::RelocationSection DynamicObject::plt_relocation_section() const
  235. {
  236. return RelocationSection(Section(*this, m_plt_relocation_offset_location, m_size_of_plt_relocation_entry_list, m_size_of_relocation_entry, "DT_JMPREL"sv), m_procedure_linkage_table_relocation_type & DT_RELA);
  237. }
  238. DynamicObject::Section DynamicObject::relr_relocation_section() const
  239. {
  240. return Section(*this, m_relr_relocation_table_offset, m_size_of_relr_relocation_table, m_size_of_relr_relocations_entry, "DT_RELR"sv);
  241. }
  242. ElfW(Half) DynamicObject::program_header_count() const
  243. {
  244. auto* header = (const ElfW(Ehdr)*)m_base_address.as_ptr();
  245. return header->e_phnum;
  246. }
  247. const ElfW(Phdr) * DynamicObject::program_headers() const
  248. {
  249. auto* header = (const ElfW(Ehdr)*)m_base_address.as_ptr();
  250. return (const ElfW(Phdr)*)(m_base_address.as_ptr() + header->e_phoff);
  251. }
  252. auto DynamicObject::HashSection::lookup_sysv_symbol(StringView name, u32 hash_value) const -> Optional<Symbol>
  253. {
  254. u32* hash_table_begin = (u32*)address().as_ptr();
  255. size_t num_buckets = hash_table_begin[0];
  256. // This is here for completeness, but, since we're using the fact that every chain
  257. // will end at chain 0 (which means 'not found'), we don't need to check num_chains.
  258. // Interestingly, num_chains is required to be num_symbols
  259. // size_t num_chains = hash_table_begin[1];
  260. u32* buckets = &hash_table_begin[2];
  261. u32* chains = &buckets[num_buckets];
  262. for (u32 i = buckets[hash_value % num_buckets]; i; i = chains[i]) {
  263. auto symbol = m_dynamic.symbol(i);
  264. if (name == symbol.raw_name()) {
  265. dbgln_if(DYNAMIC_LOAD_DEBUG, "Returning SYSV dynamic symbol with index {} for {}: {}", i, symbol.name(), symbol.address().as_ptr());
  266. return symbol;
  267. }
  268. }
  269. return {};
  270. }
  271. auto DynamicObject::HashSection::lookup_gnu_symbol(StringView name, u32 hash_value) const -> Optional<Symbol>
  272. {
  273. // Algorithm reference: https://ent-voy.blogspot.com/2011/02/
  274. using BloomWord = FlatPtr;
  275. constexpr size_t bloom_word_size = sizeof(BloomWord) * 8;
  276. u32 const* hash_table_begin = (u32*)address().as_ptr();
  277. const size_t num_buckets = hash_table_begin[0];
  278. const size_t num_omitted_symbols = hash_table_begin[1];
  279. const u32 num_maskwords = hash_table_begin[2];
  280. // This works because num_maskwords is required to be a power of 2
  281. const u32 num_maskwords_bitmask = num_maskwords - 1;
  282. const u32 shift2 = hash_table_begin[3];
  283. BloomWord const* bloom_words = (BloomWord const*)&hash_table_begin[4];
  284. u32 const* const buckets = (u32 const*)&bloom_words[num_maskwords];
  285. u32 const* const chains = &buckets[num_buckets];
  286. BloomWord hash1 = hash_value;
  287. BloomWord hash2 = hash1 >> shift2;
  288. const BloomWord bitmask = ((BloomWord)1 << (hash1 % bloom_word_size)) | ((BloomWord)1 << (hash2 % bloom_word_size));
  289. if ((bloom_words[(hash1 / bloom_word_size) & num_maskwords_bitmask] & bitmask) != bitmask)
  290. return {};
  291. size_t current_sym = buckets[hash1 % num_buckets];
  292. if (current_sym == 0)
  293. return {};
  294. u32 const* current_chain = &chains[current_sym - num_omitted_symbols];
  295. for (hash1 &= ~1;; ++current_sym) {
  296. hash2 = *(current_chain++);
  297. if (hash1 == (hash2 & ~1)) {
  298. auto symbol = m_dynamic.symbol(current_sym);
  299. if (name == symbol.raw_name())
  300. return symbol;
  301. }
  302. if (hash2 & 1)
  303. break;
  304. }
  305. return {};
  306. }
  307. StringView DynamicObject::symbol_string_table_string(ElfW(Word) index) const
  308. {
  309. auto const* symbol_string_table_ptr = reinterpret_cast<char const*>(base_address().offset(m_string_table_offset + index).as_ptr());
  310. return StringView { symbol_string_table_ptr, strlen(symbol_string_table_ptr) };
  311. }
  312. char const* DynamicObject::raw_symbol_string_table_string(ElfW(Word) index) const
  313. {
  314. return (char const*)base_address().offset(m_string_table_offset + index).as_ptr();
  315. }
  316. DynamicObject::InitializationFunction DynamicObject::init_section_function() const
  317. {
  318. VERIFY(has_init_section());
  319. return (InitializationFunction)init_section().address().as_ptr();
  320. }
  321. char const* DynamicObject::name_for_dtag(ElfW(Sword) d_tag)
  322. {
  323. switch (d_tag) {
  324. case DT_NULL:
  325. return "NULL"; /* marks end of _DYNAMIC array */
  326. case DT_NEEDED:
  327. return "NEEDED"; /* string table offset of needed lib */
  328. case DT_PLTRELSZ:
  329. return "PLTRELSZ"; /* size of relocation entries in PLT */
  330. case DT_PLTGOT:
  331. return "PLTGOT"; /* address PLT/GOT */
  332. case DT_HASH:
  333. return "HASH"; /* address of symbol hash table */
  334. case DT_STRTAB:
  335. return "STRTAB"; /* address of string table */
  336. case DT_SYMTAB:
  337. return "SYMTAB"; /* address of symbol table */
  338. case DT_RELA:
  339. return "RELA"; /* address of relocation table */
  340. case DT_RELASZ:
  341. return "RELASZ"; /* size of relocation table */
  342. case DT_RELAENT:
  343. return "RELAENT"; /* size of relocation entry */
  344. case DT_STRSZ:
  345. return "STRSZ"; /* size of string table */
  346. case DT_SYMENT:
  347. return "SYMENT"; /* size of symbol table entry */
  348. case DT_INIT:
  349. return "INIT"; /* address of initialization func. */
  350. case DT_FINI:
  351. return "FINI"; /* address of termination function */
  352. case DT_SONAME:
  353. return "SONAME"; /* string table offset of shared obj */
  354. case DT_RPATH:
  355. return "RPATH"; /* string table offset of library search path */
  356. case DT_SYMBOLIC:
  357. return "SYMBOLIC"; /* start sym search in shared obj. */
  358. case DT_REL:
  359. return "REL"; /* address of rel. tbl. w addends */
  360. case DT_RELSZ:
  361. return "RELSZ"; /* size of DT_REL relocation table */
  362. case DT_RELENT:
  363. return "RELENT"; /* size of DT_REL relocation entry */
  364. case DT_PLTREL:
  365. return "PLTREL"; /* PLT referenced relocation entry */
  366. case DT_DEBUG:
  367. return "DEBUG"; /* bugger */
  368. case DT_TEXTREL:
  369. return "TEXTREL"; /* Allow rel. mod. to unwritable seg */
  370. case DT_JMPREL:
  371. return "JMPREL"; /* add. of PLT's relocation entries */
  372. case DT_BIND_NOW:
  373. return "BIND_NOW"; /* Bind now regardless of env setting */
  374. case DT_INIT_ARRAY:
  375. return "INIT_ARRAY"; /* address of array of init func */
  376. case DT_FINI_ARRAY:
  377. return "FINI_ARRAY"; /* address of array of term func */
  378. case DT_INIT_ARRAYSZ:
  379. return "INIT_ARRAYSZ"; /* size of array of init func */
  380. case DT_FINI_ARRAYSZ:
  381. return "FINI_ARRAYSZ"; /* size of array of term func */
  382. case DT_RUNPATH:
  383. return "RUNPATH"; /* strtab offset of lib search path */
  384. case DT_FLAGS:
  385. return "FLAGS"; /* Set of DF_* flags */
  386. case DT_ENCODING:
  387. return "ENCODING"; /* further DT_* follow encoding rules */
  388. case DT_PREINIT_ARRAY:
  389. return "PREINIT_ARRAY"; /* address of array of preinit func */
  390. case DT_PREINIT_ARRAYSZ:
  391. return "PREINIT_ARRAYSZ"; /* size of array of preinit func */
  392. case DT_LOOS:
  393. return "LOOS"; /* reserved range for OS */
  394. case DT_HIOS:
  395. return "HIOS"; /* specific dynamic array tags */
  396. case DT_LOPROC:
  397. return "LOPROC"; /* reserved range for processor */
  398. case DT_HIPROC:
  399. return "HIPROC"; /* specific dynamic array tags */
  400. case DT_GNU_HASH:
  401. return "GNU_HASH"; /* address of GNU hash table */
  402. case DT_RELACOUNT:
  403. return "RELACOUNT"; /* if present, number of RELATIVE */
  404. case DT_RELCOUNT:
  405. return "RELCOUNT"; /* relocs, which must come first */
  406. case DT_FLAGS_1:
  407. return "FLAGS_1";
  408. case DT_VERDEF:
  409. return "VERDEF";
  410. case DT_VERDEFNUM:
  411. return "VERDEFNUM";
  412. case DT_VERSYM:
  413. return "VERSYM";
  414. case DT_VERNEEDED:
  415. return "VERNEEDED";
  416. case DT_VERNEEDEDNUM:
  417. return "VERNEEDEDNUM";
  418. case DT_RELR:
  419. return "DT_RELR";
  420. case DT_RELRSZ:
  421. return "DT_RELRSZ";
  422. case DT_RELRENT:
  423. return "DT_RELRENT";
  424. default:
  425. return "??";
  426. }
  427. }
  428. auto DynamicObject::lookup_symbol(StringView name) const -> Optional<SymbolLookupResult>
  429. {
  430. return lookup_symbol(HashSymbol { name });
  431. }
  432. auto DynamicObject::lookup_symbol(HashSymbol const& symbol) const -> Optional<SymbolLookupResult>
  433. {
  434. auto result = hash_section().lookup_symbol(symbol);
  435. if (!result.has_value())
  436. return {};
  437. auto symbol_result = result.value();
  438. if (symbol_result.is_undefined())
  439. return {};
  440. return SymbolLookupResult { symbol_result.value(), symbol_result.size(), symbol_result.address(), symbol_result.bind(), symbol_result.type(), this };
  441. }
  442. NonnullRefPtr<DynamicObject> DynamicObject::create(DeprecatedString const& filepath, VirtualAddress base_address, VirtualAddress dynamic_section_address)
  443. {
  444. return adopt_ref(*new DynamicObject(filepath, base_address, dynamic_section_address));
  445. }
  446. u32 DynamicObject::HashSymbol::gnu_hash() const
  447. {
  448. if (!m_gnu_hash.has_value())
  449. m_gnu_hash = compute_gnu_hash(m_name);
  450. return m_gnu_hash.value();
  451. }
  452. u32 DynamicObject::HashSymbol::sysv_hash() const
  453. {
  454. if (!m_sysv_hash.has_value())
  455. m_sysv_hash = compute_sysv_hash(m_name);
  456. return m_sysv_hash.value();
  457. }
  458. void* DynamicObject::symbol_for_name(StringView name)
  459. {
  460. auto result = hash_section().lookup_symbol(name);
  461. if (!result.has_value())
  462. return nullptr;
  463. auto symbol = result.value();
  464. if (symbol.is_undefined())
  465. return nullptr;
  466. return base_address().offset(symbol.value()).as_ptr();
  467. }
  468. } // end namespace ELF