Loader.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. #ifndef KERNEL
  137. Optional<Image::Symbol> Loader::find_symbol(u32 address, u32* out_offset) const
  138. {
  139. if (!m_symbol_count)
  140. return {};
  141. SortedSymbol* sorted_symbols = nullptr;
  142. # ifdef KERNEL
  143. if (!m_sorted_symbols_region) {
  144. 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);
  145. sorted_symbols = (SortedSymbol*)m_sorted_symbols_region->vaddr().as_ptr();
  146. size_t index = 0;
  147. m_image.for_each_symbol([&](auto& symbol) {
  148. sorted_symbols[index++] = { symbol.value(), symbol.name() };
  149. return IterationDecision::Continue;
  150. });
  151. quick_sort(sorted_symbols, sorted_symbols + m_symbol_count, [](auto& a, auto& b) {
  152. return a.address < b.address;
  153. });
  154. } else {
  155. sorted_symbols = (SortedSymbol*)m_sorted_symbols_region->vaddr().as_ptr();
  156. }
  157. # else
  158. if (m_sorted_symbols.is_empty()) {
  159. m_sorted_symbols.ensure_capacity(m_symbol_count);
  160. m_image.for_each_symbol([this](auto& symbol) {
  161. m_sorted_symbols.append({ symbol.value(), symbol.name(), {}, symbol });
  162. return IterationDecision::Continue;
  163. });
  164. quick_sort(m_sorted_symbols, [](auto& a, auto& b) {
  165. return a.address < b.address;
  166. });
  167. }
  168. sorted_symbols = m_sorted_symbols.data();
  169. # endif
  170. for (size_t i = 0; i < m_symbol_count; ++i) {
  171. if (sorted_symbols[i].address > address) {
  172. if (i == 0)
  173. return {};
  174. auto& symbol = sorted_symbols[i - 1];
  175. if (out_offset)
  176. *out_offset = address - symbol.address;
  177. return symbol.symbol;
  178. }
  179. }
  180. return {};
  181. }
  182. #endif
  183. String Loader::symbolicate(u32 address, u32* out_offset) const
  184. {
  185. if (!m_symbol_count) {
  186. if (out_offset)
  187. *out_offset = 0;
  188. return "??";
  189. }
  190. SortedSymbol* sorted_symbols = nullptr;
  191. #ifdef KERNEL
  192. if (!m_sorted_symbols_region) {
  193. 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);
  194. sorted_symbols = (SortedSymbol*)m_sorted_symbols_region->vaddr().as_ptr();
  195. size_t index = 0;
  196. m_image.for_each_symbol([&](auto& symbol) {
  197. sorted_symbols[index++] = { symbol.value(), symbol.name() };
  198. return IterationDecision::Continue;
  199. });
  200. quick_sort(sorted_symbols, sorted_symbols + m_symbol_count, [](auto& a, auto& b) {
  201. return a.address < b.address;
  202. });
  203. } else {
  204. sorted_symbols = (SortedSymbol*)m_sorted_symbols_region->vaddr().as_ptr();
  205. }
  206. #else
  207. if (m_sorted_symbols.is_empty()) {
  208. m_sorted_symbols.ensure_capacity(m_symbol_count);
  209. m_image.for_each_symbol([this](auto& symbol) {
  210. m_sorted_symbols.append({ symbol.value(), symbol.name(), {}, {} });
  211. return IterationDecision::Continue;
  212. });
  213. quick_sort(m_sorted_symbols, [](auto& a, auto& b) {
  214. return a.address < b.address;
  215. });
  216. }
  217. sorted_symbols = m_sorted_symbols.data();
  218. #endif
  219. for (size_t i = 0; i < m_symbol_count; ++i) {
  220. if (sorted_symbols[i].address > address) {
  221. if (i == 0) {
  222. if (out_offset)
  223. *out_offset = 0;
  224. return "!!";
  225. }
  226. auto& symbol = sorted_symbols[i - 1];
  227. #ifdef KERNEL
  228. auto demangled_name = demangle(symbol.name);
  229. #else
  230. auto& demangled_name = symbol.demangled_name;
  231. if (demangled_name.is_null()) {
  232. demangled_name = demangle(symbol.name);
  233. }
  234. #endif
  235. if (out_offset) {
  236. *out_offset = address - symbol.address;
  237. return demangled_name;
  238. }
  239. return String::format("%s +%u", demangled_name.characters(), address - symbol.address);
  240. }
  241. }
  242. if (out_offset)
  243. *out_offset = 0;
  244. return "??";
  245. }
  246. } // end namespace ELF