Loader.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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, String&& name, bool verbose_logging)
  39. : m_image(buffer, size, verbose_logging)
  40. , m_name(move(name))
  41. {
  42. if (m_image.is_valid())
  43. m_symbol_count = m_image.symbol_count();
  44. }
  45. Loader::~Loader()
  46. {
  47. }
  48. bool Loader::load()
  49. {
  50. #ifdef Loader_DEBUG
  51. m_image.dump();
  52. #endif
  53. if (!m_image.is_valid())
  54. return false;
  55. if (!layout())
  56. return false;
  57. return true;
  58. }
  59. bool Loader::layout()
  60. {
  61. bool failed = false;
  62. m_image.for_each_program_header([&](const Image::ProgramHeader& program_header) {
  63. if (program_header.type() == PT_TLS) {
  64. #ifdef KERNEL
  65. auto* tls_image = tls_section_hook(program_header.size_in_memory(), program_header.alignment());
  66. if (!tls_image) {
  67. failed = true;
  68. return;
  69. }
  70. if (!m_image.is_within_image(program_header.raw_data(), program_header.size_in_image())) {
  71. dbg() << "Shenanigans! ELF PT_TLS header sneaks outside of executable.";
  72. failed = true;
  73. return;
  74. }
  75. if (!do_memcpy(tls_image, program_header.raw_data(), program_header.size_in_image())) {
  76. failed = false;
  77. return;
  78. }
  79. #endif
  80. return;
  81. }
  82. if (program_header.type() != PT_LOAD)
  83. return;
  84. #ifdef KERNEL
  85. # ifdef Loader_DEBUG
  86. 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());
  87. # endif
  88. if (program_header.is_writable()) {
  89. auto* allocated_section = alloc_section_hook(
  90. program_header.vaddr(),
  91. program_header.size_in_memory(),
  92. program_header.alignment(),
  93. program_header.is_readable(),
  94. program_header.is_writable(),
  95. String::format("%s-alloc-%s%s", m_name.is_empty() ? "elf" : m_name.characters(), program_header.is_readable() ? "r" : "", program_header.is_writable() ? "w" : ""));
  96. if (!allocated_section) {
  97. failed = true;
  98. return;
  99. }
  100. if (!m_image.is_within_image(program_header.raw_data(), program_header.size_in_image())) {
  101. dbg() << "Shenanigans! Writable ELF PT_LOAD header sneaks outside of executable.";
  102. failed = true;
  103. return;
  104. }
  105. // It's not always the case with PIE executables (and very well shouldn't be) that the
  106. // virtual address in the program header matches the one we end up giving the process.
  107. // In order to copy the data image correctly into memory, we need to copy the data starting at
  108. // the right initial page offset into the pages allocated for the elf_alloc-XX section.
  109. // FIXME: There's an opportunity to munmap, or at least mprotect, the padding space between
  110. // the .text and .data PT_LOAD sections of the executable.
  111. // Accessing it would definitely be a bug.
  112. auto page_offset = program_header.vaddr();
  113. page_offset.mask(~PAGE_MASK);
  114. if (!do_memcpy((u8*)allocated_section + page_offset.get(), program_header.raw_data(), program_header.size_in_image())) {
  115. failed = false;
  116. return;
  117. }
  118. } else {
  119. auto* mapped_section = map_section_hook(
  120. program_header.vaddr(),
  121. program_header.size_in_memory(),
  122. program_header.alignment(),
  123. program_header.offset(),
  124. program_header.is_readable(),
  125. program_header.is_writable(),
  126. program_header.is_executable(),
  127. String::format("%s-map-%s%s%s", m_name.is_empty() ? "elf" : m_name.characters(), program_header.is_readable() ? "r" : "", program_header.is_writable() ? "w" : "", program_header.is_executable() ? "x" : ""));
  128. if (!mapped_section) {
  129. failed = true;
  130. }
  131. }
  132. #endif
  133. });
  134. return !failed;
  135. }
  136. Optional<Image::Symbol> Loader::find_demangled_function(const String& name) const
  137. {
  138. Optional<Image::Symbol> found;
  139. m_image.for_each_symbol([&](const Image::Symbol symbol) {
  140. if (symbol.type() != STT_FUNC)
  141. return IterationDecision::Continue;
  142. auto demangled = demangle(symbol.name());
  143. auto index_of_paren = demangled.index_of("(");
  144. if (index_of_paren.has_value()) {
  145. demangled = demangled.substring(0, index_of_paren.value());
  146. }
  147. if (demangled != name)
  148. return IterationDecision::Continue;
  149. found = symbol;
  150. return IterationDecision::Break;
  151. });
  152. return found;
  153. }
  154. #ifndef KERNEL
  155. Optional<Image::Symbol> Loader::find_symbol(u32 address, u32* out_offset) const
  156. {
  157. if (!m_symbol_count)
  158. return {};
  159. SortedSymbol* sorted_symbols = nullptr;
  160. # ifdef KERNEL
  161. if (!m_sorted_symbols_region) {
  162. 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);
  163. sorted_symbols = (SortedSymbol*)m_sorted_symbols_region->vaddr().as_ptr();
  164. size_t index = 0;
  165. m_image.for_each_symbol([&](auto& symbol) {
  166. sorted_symbols[index++] = { symbol.value(), symbol.name() };
  167. return IterationDecision::Continue;
  168. });
  169. quick_sort(sorted_symbols, sorted_symbols + m_symbol_count, [](auto& a, auto& b) {
  170. return a.address < b.address;
  171. });
  172. } else {
  173. sorted_symbols = (SortedSymbol*)m_sorted_symbols_region->vaddr().as_ptr();
  174. }
  175. # else
  176. if (m_sorted_symbols.is_empty()) {
  177. m_sorted_symbols.ensure_capacity(m_symbol_count);
  178. m_image.for_each_symbol([this](auto& symbol) {
  179. m_sorted_symbols.append({ symbol.value(), symbol.name(), {}, symbol });
  180. return IterationDecision::Continue;
  181. });
  182. quick_sort(m_sorted_symbols, [](auto& a, auto& b) {
  183. return a.address < b.address;
  184. });
  185. }
  186. sorted_symbols = m_sorted_symbols.data();
  187. # endif
  188. for (size_t i = 0; i < m_symbol_count; ++i) {
  189. if (sorted_symbols[i].address > address) {
  190. if (i == 0)
  191. return {};
  192. auto& symbol = sorted_symbols[i - 1];
  193. if (out_offset)
  194. *out_offset = address - symbol.address;
  195. return symbol.symbol;
  196. }
  197. }
  198. return {};
  199. }
  200. #endif
  201. String Loader::symbolicate(u32 address, u32* out_offset) const
  202. {
  203. if (!m_symbol_count) {
  204. if (out_offset)
  205. *out_offset = 0;
  206. return "??";
  207. }
  208. SortedSymbol* sorted_symbols = nullptr;
  209. #ifdef KERNEL
  210. if (!m_sorted_symbols_region) {
  211. 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);
  212. sorted_symbols = (SortedSymbol*)m_sorted_symbols_region->vaddr().as_ptr();
  213. size_t index = 0;
  214. m_image.for_each_symbol([&](auto& symbol) {
  215. sorted_symbols[index++] = { symbol.value(), symbol.name() };
  216. return IterationDecision::Continue;
  217. });
  218. quick_sort(sorted_symbols, sorted_symbols + m_symbol_count, [](auto& a, auto& b) {
  219. return a.address < b.address;
  220. });
  221. } else {
  222. sorted_symbols = (SortedSymbol*)m_sorted_symbols_region->vaddr().as_ptr();
  223. }
  224. #else
  225. if (m_sorted_symbols.is_empty()) {
  226. m_sorted_symbols.ensure_capacity(m_symbol_count);
  227. m_image.for_each_symbol([this](auto& symbol) {
  228. m_sorted_symbols.append({ symbol.value(), symbol.name(), {}, {} });
  229. return IterationDecision::Continue;
  230. });
  231. quick_sort(m_sorted_symbols, [](auto& a, auto& b) {
  232. return a.address < b.address;
  233. });
  234. }
  235. sorted_symbols = m_sorted_symbols.data();
  236. #endif
  237. for (size_t i = 0; i < m_symbol_count; ++i) {
  238. if (sorted_symbols[i].address > address) {
  239. if (i == 0) {
  240. if (out_offset)
  241. *out_offset = 0;
  242. return "!!";
  243. }
  244. auto& symbol = sorted_symbols[i - 1];
  245. #ifdef KERNEL
  246. auto demangled_name = demangle(symbol.name);
  247. #else
  248. auto& demangled_name = symbol.demangled_name;
  249. if (demangled_name.is_null()) {
  250. demangled_name = demangle(symbol.name);
  251. }
  252. #endif
  253. if (out_offset) {
  254. *out_offset = address - symbol.address;
  255. return demangled_name;
  256. }
  257. return String::format("%s +%u", demangled_name.characters(), address - symbol.address);
  258. }
  259. }
  260. if (out_offset)
  261. *out_offset = 0;
  262. return "??";
  263. }
  264. } // end namespace ELF