DynamicObject.cpp 18 KB

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