DynamicObject.cpp 19 KB

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