DynamicObject.cpp 18 KB

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