DynamicLinker.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. * Copyright (c) 2021, the SerenityOS developers.
  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/HashMap.h>
  29. #include <AK/HashTable.h>
  30. #include <AK/LexicalPath.h>
  31. #include <AK/LogStream.h>
  32. #include <AK/ScopeGuard.h>
  33. #include <Kernel/API/Syscall.h>
  34. #include <LibC/mman.h>
  35. #include <LibC/stdio.h>
  36. #include <LibC/sys/internals.h>
  37. #include <LibC/unistd.h>
  38. #include <LibELF/AuxiliaryVector.h>
  39. #include <LibELF/DynamicLinker.h>
  40. #include <LibELF/DynamicLoader.h>
  41. #include <LibELF/DynamicObject.h>
  42. #include <LibELF/Image.h>
  43. #include <dlfcn.h>
  44. #include <fcntl.h>
  45. #include <string.h>
  46. #include <sys/types.h>
  47. namespace ELF {
  48. namespace {
  49. HashMap<String, NonnullRefPtr<ELF::DynamicLoader>> g_loaders;
  50. HashMap<String, NonnullRefPtr<ELF::DynamicObject>> g_loaded_objects;
  51. Vector<NonnullRefPtr<ELF::DynamicObject>> g_global_objects;
  52. using MainFunction = int (*)(int, char**, char**);
  53. using LibCExitFunction = void (*)(int);
  54. size_t g_current_tls_offset = 0;
  55. size_t g_total_tls_size = 0;
  56. char** g_envp = nullptr;
  57. LibCExitFunction g_libc_exit = nullptr;
  58. bool g_allowed_to_check_environment_variables { false };
  59. bool g_do_breakpoint_trap_before_entry { false };
  60. }
  61. Optional<DynamicObject::SymbolLookupResult> DynamicLinker::lookup_global_symbol(const char* symbol_name)
  62. {
  63. Optional<DynamicObject::SymbolLookupResult> weak_result;
  64. for (auto& lib : g_global_objects) {
  65. auto res = lib->lookup_symbol(symbol_name);
  66. if (!res.has_value())
  67. continue;
  68. if (res.value().bind == STB_GLOBAL)
  69. return res;
  70. if (res.value().bind == STB_WEAK && !weak_result.has_value())
  71. weak_result = res;
  72. // We don't want to allow local symbols to be pulled in to other modules
  73. }
  74. return weak_result;
  75. }
  76. static void map_library(const String& name, int fd)
  77. {
  78. auto loader = ELF::DynamicLoader::try_create(fd, name);
  79. if (!loader) {
  80. dbgln("Failed to create ELF::DynamicLoader for fd={}, name={}", fd, name);
  81. ASSERT_NOT_REACHED();
  82. }
  83. loader->set_tls_offset(g_current_tls_offset);
  84. g_loaders.set(name, *loader);
  85. g_current_tls_offset += loader->tls_size();
  86. }
  87. static void map_library(const String& name)
  88. {
  89. // TODO: Do we want to also look for libs in other paths too?
  90. String path = String::formatted("/usr/lib/{}", name);
  91. int fd = open(path.characters(), O_RDONLY);
  92. ASSERT(fd >= 0);
  93. map_library(name, fd);
  94. }
  95. static String get_library_name(const StringView& path)
  96. {
  97. return LexicalPath(path).basename();
  98. }
  99. static Vector<String> get_dependencies(const String& name)
  100. {
  101. auto lib = g_loaders.get(name).value();
  102. Vector<String> dependencies;
  103. lib->for_each_needed_library([&dependencies, &name](auto needed_name) {
  104. if (name == needed_name)
  105. return IterationDecision::Continue;
  106. dependencies.append(needed_name);
  107. return IterationDecision::Continue;
  108. });
  109. return dependencies;
  110. }
  111. static void map_dependencies(const String& name)
  112. {
  113. dbgln<DYNAMIC_LOAD_DEBUG>("mapping dependencies for: {}", name);
  114. for (const auto& needed_name : get_dependencies(name)) {
  115. dbgln<DYNAMIC_LOAD_DEBUG>("needed library: {}", needed_name.characters());
  116. String library_name = get_library_name(needed_name);
  117. if (!g_loaders.contains(library_name)) {
  118. map_library(library_name);
  119. map_dependencies(library_name);
  120. }
  121. }
  122. dbgln<DYNAMIC_LOAD_DEBUG>("mapped dependencies for {}", name);
  123. }
  124. static void allocate_tls()
  125. {
  126. size_t total_tls_size = 0;
  127. for (const auto& data : g_loaders) {
  128. dbgln<DYNAMIC_LOAD_DEBUG>("{}: TLS Size: {}", data.key, data.value->tls_size());
  129. total_tls_size += data.value->tls_size();
  130. }
  131. if (total_tls_size) {
  132. [[maybe_unused]] void* tls_address = ::allocate_tls(total_tls_size);
  133. dbgln<DYNAMIC_LOAD_DEBUG>("from userspace, tls_address: {:p}", tls_address);
  134. }
  135. g_total_tls_size = total_tls_size;
  136. }
  137. static void initialize_libc(DynamicObject& libc)
  138. {
  139. // Traditionally, `_start` of the main program initializes libc.
  140. // However, since some libs use malloc() and getenv() in global constructors,
  141. // we have to initialize libc just after it is loaded.
  142. // Also, we can't just mark `__libc_init` with "__attribute__((constructor))"
  143. // because it uses getenv() internally, so `environ` has to be initialized before we call `__libc_init`.
  144. auto res = libc.lookup_symbol("environ");
  145. ASSERT(res.has_value());
  146. *((char***)res.value().address) = g_envp;
  147. res = libc.lookup_symbol("__environ_is_malloced");
  148. ASSERT(res.has_value());
  149. *((bool*)res.value().address) = false;
  150. res = libc.lookup_symbol("exit");
  151. ASSERT(res.has_value());
  152. g_libc_exit = (LibCExitFunction)res.value().address;
  153. res = libc.lookup_symbol("__libc_init");
  154. ASSERT(res.has_value());
  155. typedef void libc_init_func();
  156. ((libc_init_func*)res.value().address)();
  157. }
  158. static void load_elf(const String& name)
  159. {
  160. dbgln<DYNAMIC_LOAD_DEBUG>("load_elf: {}", name);
  161. auto loader = g_loaders.get(name).value();
  162. auto dynamic_object = loader->map();
  163. ASSERT(dynamic_object);
  164. for (const auto& needed_name : get_dependencies(name)) {
  165. dbgln<DYNAMIC_LOAD_DEBUG>("needed library: {}", needed_name);
  166. String library_name = get_library_name(needed_name);
  167. if (!g_loaded_objects.contains(library_name)) {
  168. load_elf(library_name);
  169. }
  170. }
  171. bool success = loader->link(RTLD_GLOBAL | RTLD_LAZY, g_total_tls_size);
  172. ASSERT(success);
  173. g_loaded_objects.set(name, *dynamic_object);
  174. g_global_objects.append(*dynamic_object);
  175. dbgln<DYNAMIC_LOAD_DEBUG>("load_elf: done {}", name);
  176. }
  177. static NonnullRefPtr<DynamicLoader> commit_elf(const String& name)
  178. {
  179. auto loader = g_loaders.get(name).value();
  180. for (const auto& needed_name : get_dependencies(name)) {
  181. String library_name = get_library_name(needed_name);
  182. if (g_loaders.contains(library_name)) {
  183. commit_elf(library_name);
  184. }
  185. }
  186. auto object = loader->load_stage_3(RTLD_GLOBAL | RTLD_LAZY, g_total_tls_size);
  187. ASSERT(object);
  188. if (name.is_one_of("libc.so", "libpthread.so")) {
  189. if (syscall(SC_msyscall, object->base_address().as_ptr())) {
  190. ASSERT_NOT_REACHED();
  191. }
  192. }
  193. if (name == "libc.so") {
  194. initialize_libc(*object);
  195. }
  196. g_loaders.remove(name);
  197. return loader;
  198. }
  199. static void read_environment_variables()
  200. {
  201. for (char** env = g_envp; *env; ++env) {
  202. if (StringView { *env } == "_LOADER_BREAKPOINT=1") {
  203. g_do_breakpoint_trap_before_entry = true;
  204. }
  205. }
  206. }
  207. void ELF::DynamicLinker::linker_main(String&& main_program_name, int main_program_fd, bool is_secure, int argc, char** argv, char** envp)
  208. {
  209. g_envp = envp;
  210. g_allowed_to_check_environment_variables = !is_secure;
  211. if (g_allowed_to_check_environment_variables)
  212. read_environment_variables();
  213. map_library(main_program_name, main_program_fd);
  214. map_dependencies(main_program_name);
  215. dbgln<DYNAMIC_LOAD_DEBUG>("loaded all dependencies");
  216. for ([[maybe_unused]] auto& lib : g_loaders) {
  217. dbgln<DYNAMIC_LOAD_DEBUG>("{} - tls size: {}, tls offset: {}", lib.key, lib.value->tls_size(), lib.value->tls_offset());
  218. }
  219. allocate_tls();
  220. load_elf(main_program_name);
  221. auto main_program_lib = commit_elf(main_program_name);
  222. FlatPtr entry_point = reinterpret_cast<FlatPtr>(main_program_lib->image().entry().as_ptr());
  223. if (main_program_lib->is_dynamic())
  224. entry_point += reinterpret_cast<FlatPtr>(main_program_lib->text_segment_load_address().as_ptr());
  225. dbgln<DYNAMIC_LOAD_DEBUG>("entry point: {:p}", (void*)entry_point);
  226. g_loaders.clear();
  227. MainFunction main_function = (MainFunction)(entry_point);
  228. dbgln<DYNAMIC_LOAD_DEBUG>("jumping to main program entry point: {:p}", main_function);
  229. if (g_do_breakpoint_trap_before_entry) {
  230. asm("int3");
  231. }
  232. int rc = syscall(SC_msyscall, nullptr);
  233. if (rc < 0) {
  234. ASSERT_NOT_REACHED();
  235. }
  236. rc = main_function(argc, argv, envp);
  237. dbgln<DYNAMIC_LOAD_DEBUG>("rc: {}", rc);
  238. if (g_libc_exit != nullptr) {
  239. g_libc_exit(rc);
  240. } else {
  241. _exit(rc);
  242. }
  243. ASSERT_NOT_REACHED();
  244. }
  245. }