DynamicObject.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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/String.h>
  28. #include <AK/StringBuilder.h>
  29. #include <LibELF/DynamicObject.h>
  30. #include <LibELF/exec_elf.h>
  31. #include <stdio.h>
  32. #include <string.h>
  33. // #define DYNAMIC_OBJECT_VERBOSE
  34. #ifdef DYNAMIC_OBJECT_VERBOSE
  35. # define VERBOSE(fmt, ...) dbgprintf(fmt, ##__VA_ARGS__)
  36. #else
  37. # define VERBOSE(fmt, ...) \
  38. do { \
  39. } while (0)
  40. #endif
  41. namespace ELF {
  42. static const char* name_for_dtag(Elf32_Sword d_tag);
  43. DynamicObject::DynamicObject(VirtualAddress base_address, VirtualAddress dynamic_section_addresss)
  44. : m_base_address(base_address)
  45. , m_dynamic_address(dynamic_section_addresss)
  46. {
  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::format("(%s)", 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.appendf("DT_SONAME: %s\n", soname()); // FIXME: Valdidate that this string is null terminated?
  65. VERBOSE("Dynamic section at address %p contains %zu entries:\n", m_dynamic_address.as_ptr(), num_dynamic_sections);
  66. VERBOSE("%s", builder.to_string().characters());
  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();
  74. break;
  75. case DT_FINI:
  76. m_fini_offset = entry.ptr();
  77. break;
  78. case DT_INIT_ARRAY:
  79. m_init_array_offset = entry.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();
  86. break;
  87. case DT_FINI_ARRAYSZ:
  88. m_fini_array_size = entry.val();
  89. break;
  90. case DT_HASH:
  91. m_hash_table_offset = entry.ptr();
  92. break;
  93. case DT_SYMTAB:
  94. m_symbol_table_offset = entry.ptr();
  95. break;
  96. case DT_STRTAB:
  97. m_string_table_offset = entry.ptr();
  98. break;
  99. case DT_STRSZ:
  100. m_size_of_string_table = entry.val();
  101. break;
  102. case DT_SYMENT:
  103. m_size_of_symbol_table_entry = entry.val();
  104. break;
  105. case DT_PLTGOT:
  106. m_procedure_linkage_table_offset = entry.ptr();
  107. break;
  108. case DT_PLTRELSZ:
  109. m_size_of_plt_relocation_entry_list = entry.val();
  110. break;
  111. case DT_PLTREL:
  112. m_procedure_linkage_table_relocation_type = entry.val();
  113. ASSERT(m_procedure_linkage_table_relocation_type & (DT_REL | DT_RELA));
  114. break;
  115. case DT_JMPREL:
  116. m_plt_relocation_offset_location = entry.ptr();
  117. break;
  118. case DT_RELA:
  119. case DT_REL:
  120. m_relocation_table_offset = entry.ptr();
  121. break;
  122. case DT_RELASZ:
  123. case DT_RELSZ:
  124. m_size_of_relocation_table = entry.val();
  125. break;
  126. case DT_RELAENT:
  127. case DT_RELENT:
  128. m_size_of_relocation_entry = entry.val();
  129. break;
  130. case DT_RELACOUNT:
  131. case DT_RELCOUNT:
  132. m_number_of_relocations = entry.val();
  133. break;
  134. case DT_FLAGS:
  135. m_dt_flags = entry.val();
  136. break;
  137. case DT_TEXTREL:
  138. m_dt_flags |= DF_TEXTREL; // This tag seems to exist for legacy reasons only?
  139. break;
  140. case DT_SONAME:
  141. m_soname_index = entry.val();
  142. m_has_soname = true;
  143. break;
  144. case DT_DEBUG:
  145. break;
  146. case DT_FLAGS_1:
  147. break;
  148. case DT_NEEDED:
  149. // We handle these in for_each_needed_library
  150. break;
  151. default:
  152. dbgprintf("DynamicObject: DYNAMIC tag handling not implemented for DT_%s\n", name_for_dtag(entry.tag()));
  153. printf("DynamicObject: DYNAMIC tag handling not implemented for DT_%s\n", name_for_dtag(entry.tag()));
  154. ASSERT_NOT_REACHED(); // FIXME: Maybe just break out here and return false?
  155. break;
  156. }
  157. return IterationDecision::Continue;
  158. });
  159. if (!m_size_of_relocation_entry) {
  160. // TODO: FIXME, this shouldn't be hardcoded
  161. // The reason we need this here is the for some reason, when there only PLT relocations, the compiler
  162. // doesn't insert a 'PLTRELSZ' entry to the dynamic section
  163. m_size_of_relocation_entry = sizeof(Elf32_Rel);
  164. }
  165. auto hash_section_address = hash_section().address().as_ptr();
  166. auto num_hash_chains = ((u32*)hash_section_address)[1];
  167. m_symbol_count = num_hash_chains;
  168. }
  169. const DynamicObject::Relocation DynamicObject::RelocationSection::relocation(unsigned index) const
  170. {
  171. ASSERT(index < entry_count());
  172. unsigned offset_in_section = index * entry_size();
  173. auto relocation_address = (Elf32_Rel*)address().offset(offset_in_section).as_ptr();
  174. return Relocation(m_dynamic, *relocation_address, offset_in_section);
  175. }
  176. const DynamicObject::Relocation DynamicObject::RelocationSection::relocation_at_offset(unsigned offset) const
  177. {
  178. ASSERT(offset <= (m_section_size_bytes - m_entry_size));
  179. auto relocation_address = (Elf32_Rel*)address().offset(offset).as_ptr();
  180. return Relocation(m_dynamic, *relocation_address, offset);
  181. }
  182. const DynamicObject::Symbol DynamicObject::symbol(unsigned index) const
  183. {
  184. 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");
  185. auto symbol_entry = (Elf32_Sym*)symbol_section.address().offset(index * symbol_section.entry_size()).as_ptr();
  186. return Symbol(*this, index, *symbol_entry);
  187. }
  188. const DynamicObject::Section DynamicObject::init_section() const
  189. {
  190. return Section(*this, m_init_offset, sizeof(void (*)()), sizeof(void (*)()), "DT_INIT");
  191. }
  192. const DynamicObject::Section DynamicObject::fini_section() const
  193. {
  194. return Section(*this, m_fini_offset, sizeof(void (*)()), sizeof(void (*)()), "DT_FINI");
  195. }
  196. const DynamicObject::Section DynamicObject::init_array_section() const
  197. {
  198. return Section(*this, m_init_array_offset, m_init_array_size, sizeof(void (*)()), "DT_INIT_ARRAY");
  199. }
  200. const DynamicObject::Section DynamicObject::fini_array_section() const
  201. {
  202. return Section(*this, m_fini_array_offset, m_fini_array_size, sizeof(void (*)()), "DT_FINI_ARRAY");
  203. }
  204. const DynamicObject::HashSection DynamicObject::hash_section() const
  205. {
  206. return HashSection(Section(*this, m_hash_table_offset, 0, 0, "DT_HASH"), HashType::SYSV);
  207. }
  208. const DynamicObject::RelocationSection DynamicObject::relocation_section() const
  209. {
  210. return RelocationSection(Section(*this, m_relocation_table_offset, m_size_of_relocation_table, m_size_of_relocation_entry, "DT_REL"));
  211. }
  212. const DynamicObject::RelocationSection DynamicObject::plt_relocation_section() const
  213. {
  214. return RelocationSection(Section(*this, m_plt_relocation_offset_location, m_size_of_plt_relocation_entry_list, m_size_of_relocation_entry, "DT_JMPREL"));
  215. }
  216. u32 DynamicObject::HashSection::calculate_elf_hash(const char* name) const
  217. {
  218. // SYSV ELF hash algorithm
  219. // Note that the GNU HASH algorithm has less collisions
  220. uint32_t hash = 0;
  221. uint32_t top_nibble_of_hash = 0;
  222. while (*name != '\0') {
  223. hash = hash << 4;
  224. hash += *name;
  225. name++;
  226. top_nibble_of_hash = hash & 0xF0000000U;
  227. if (top_nibble_of_hash != 0)
  228. hash ^= top_nibble_of_hash >> 24;
  229. hash &= ~top_nibble_of_hash;
  230. }
  231. return hash;
  232. }
  233. u32 DynamicObject::HashSection::calculate_gnu_hash(const char*) const
  234. {
  235. // FIXME: Implement the GNU hash algorithm
  236. ASSERT_NOT_REACHED();
  237. }
  238. const DynamicObject::Symbol DynamicObject::HashSection::lookup_symbol(const char* name) const
  239. {
  240. // FIXME: If we enable gnu hash in the compiler, we should use that here instead
  241. // The algo is way better with less collisions
  242. u32 hash_value = (this->*(m_hash_function))(name);
  243. u32* hash_table_begin = (u32*)address().as_ptr();
  244. size_t num_buckets = hash_table_begin[0];
  245. // This is here for completeness, but, since we're using the fact that every chain
  246. // will end at chain 0 (which means 'not found'), we don't need to check num_chains.
  247. // Interestingly, num_chains is required to be num_symbols
  248. //size_t num_chains = hash_table_begin[1];
  249. u32* buckets = &hash_table_begin[2];
  250. u32* chains = &buckets[num_buckets];
  251. for (u32 i = buckets[hash_value % num_buckets]; i; i = chains[i]) {
  252. auto symbol = m_dynamic.symbol(i);
  253. if (strcmp(name, symbol.name()) == 0) {
  254. #ifdef DYNAMIC_LOAD_DEBUG
  255. dbgprintf("Returning dynamic symbol with index %u for %s: %p\n", i, symbol.name(), symbol.address().as_ptr());
  256. #endif
  257. return symbol;
  258. }
  259. }
  260. return Symbol::create_undefined(m_dynamic);
  261. }
  262. const char* DynamicObject::symbol_string_table_string(Elf32_Word index) const
  263. {
  264. return (const char*)base_address().offset(m_string_table_offset + index).as_ptr();
  265. }
  266. DynamicObject::InitializationFunction DynamicObject::init_section_function() const
  267. {
  268. ASSERT(has_init_section());
  269. return (InitializationFunction)init_section().address().as_ptr();
  270. }
  271. static const char* name_for_dtag(Elf32_Sword d_tag)
  272. {
  273. switch (d_tag) {
  274. case DT_NULL:
  275. return "NULL"; /* marks end of _DYNAMIC array */
  276. case DT_NEEDED:
  277. return "NEEDED"; /* string table offset of needed lib */
  278. case DT_PLTRELSZ:
  279. return "PLTRELSZ"; /* size of relocation entries in PLT */
  280. case DT_PLTGOT:
  281. return "PLTGOT"; /* address PLT/GOT */
  282. case DT_HASH:
  283. return "HASH"; /* address of symbol hash table */
  284. case DT_STRTAB:
  285. return "STRTAB"; /* address of string table */
  286. case DT_SYMTAB:
  287. return "SYMTAB"; /* address of symbol table */
  288. case DT_RELA:
  289. return "RELA"; /* address of relocation table */
  290. case DT_RELASZ:
  291. return "RELASZ"; /* size of relocation table */
  292. case DT_RELAENT:
  293. return "RELAENT"; /* size of relocation entry */
  294. case DT_STRSZ:
  295. return "STRSZ"; /* size of string table */
  296. case DT_SYMENT:
  297. return "SYMENT"; /* size of symbol table entry */
  298. case DT_INIT:
  299. return "INIT"; /* address of initialization func. */
  300. case DT_FINI:
  301. return "FINI"; /* address of termination function */
  302. case DT_SONAME:
  303. return "SONAME"; /* string table offset of shared obj */
  304. case DT_RPATH:
  305. return "RPATH"; /* string table offset of library search path */
  306. case DT_SYMBOLIC:
  307. return "SYMBOLIC"; /* start sym search in shared obj. */
  308. case DT_REL:
  309. return "REL"; /* address of rel. tbl. w addends */
  310. case DT_RELSZ:
  311. return "RELSZ"; /* size of DT_REL relocation table */
  312. case DT_RELENT:
  313. return "RELENT"; /* size of DT_REL relocation entry */
  314. case DT_PLTREL:
  315. return "PLTREL"; /* PLT referenced relocation entry */
  316. case DT_DEBUG:
  317. return "DEBUG"; /* bugger */
  318. case DT_TEXTREL:
  319. return "TEXTREL"; /* Allow rel. mod. to unwritable seg */
  320. case DT_JMPREL:
  321. return "JMPREL"; /* add. of PLT's relocation entries */
  322. case DT_BIND_NOW:
  323. return "BIND_NOW"; /* Bind now regardless of env setting */
  324. case DT_INIT_ARRAY:
  325. return "INIT_ARRAY"; /* address of array of init func */
  326. case DT_FINI_ARRAY:
  327. return "FINI_ARRAY"; /* address of array of term func */
  328. case DT_INIT_ARRAYSZ:
  329. return "INIT_ARRAYSZ"; /* size of array of init func */
  330. case DT_FINI_ARRAYSZ:
  331. return "FINI_ARRAYSZ"; /* size of array of term func */
  332. case DT_RUNPATH:
  333. return "RUNPATH"; /* strtab offset of lib search path */
  334. case DT_FLAGS:
  335. return "FLAGS"; /* Set of DF_* flags */
  336. case DT_ENCODING:
  337. return "ENCODING"; /* further DT_* follow encoding rules */
  338. case DT_PREINIT_ARRAY:
  339. return "PREINIT_ARRAY"; /* address of array of preinit func */
  340. case DT_PREINIT_ARRAYSZ:
  341. return "PREINIT_ARRAYSZ"; /* size of array of preinit func */
  342. case DT_LOOS:
  343. return "LOOS"; /* reserved range for OS */
  344. case DT_HIOS:
  345. return "HIOS"; /* specific dynamic array tags */
  346. case DT_LOPROC:
  347. return "LOPROC"; /* reserved range for processor */
  348. case DT_HIPROC:
  349. return "HIPROC"; /* specific dynamic array tags */
  350. case DT_GNU_HASH:
  351. return "GNU_HASH"; /* address of GNU hash table */
  352. case DT_RELACOUNT:
  353. return "RELACOUNT"; /* if present, number of RELATIVE */
  354. case DT_RELCOUNT:
  355. return "RELCOUNT"; /* relocs, which must come first */
  356. case DT_FLAGS_1:
  357. return "FLAGS_1";
  358. default:
  359. return "??";
  360. }
  361. }
  362. Optional<DynamicObject::SymbolLookupResult> DynamicObject::lookup_symbol(const char* name) const
  363. {
  364. auto res = hash_section().lookup_symbol(name);
  365. if (res.is_undefined())
  366. return {};
  367. return SymbolLookupResult { true, res.value(), (FlatPtr)res.address().as_ptr(), this };
  368. }
  369. NonnullRefPtr<DynamicObject> DynamicObject::construct(VirtualAddress base_address, VirtualAddress dynamic_section_address)
  370. {
  371. return adopt(*new DynamicObject(base_address, dynamic_section_address));
  372. }
  373. // offset is in PLT relocation table
  374. Elf32_Addr DynamicObject::patch_plt_entry(u32 relocation_offset)
  375. {
  376. auto relocation = plt_relocation_section().relocation_at_offset(relocation_offset);
  377. ASSERT(relocation.type() == R_386_JMP_SLOT);
  378. auto sym = relocation.symbol();
  379. u8* relocation_address = relocation.address().as_ptr();
  380. auto res = lookup_symbol(sym);
  381. if (!res.found) {
  382. dbgln("did not find symbol: {} ", sym.name());
  383. ASSERT_NOT_REACHED();
  384. }
  385. u32 symbol_location = res.address;
  386. VERBOSE("DynamicLoader: Jump slot relocation: putting %s (%p) into PLT at %p\n", sym.name(), symbol_location, relocation_address);
  387. *(u32*)relocation_address = symbol_location;
  388. return symbol_location;
  389. }
  390. DynamicObject::SymbolLookupResult DynamicObject::lookup_symbol(const ELF::DynamicObject::Symbol& symbol) const
  391. {
  392. VERBOSE("looking up symbol: %s\n", symbol.name());
  393. if (!symbol.is_undefined()) {
  394. VERBOSE("symbol is defiend in its object\n");
  395. return { true, symbol.value(), (FlatPtr)symbol.address().as_ptr(), &symbol.object() };
  396. }
  397. ASSERT(m_global_symbol_lookup_func);
  398. return m_global_symbol_lookup_func(symbol.name());
  399. }
  400. } // end namespace ELF