DynamicObject.cpp 19 KB

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