DynamicObject.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. /*
  2. * Copyright (c) 2019-2020, Andrew Kaster <andrewdkaster@gmail.com>
  3. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include <AK/Debug.h>
  28. #include <AK/String.h>
  29. #include <AK/StringBuilder.h>
  30. #include <LibELF/DynamicLoader.h>
  31. #include <LibELF/DynamicObject.h>
  32. #include <LibELF/exec_elf.h>
  33. #include <string.h>
  34. namespace ELF {
  35. static const char* name_for_dtag(Elf32_Sword d_tag);
  36. DynamicObject::DynamicObject(VirtualAddress base_address, VirtualAddress dynamic_section_addresss)
  37. : m_base_address(base_address)
  38. , m_dynamic_address(dynamic_section_addresss)
  39. {
  40. auto* header = (Elf32_Ehdr*)base_address.as_ptr();
  41. auto* pheader = (Elf32_Phdr*)(base_address.as_ptr() + header->e_phoff);
  42. m_elf_base_address = VirtualAddress(pheader->p_vaddr - pheader->p_offset);
  43. if (header->e_type == ET_DYN)
  44. m_is_elf_dynamic = true;
  45. else
  46. m_is_elf_dynamic = false;
  47. parse();
  48. }
  49. DynamicObject::~DynamicObject()
  50. {
  51. }
  52. void DynamicObject::dump() const
  53. {
  54. StringBuilder builder;
  55. builder.append("\nd_tag tag_name value\n");
  56. size_t num_dynamic_sections = 0;
  57. for_each_dynamic_entry([&](const DynamicObject::DynamicEntry& entry) {
  58. String name_field = String::formatted("({})", name_for_dtag(entry.tag()));
  59. builder.appendf("0x%08X %-17s0x%X\n", entry.tag(), name_field.characters(), entry.val());
  60. num_dynamic_sections++;
  61. return IterationDecision::Continue;
  62. });
  63. if (m_has_soname)
  64. builder.appendff("DT_SONAME: {}\n", soname()); // FIXME: Valdidate that this string is null terminated?
  65. dbgln_if(DYNAMIC_LOAD_DEBUG, "Dynamic section at address {} contains {} entries:", m_dynamic_address.as_ptr(), num_dynamic_sections);
  66. dbgln_if(DYNAMIC_LOAD_DEBUG, "{}", builder.string_view());
  67. }
  68. void DynamicObject::parse()
  69. {
  70. for_each_dynamic_entry([&](const DynamicEntry& entry) {
  71. switch (entry.tag()) {
  72. case DT_INIT:
  73. m_init_offset = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  74. break;
  75. case DT_FINI:
  76. m_fini_offset = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  77. break;
  78. case DT_INIT_ARRAY:
  79. m_init_array_offset = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  80. break;
  81. case DT_INIT_ARRAYSZ:
  82. m_init_array_size = entry.val();
  83. break;
  84. case DT_FINI_ARRAY:
  85. m_fini_array_offset = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  86. break;
  87. case DT_FINI_ARRAYSZ:
  88. m_fini_array_size = entry.val();
  89. break;
  90. case DT_HASH:
  91. // Use SYSV hash only if GNU hash is not available
  92. if (m_hash_type == HashType::SYSV) {
  93. m_hash_table_offset = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  94. }
  95. break;
  96. case DT_GNU_HASH:
  97. m_hash_type = HashType::GNU;
  98. m_hash_table_offset = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  99. break;
  100. case DT_SYMTAB:
  101. m_symbol_table_offset = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  102. break;
  103. case DT_STRTAB:
  104. m_string_table_offset = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  105. break;
  106. case DT_STRSZ:
  107. m_size_of_string_table = entry.val();
  108. break;
  109. case DT_SYMENT:
  110. m_size_of_symbol_table_entry = entry.val();
  111. break;
  112. case DT_PLTGOT:
  113. m_procedure_linkage_table_offset = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  114. break;
  115. case DT_PLTRELSZ:
  116. m_size_of_plt_relocation_entry_list = entry.val();
  117. break;
  118. case DT_PLTREL:
  119. m_procedure_linkage_table_relocation_type = entry.val();
  120. ASSERT(m_procedure_linkage_table_relocation_type & (DT_REL | DT_RELA));
  121. break;
  122. case DT_JMPREL:
  123. m_plt_relocation_offset_location = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  124. break;
  125. case DT_RELA:
  126. case DT_REL:
  127. m_relocation_table_offset = entry.ptr() - (FlatPtr)m_elf_base_address.as_ptr();
  128. break;
  129. case DT_RELASZ:
  130. case DT_RELSZ:
  131. m_size_of_relocation_table = entry.val();
  132. break;
  133. case DT_RELAENT:
  134. case DT_RELENT:
  135. m_size_of_relocation_entry = entry.val();
  136. break;
  137. case DT_RELACOUNT:
  138. case DT_RELCOUNT:
  139. m_number_of_relocations = entry.val();
  140. break;
  141. case DT_FLAGS:
  142. m_dt_flags = entry.val();
  143. break;
  144. case DT_TEXTREL:
  145. m_dt_flags |= DF_TEXTREL; // This tag seems to exist for legacy reasons only?
  146. break;
  147. case DT_SONAME:
  148. m_soname_index = entry.val();
  149. m_has_soname = true;
  150. break;
  151. case DT_BIND_NOW:
  152. m_dt_flags |= DF_BIND_NOW;
  153. break;
  154. case DT_DEBUG:
  155. break;
  156. case DT_FLAGS_1:
  157. break;
  158. case DT_NEEDED:
  159. // We handle these in for_each_needed_library
  160. break;
  161. default:
  162. dbgln("DynamicObject: DYNAMIC tag handling not implemented for DT_{}", name_for_dtag(entry.tag()));
  163. ASSERT_NOT_REACHED(); // FIXME: Maybe just break out here and return false?
  164. break;
  165. }
  166. return IterationDecision::Continue;
  167. });
  168. if (!m_size_of_relocation_entry) {
  169. // TODO: FIXME, this shouldn't be hardcoded
  170. // The reason we need this here is that for some reason, when there only PLT relocations, the compiler
  171. // doesn't insert a 'PLTRELSZ' entry to the dynamic section
  172. m_size_of_relocation_entry = sizeof(Elf32_Rel);
  173. }
  174. auto hash_section_address = hash_section().address().as_ptr();
  175. // TODO: consider base address - it might not be zero
  176. auto num_hash_chains = ((u32*)hash_section_address)[1];
  177. m_symbol_count = num_hash_chains;
  178. }
  179. DynamicObject::Relocation DynamicObject::RelocationSection::relocation(unsigned index) const
  180. {
  181. ASSERT(index < entry_count());
  182. unsigned offset_in_section = index * entry_size();
  183. auto relocation_address = (Elf32_Rel*)address().offset(offset_in_section).as_ptr();
  184. return Relocation(m_dynamic, *relocation_address, offset_in_section);
  185. }
  186. DynamicObject::Relocation DynamicObject::RelocationSection::relocation_at_offset(unsigned offset) const
  187. {
  188. ASSERT(offset <= (m_section_size_bytes - m_entry_size));
  189. auto relocation_address = (Elf32_Rel*)address().offset(offset).as_ptr();
  190. return Relocation(m_dynamic, *relocation_address, offset);
  191. }
  192. DynamicObject::Symbol DynamicObject::symbol(unsigned index) const
  193. {
  194. 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");
  195. auto symbol_entry = (Elf32_Sym*)symbol_section.address().offset(index * symbol_section.entry_size()).as_ptr();
  196. return Symbol(*this, index, *symbol_entry);
  197. }
  198. DynamicObject::Section DynamicObject::init_section() const
  199. {
  200. return Section(*this, m_init_offset, sizeof(void (*)()), sizeof(void (*)()), "DT_INIT");
  201. }
  202. DynamicObject::Section DynamicObject::fini_section() const
  203. {
  204. return Section(*this, m_fini_offset, sizeof(void (*)()), sizeof(void (*)()), "DT_FINI");
  205. }
  206. DynamicObject::Section DynamicObject::init_array_section() const
  207. {
  208. return Section(*this, m_init_array_offset, m_init_array_size, sizeof(void (*)()), "DT_INIT_ARRAY");
  209. }
  210. DynamicObject::Section DynamicObject::fini_array_section() const
  211. {
  212. return Section(*this, m_fini_array_offset, m_fini_array_size, sizeof(void (*)()), "DT_FINI_ARRAY");
  213. }
  214. DynamicObject::HashSection DynamicObject::hash_section() const
  215. {
  216. const char* section_name = m_hash_type == HashType::SYSV ? "DT_HASH" : "DT_GNU_HASH";
  217. return HashSection(Section(*this, m_hash_table_offset, 0, 0, section_name), m_hash_type);
  218. }
  219. DynamicObject::RelocationSection DynamicObject::relocation_section() const
  220. {
  221. return RelocationSection(Section(*this, m_relocation_table_offset, m_size_of_relocation_table, m_size_of_relocation_entry, "DT_REL"));
  222. }
  223. DynamicObject::RelocationSection DynamicObject::plt_relocation_section() const
  224. {
  225. return RelocationSection(Section(*this, m_plt_relocation_offset_location, m_size_of_plt_relocation_entry_list, m_size_of_relocation_entry, "DT_JMPREL"));
  226. }
  227. u32 DynamicObject::HashSection::calculate_elf_hash(const StringView& name)
  228. {
  229. // SYSV ELF hash algorithm
  230. // Note that the GNU HASH algorithm has less collisions
  231. uint32_t hash = 0;
  232. for (auto ch : name) {
  233. hash = hash << 4;
  234. hash += ch;
  235. const uint32_t top_nibble_of_hash = hash & 0xF0000000U;
  236. hash ^= top_nibble_of_hash >> 24;
  237. hash &= ~top_nibble_of_hash;
  238. }
  239. return hash;
  240. }
  241. u32 DynamicObject::HashSection::calculate_gnu_hash(const StringView& name)
  242. {
  243. // GNU ELF hash algorithm
  244. u32 hash = 5381;
  245. for (auto ch : name)
  246. hash = hash * 33 + ch;
  247. return hash;
  248. }
  249. auto DynamicObject::HashSection::lookup_symbol(const StringView& name) const -> Optional<Symbol>
  250. {
  251. return (this->*(m_lookup_function))(name);
  252. }
  253. auto DynamicObject::HashSection::lookup_elf_symbol(const StringView& name) const -> Optional<Symbol>
  254. {
  255. u32 hash_value = calculate_elf_hash(name);
  256. u32* hash_table_begin = (u32*)address().as_ptr();
  257. size_t num_buckets = hash_table_begin[0];
  258. // This is here for completeness, but, since we're using the fact that every chain
  259. // will end at chain 0 (which means 'not found'), we don't need to check num_chains.
  260. // Interestingly, num_chains is required to be num_symbols
  261. // size_t num_chains = hash_table_begin[1];
  262. u32* buckets = &hash_table_begin[2];
  263. u32* chains = &buckets[num_buckets];
  264. for (u32 i = buckets[hash_value % num_buckets]; i; i = chains[i]) {
  265. auto symbol = m_dynamic.symbol(i);
  266. if (name == symbol.name()) {
  267. dbgln_if(DYNAMIC_LOAD_DEBUG, "Returning SYSV dynamic symbol with index {} for {}: {}", i, symbol.name(), symbol.address().as_ptr());
  268. return symbol;
  269. }
  270. }
  271. return {};
  272. }
  273. auto DynamicObject::HashSection::lookup_gnu_symbol(const StringView& name) const -> Optional<Symbol>
  274. {
  275. // Algorithm reference: https://ent-voy.blogspot.com/2011/02/
  276. // TODO: Handle 64bit bloomwords for ELF_CLASS64
  277. using BloomWord = u32;
  278. constexpr size_t bloom_word_size = sizeof(BloomWord) * 8;
  279. const u32* hash_table_begin = (u32*)address().as_ptr();
  280. const size_t num_buckets = hash_table_begin[0];
  281. const size_t num_omitted_symbols = hash_table_begin[1];
  282. const u32 num_maskwords = hash_table_begin[2];
  283. // This works because num_maskwords is required to be a power of 2
  284. const u32 num_maskwords_bitmask = num_maskwords - 1;
  285. const u32 shift2 = hash_table_begin[3];
  286. const BloomWord* bloom_words = &hash_table_begin[4];
  287. const u32* const buckets = &bloom_words[num_maskwords];
  288. const u32* const chains = &buckets[num_buckets];
  289. BloomWord hash1 = calculate_gnu_hash(name);
  290. BloomWord hash2 = hash1 >> shift2;
  291. const BloomWord bitmask = (1 << (hash1 % bloom_word_size)) | (1 << (hash2 % bloom_word_size));
  292. if ((bloom_words[(hash1 / bloom_word_size) & num_maskwords_bitmask] & bitmask) != bitmask)
  293. return {};
  294. size_t current_sym = buckets[hash1 % num_buckets];
  295. if (current_sym == 0)
  296. return {};
  297. const u32* current_chain = &chains[current_sym - num_omitted_symbols];
  298. for (hash1 &= ~1;; ++current_sym) {
  299. hash2 = *(current_chain++);
  300. auto symbol = m_dynamic.symbol(current_sym);
  301. if ((hash1 == (hash2 & ~1)) && name == symbol.name()) {
  302. dbgln_if(DYNAMIC_LOAD_DEBUG, "Returning GNU dynamic symbol with index {} for {}: {}", current_sym, symbol.name(), symbol.address().as_ptr());
  303. return symbol;
  304. }
  305. if (hash2 & 1) {
  306. break;
  307. }
  308. }
  309. return {};
  310. }
  311. StringView DynamicObject::symbol_string_table_string(Elf32_Word index) const
  312. {
  313. return StringView { (const char*)base_address().offset(m_string_table_offset + index).as_ptr() };
  314. }
  315. DynamicObject::InitializationFunction DynamicObject::init_section_function() const
  316. {
  317. ASSERT(has_init_section());
  318. return (InitializationFunction)init_section().address().as_ptr();
  319. }
  320. static const char* name_for_dtag(Elf32_Sword d_tag)
  321. {
  322. switch (d_tag) {
  323. case DT_NULL:
  324. return "NULL"; /* marks end of _DYNAMIC array */
  325. case DT_NEEDED:
  326. return "NEEDED"; /* string table offset of needed lib */
  327. case DT_PLTRELSZ:
  328. return "PLTRELSZ"; /* size of relocation entries in PLT */
  329. case DT_PLTGOT:
  330. return "PLTGOT"; /* address PLT/GOT */
  331. case DT_HASH:
  332. return "HASH"; /* address of symbol hash table */
  333. case DT_STRTAB:
  334. return "STRTAB"; /* address of string table */
  335. case DT_SYMTAB:
  336. return "SYMTAB"; /* address of symbol table */
  337. case DT_RELA:
  338. return "RELA"; /* address of relocation table */
  339. case DT_RELASZ:
  340. return "RELASZ"; /* size of relocation table */
  341. case DT_RELAENT:
  342. return "RELAENT"; /* size of relocation entry */
  343. case DT_STRSZ:
  344. return "STRSZ"; /* size of string table */
  345. case DT_SYMENT:
  346. return "SYMENT"; /* size of symbol table entry */
  347. case DT_INIT:
  348. return "INIT"; /* address of initialization func. */
  349. case DT_FINI:
  350. return "FINI"; /* address of termination function */
  351. case DT_SONAME:
  352. return "SONAME"; /* string table offset of shared obj */
  353. case DT_RPATH:
  354. return "RPATH"; /* string table offset of library search path */
  355. case DT_SYMBOLIC:
  356. return "SYMBOLIC"; /* start sym search in shared obj. */
  357. case DT_REL:
  358. return "REL"; /* address of rel. tbl. w addends */
  359. case DT_RELSZ:
  360. return "RELSZ"; /* size of DT_REL relocation table */
  361. case DT_RELENT:
  362. return "RELENT"; /* size of DT_REL relocation entry */
  363. case DT_PLTREL:
  364. return "PLTREL"; /* PLT referenced relocation entry */
  365. case DT_DEBUG:
  366. return "DEBUG"; /* bugger */
  367. case DT_TEXTREL:
  368. return "TEXTREL"; /* Allow rel. mod. to unwritable seg */
  369. case DT_JMPREL:
  370. return "JMPREL"; /* add. of PLT's relocation entries */
  371. case DT_BIND_NOW:
  372. return "BIND_NOW"; /* Bind now regardless of env setting */
  373. case DT_INIT_ARRAY:
  374. return "INIT_ARRAY"; /* address of array of init func */
  375. case DT_FINI_ARRAY:
  376. return "FINI_ARRAY"; /* address of array of term func */
  377. case DT_INIT_ARRAYSZ:
  378. return "INIT_ARRAYSZ"; /* size of array of init func */
  379. case DT_FINI_ARRAYSZ:
  380. return "FINI_ARRAYSZ"; /* size of array of term func */
  381. case DT_RUNPATH:
  382. return "RUNPATH"; /* strtab offset of lib search path */
  383. case DT_FLAGS:
  384. return "FLAGS"; /* Set of DF_* flags */
  385. case DT_ENCODING:
  386. return "ENCODING"; /* further DT_* follow encoding rules */
  387. case DT_PREINIT_ARRAY:
  388. return "PREINIT_ARRAY"; /* address of array of preinit func */
  389. case DT_PREINIT_ARRAYSZ:
  390. return "PREINIT_ARRAYSZ"; /* size of array of preinit func */
  391. case DT_LOOS:
  392. return "LOOS"; /* reserved range for OS */
  393. case DT_HIOS:
  394. return "HIOS"; /* specific dynamic array tags */
  395. case DT_LOPROC:
  396. return "LOPROC"; /* reserved range for processor */
  397. case DT_HIPROC:
  398. return "HIPROC"; /* specific dynamic array tags */
  399. case DT_GNU_HASH:
  400. return "GNU_HASH"; /* address of GNU hash table */
  401. case DT_RELACOUNT:
  402. return "RELACOUNT"; /* if present, number of RELATIVE */
  403. case DT_RELCOUNT:
  404. return "RELCOUNT"; /* relocs, which must come first */
  405. case DT_FLAGS_1:
  406. return "FLAGS_1";
  407. default:
  408. return "??";
  409. }
  410. }
  411. auto DynamicObject::lookup_symbol(const StringView& name) const -> Optional<SymbolLookupResult>
  412. {
  413. auto result = hash_section().lookup_symbol(name);
  414. if (!result.has_value())
  415. return {};
  416. auto symbol = result.value();
  417. if (symbol.is_undefined())
  418. return {};
  419. return SymbolLookupResult { symbol.value(), symbol.address(), symbol.bind(), this };
  420. }
  421. NonnullRefPtr<DynamicObject> DynamicObject::create(VirtualAddress base_address, VirtualAddress dynamic_section_address)
  422. {
  423. return adopt(*new DynamicObject(base_address, dynamic_section_address));
  424. }
  425. // offset is in PLT relocation table
  426. VirtualAddress DynamicObject::patch_plt_entry(u32 relocation_offset)
  427. {
  428. auto relocation = plt_relocation_section().relocation_at_offset(relocation_offset);
  429. ASSERT(relocation.type() == R_386_JMP_SLOT);
  430. auto symbol = relocation.symbol();
  431. u8* relocation_address = relocation.address().as_ptr();
  432. auto result = DynamicLoader::lookup_symbol(symbol);
  433. if (!result.has_value()) {
  434. dbgln("did not find symbol: {}", symbol.name());
  435. ASSERT_NOT_REACHED();
  436. }
  437. auto symbol_location = result.value().address;
  438. dbgln_if(DYNAMIC_LOAD_DEBUG, "DynamicLoader: Jump slot relocation: putting {} ({}) into PLT at {}", symbol.name(), symbol_location, (void*)relocation_address);
  439. *(FlatPtr*)relocation_address = symbol_location.get();
  440. return symbol_location;
  441. }
  442. } // end namespace ELF