Loader.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Loader.h"
  27. #include <AK/Demangle.h>
  28. #include <AK/Memory.h>
  29. #include <AK/QuickSort.h>
  30. #ifdef KERNEL
  31. # include <Kernel/VM/MemoryManager.h>
  32. # define do_memcpy copy_to_user
  33. #else
  34. # define do_memcpy memcpy
  35. #endif
  36. //#define Loader_DEBUG
  37. namespace ELF {
  38. Loader::Loader(const u8* buffer, size_t size, bool verbose_logging)
  39. : m_image(buffer, size, verbose_logging)
  40. {
  41. }
  42. Loader::~Loader()
  43. {
  44. }
  45. bool Loader::load()
  46. {
  47. #ifdef Loader_DEBUG
  48. m_image.dump();
  49. #endif
  50. if (!m_image.is_valid())
  51. return false;
  52. m_symbol_count = m_image.symbol_count();
  53. if (!layout())
  54. return false;
  55. return true;
  56. }
  57. bool Loader::layout()
  58. {
  59. bool failed = false;
  60. m_image.for_each_program_header([&](const Image::ProgramHeader& program_header) {
  61. if (program_header.type() == PT_TLS) {
  62. #ifdef KERNEL
  63. auto* tls_image = tls_section_hook(program_header.size_in_memory(), program_header.alignment());
  64. if (!tls_image) {
  65. failed = true;
  66. return;
  67. }
  68. if (!m_image.is_within_image(program_header.raw_data(), program_header.size_in_image())) {
  69. dbg() << "Shenanigans! ELF PT_TLS header sneaks outside of executable.";
  70. failed = true;
  71. return;
  72. }
  73. do_memcpy(tls_image, program_header.raw_data(), program_header.size_in_image());
  74. #endif
  75. return;
  76. }
  77. if (program_header.type() != PT_LOAD)
  78. return;
  79. #ifdef Loader_DEBUG
  80. kprintf("PH: V%p %u r:%u w:%u\n", program_header.vaddr().get(), program_header.size_in_memory(), program_header.is_readable(), program_header.is_writable());
  81. #endif
  82. #ifdef KERNEL
  83. if (program_header.is_writable()) {
  84. auto* allocated_section = alloc_section_hook(
  85. program_header.vaddr(),
  86. program_header.size_in_memory(),
  87. program_header.alignment(),
  88. program_header.is_readable(),
  89. program_header.is_writable(),
  90. String::format("elf-alloc-%s%s", program_header.is_readable() ? "r" : "", program_header.is_writable() ? "w" : ""));
  91. if (!allocated_section) {
  92. failed = true;
  93. return;
  94. }
  95. if (!m_image.is_within_image(program_header.raw_data(), program_header.size_in_image())) {
  96. dbg() << "Shenanigans! Writable ELF PT_LOAD header sneaks outside of executable.";
  97. failed = true;
  98. return;
  99. }
  100. // It's not always the case with PIE executables (and very well shouldn't be) that the
  101. // virtual address in the program header matches the one we end up giving the process.
  102. // In order to copy the data image correctly into memory, we need to copy the data starting at
  103. // the right initial page offset into the pages allocated for the elf_alloc-XX section.
  104. // FIXME: There's an opportunity to munmap, or at least mprotect, the padding space between
  105. // the .text and .data PT_LOAD sections of the executable.
  106. // Accessing it would definitely be a bug.
  107. auto page_offset = program_header.vaddr();
  108. page_offset.mask(~PAGE_MASK);
  109. do_memcpy((u8*)allocated_section + page_offset.get(), program_header.raw_data(), program_header.size_in_image());
  110. } else {
  111. auto* mapped_section = map_section_hook(
  112. program_header.vaddr(),
  113. program_header.size_in_memory(),
  114. program_header.alignment(),
  115. program_header.offset(),
  116. program_header.is_readable(),
  117. program_header.is_writable(),
  118. program_header.is_executable(),
  119. String::format("elf-map-%s%s%s", program_header.is_readable() ? "r" : "", program_header.is_writable() ? "w" : "", program_header.is_executable() ? "x" : ""));
  120. if (!mapped_section) {
  121. failed = true;
  122. }
  123. }
  124. #endif
  125. });
  126. return !failed;
  127. }
  128. char* Loader::symbol_ptr(const char* name) const
  129. {
  130. char* found_ptr = nullptr;
  131. m_image.for_each_symbol([&](const Image::Symbol symbol) {
  132. if (symbol.type() != STT_FUNC)
  133. return IterationDecision::Continue;
  134. if (symbol.name() != name)
  135. return IterationDecision::Continue;
  136. if (m_image.is_executable())
  137. found_ptr = (char*)(size_t)symbol.value();
  138. else
  139. ASSERT_NOT_REACHED();
  140. return IterationDecision::Break;
  141. });
  142. return found_ptr;
  143. }
  144. Optional<Image::Symbol> Loader::find_demangled_function(const String& name) const
  145. {
  146. Optional<Image::Symbol> found;
  147. m_image.for_each_symbol([&](const Image::Symbol symbol) {
  148. if (symbol.type() != STT_FUNC)
  149. return IterationDecision::Continue;
  150. auto demangled = demangle(symbol.name());
  151. auto index_of_paren = demangled.index_of("(");
  152. if (index_of_paren.has_value()) {
  153. demangled = demangled.substring(0, index_of_paren.value());
  154. }
  155. if (demangled != name)
  156. return IterationDecision::Continue;
  157. found = symbol;
  158. return IterationDecision::Break;
  159. });
  160. return found;
  161. }
  162. #ifndef KERNEL
  163. Optional<Image::Symbol> Loader::find_symbol(u32 address, u32* out_offset) const
  164. {
  165. if (!m_symbol_count)
  166. return {};
  167. SortedSymbol* sorted_symbols = nullptr;
  168. # ifdef KERNEL
  169. if (!m_sorted_symbols_region) {
  170. m_sorted_symbols_region = MM.allocate_kernel_region(PAGE_ROUND_UP(m_symbol_count * sizeof(SortedSymbol)), "Sorted symbols", Kernel::Region::Access::Read | Kernel::Region::Access::Write);
  171. sorted_symbols = (SortedSymbol*)m_sorted_symbols_region->vaddr().as_ptr();
  172. size_t index = 0;
  173. m_image.for_each_symbol([&](auto& symbol) {
  174. sorted_symbols[index++] = { symbol.value(), symbol.name() };
  175. return IterationDecision::Continue;
  176. });
  177. quick_sort(sorted_symbols, sorted_symbols + m_symbol_count, [](auto& a, auto& b) {
  178. return a.address < b.address;
  179. });
  180. } else {
  181. sorted_symbols = (SortedSymbol*)m_sorted_symbols_region->vaddr().as_ptr();
  182. }
  183. # else
  184. if (m_sorted_symbols.is_empty()) {
  185. m_sorted_symbols.ensure_capacity(m_symbol_count);
  186. m_image.for_each_symbol([this](auto& symbol) {
  187. m_sorted_symbols.append({ symbol.value(), symbol.name(), {}, symbol });
  188. return IterationDecision::Continue;
  189. });
  190. quick_sort(m_sorted_symbols, [](auto& a, auto& b) {
  191. return a.address < b.address;
  192. });
  193. }
  194. sorted_symbols = m_sorted_symbols.data();
  195. # endif
  196. for (size_t i = 0; i < m_symbol_count; ++i) {
  197. if (sorted_symbols[i].address > address) {
  198. if (i == 0)
  199. return {};
  200. auto& symbol = sorted_symbols[i - 1];
  201. if (out_offset)
  202. *out_offset = address - symbol.address;
  203. return symbol.symbol;
  204. }
  205. }
  206. return {};
  207. }
  208. #endif
  209. String Loader::symbolicate(u32 address, u32* out_offset) const
  210. {
  211. if (!m_symbol_count) {
  212. if (out_offset)
  213. *out_offset = 0;
  214. return "??";
  215. }
  216. SortedSymbol* sorted_symbols = nullptr;
  217. #ifdef KERNEL
  218. if (!m_sorted_symbols_region) {
  219. m_sorted_symbols_region = MM.allocate_kernel_region(PAGE_ROUND_UP(m_symbol_count * sizeof(SortedSymbol)), "Sorted symbols", Kernel::Region::Access::Read | Kernel::Region::Access::Write);
  220. sorted_symbols = (SortedSymbol*)m_sorted_symbols_region->vaddr().as_ptr();
  221. size_t index = 0;
  222. m_image.for_each_symbol([&](auto& symbol) {
  223. sorted_symbols[index++] = { symbol.value(), symbol.name() };
  224. return IterationDecision::Continue;
  225. });
  226. quick_sort(sorted_symbols, sorted_symbols + m_symbol_count, [](auto& a, auto& b) {
  227. return a.address < b.address;
  228. });
  229. } else {
  230. sorted_symbols = (SortedSymbol*)m_sorted_symbols_region->vaddr().as_ptr();
  231. }
  232. #else
  233. if (m_sorted_symbols.is_empty()) {
  234. m_sorted_symbols.ensure_capacity(m_symbol_count);
  235. m_image.for_each_symbol([this](auto& symbol) {
  236. m_sorted_symbols.append({ symbol.value(), symbol.name(), {}, {} });
  237. return IterationDecision::Continue;
  238. });
  239. quick_sort(m_sorted_symbols, [](auto& a, auto& b) {
  240. return a.address < b.address;
  241. });
  242. }
  243. sorted_symbols = m_sorted_symbols.data();
  244. #endif
  245. for (size_t i = 0; i < m_symbol_count; ++i) {
  246. if (sorted_symbols[i].address > address) {
  247. if (i == 0) {
  248. if (out_offset)
  249. *out_offset = 0;
  250. return "!!";
  251. }
  252. auto& symbol = sorted_symbols[i - 1];
  253. #ifdef KERNEL
  254. auto demangled_name = demangle(symbol.name);
  255. #else
  256. auto& demangled_name = symbol.demangled_name;
  257. if (demangled_name.is_null())
  258. demangled_name = demangle(symbol.name);
  259. #endif
  260. if (out_offset) {
  261. *out_offset = address - symbol.address;
  262. return demangled_name;
  263. }
  264. return String::format("%s +%u", demangled_name.characters(), address - symbol.address);
  265. }
  266. }
  267. if (out_offset)
  268. *out_offset = 0;
  269. return "??";
  270. }
  271. } // end namespace ELF