DynamicLinker.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  4. * Copyright (c) 2021, the SerenityOS developers.
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. *
  10. * 1. Redistributions of source code must retain the above copyright notice, this
  11. * list of conditions and the following disclaimer.
  12. *
  13. * 2. Redistributions in binary form must reproduce the above copyright notice,
  14. * this list of conditions and the following disclaimer in the documentation
  15. * and/or other materials provided with the distribution.
  16. *
  17. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  18. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  19. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  20. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  21. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  22. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  23. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  24. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  25. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  26. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. */
  28. #include <AK/Debug.h>
  29. #include <AK/HashMap.h>
  30. #include <AK/HashTable.h>
  31. #include <AK/LexicalPath.h>
  32. #include <AK/LogStream.h>
  33. #include <AK/ScopeGuard.h>
  34. #include <LibC/mman.h>
  35. #include <LibC/unistd.h>
  36. #include <LibELF/AuxiliaryVector.h>
  37. #include <LibELF/DynamicLinker.h>
  38. #include <LibELF/DynamicLoader.h>
  39. #include <LibELF/DynamicObject.h>
  40. #include <dlfcn.h>
  41. #include <fcntl.h>
  42. #include <sys/types.h>
  43. #include <syscall.h>
  44. namespace ELF {
  45. namespace {
  46. HashMap<String, NonnullRefPtr<ELF::DynamicLoader>> g_loaders;
  47. Vector<NonnullRefPtr<ELF::DynamicObject>> g_global_objects;
  48. using MainFunction = int (*)(int, char**, char**);
  49. using LibCExitFunction = void (*)(int);
  50. size_t g_current_tls_offset = 0;
  51. size_t g_total_tls_size = 0;
  52. char** g_envp = nullptr;
  53. LibCExitFunction g_libc_exit = nullptr;
  54. bool g_allowed_to_check_environment_variables { false };
  55. bool g_do_breakpoint_trap_before_entry { false };
  56. }
  57. Optional<DynamicObject::SymbolLookupResult> DynamicLinker::lookup_global_symbol(const StringView& symbol)
  58. {
  59. Optional<DynamicObject::SymbolLookupResult> weak_result;
  60. for (auto& lib : g_global_objects) {
  61. auto res = lib->lookup_symbol(symbol);
  62. if (!res.has_value())
  63. continue;
  64. if (res.value().bind == STB_GLOBAL)
  65. return res;
  66. if (res.value().bind == STB_WEAK && !weak_result.has_value())
  67. weak_result = res;
  68. // We don't want to allow local symbols to be pulled in to other modules
  69. }
  70. return weak_result;
  71. }
  72. static void map_library(const String& name, int fd)
  73. {
  74. auto loader = ELF::DynamicLoader::try_create(fd, name);
  75. if (!loader) {
  76. dbgln("Failed to create ELF::DynamicLoader for fd={}, name={}", fd, name);
  77. ASSERT_NOT_REACHED();
  78. }
  79. loader->set_tls_offset(g_current_tls_offset);
  80. g_loaders.set(name, *loader);
  81. g_current_tls_offset += loader->tls_size();
  82. }
  83. static void map_library(const String& name)
  84. {
  85. // TODO: Do we want to also look for libs in other paths too?
  86. String path = String::formatted("/usr/lib/{}", name);
  87. int fd = open(path.characters(), O_RDONLY);
  88. ASSERT(fd >= 0);
  89. map_library(name, fd);
  90. }
  91. static String get_library_name(const StringView& path)
  92. {
  93. return LexicalPath(path).basename();
  94. }
  95. static Vector<String> get_dependencies(const String& name)
  96. {
  97. auto lib = g_loaders.get(name).value();
  98. Vector<String> dependencies;
  99. lib->for_each_needed_library([&dependencies, &name](auto needed_name) {
  100. if (name == needed_name)
  101. return IterationDecision::Continue;
  102. dependencies.append(needed_name);
  103. return IterationDecision::Continue;
  104. });
  105. return dependencies;
  106. }
  107. static void map_dependencies(const String& name)
  108. {
  109. dbgln_if(DYNAMIC_LOAD_DEBUG, "mapping dependencies for: {}", name);
  110. for (const auto& needed_name : get_dependencies(name)) {
  111. dbgln_if(DYNAMIC_LOAD_DEBUG, "needed library: {}", needed_name.characters());
  112. String library_name = get_library_name(needed_name);
  113. if (!g_loaders.contains(library_name)) {
  114. map_library(library_name);
  115. map_dependencies(library_name);
  116. }
  117. }
  118. dbgln_if(DYNAMIC_LOAD_DEBUG, "mapped dependencies for {}", name);
  119. }
  120. static void allocate_tls()
  121. {
  122. size_t total_tls_size = 0;
  123. for (const auto& data : g_loaders) {
  124. dbgln_if(DYNAMIC_LOAD_DEBUG, "{}: TLS Size: {}", data.key, data.value->tls_size());
  125. total_tls_size += data.value->tls_size();
  126. }
  127. if (total_tls_size) {
  128. [[maybe_unused]] void* tls_address = ::allocate_tls(total_tls_size);
  129. dbgln_if(DYNAMIC_LOAD_DEBUG, "from userspace, tls_address: {:p}", tls_address);
  130. }
  131. g_total_tls_size = total_tls_size;
  132. }
  133. static void initialize_libc(DynamicObject& libc)
  134. {
  135. // Traditionally, `_start` of the main program initializes libc.
  136. // However, since some libs use malloc() and getenv() in global constructors,
  137. // we have to initialize libc just after it is loaded.
  138. // Also, we can't just mark `__libc_init` with "__attribute__((constructor))"
  139. // because it uses getenv() internally, so `environ` has to be initialized before we call `__libc_init`.
  140. auto res = libc.lookup_symbol("environ");
  141. ASSERT(res.has_value());
  142. *((char***)res.value().address) = g_envp;
  143. res = libc.lookup_symbol("__environ_is_malloced");
  144. ASSERT(res.has_value());
  145. *((bool*)res.value().address) = false;
  146. res = libc.lookup_symbol("exit");
  147. ASSERT(res.has_value());
  148. g_libc_exit = (LibCExitFunction)res.value().address;
  149. res = libc.lookup_symbol("__libc_init");
  150. ASSERT(res.has_value());
  151. typedef void libc_init_func();
  152. ((libc_init_func*)res.value().address)();
  153. }
  154. template<typename Callback>
  155. static void for_each_dependency_of_impl(const String& name, HashTable<String>& seen_names, Callback callback)
  156. {
  157. if (seen_names.contains(name))
  158. return;
  159. seen_names.set(name);
  160. for (const auto& needed_name : get_dependencies(name))
  161. for_each_dependency_of_impl(get_library_name(needed_name), seen_names, callback);
  162. callback(*g_loaders.get(name).value());
  163. }
  164. template<typename Callback>
  165. static void for_each_dependency_of(const String& name, Callback callback)
  166. {
  167. HashTable<String> seen_names;
  168. for_each_dependency_of_impl(name, seen_names, move(callback));
  169. }
  170. static void load_elf(const String& name)
  171. {
  172. for_each_dependency_of(name, [](auto& loader) {
  173. auto dynamic_object = loader.map();
  174. ASSERT(dynamic_object);
  175. g_global_objects.append(*dynamic_object);
  176. });
  177. for_each_dependency_of(name, [](auto& loader) {
  178. bool success = loader.link(RTLD_GLOBAL | RTLD_LAZY, g_total_tls_size);
  179. ASSERT(success);
  180. });
  181. }
  182. static NonnullRefPtr<DynamicLoader> commit_elf(const String& name)
  183. {
  184. auto loader = g_loaders.get(name).value();
  185. for (const auto& needed_name : get_dependencies(name)) {
  186. String library_name = get_library_name(needed_name);
  187. if (g_loaders.contains(library_name)) {
  188. commit_elf(library_name);
  189. }
  190. }
  191. auto object = loader->load_stage_3(RTLD_GLOBAL | RTLD_LAZY, g_total_tls_size);
  192. ASSERT(object);
  193. if (name == "libsystem.so") {
  194. if (syscall(SC_msyscall, object->base_address().as_ptr())) {
  195. ASSERT_NOT_REACHED();
  196. }
  197. }
  198. if (name == "libc.so") {
  199. initialize_libc(*object);
  200. }
  201. g_loaders.remove(name);
  202. return loader;
  203. }
  204. static void read_environment_variables()
  205. {
  206. for (char** env = g_envp; *env; ++env) {
  207. if (StringView { *env } == "_LOADER_BREAKPOINT=1") {
  208. g_do_breakpoint_trap_before_entry = true;
  209. }
  210. }
  211. }
  212. void ELF::DynamicLinker::linker_main(String&& main_program_name, int main_program_fd, bool is_secure, int argc, char** argv, char** envp)
  213. {
  214. g_envp = envp;
  215. g_allowed_to_check_environment_variables = !is_secure;
  216. if (g_allowed_to_check_environment_variables)
  217. read_environment_variables();
  218. map_library(main_program_name, main_program_fd);
  219. map_dependencies(main_program_name);
  220. dbgln_if(DYNAMIC_LOAD_DEBUG, "loaded all dependencies");
  221. for ([[maybe_unused]] auto& lib : g_loaders) {
  222. dbgln_if(DYNAMIC_LOAD_DEBUG, "{} - tls size: {}, tls offset: {}", lib.key, lib.value->tls_size(), lib.value->tls_offset());
  223. }
  224. allocate_tls();
  225. load_elf(main_program_name);
  226. // NOTE: We put this in a RefPtr instead of a NonnullRefPtr so we can release it later.
  227. RefPtr main_program_lib = commit_elf(main_program_name);
  228. FlatPtr entry_point = reinterpret_cast<FlatPtr>(main_program_lib->image().entry().as_ptr());
  229. if (main_program_lib->is_dynamic())
  230. entry_point += reinterpret_cast<FlatPtr>(main_program_lib->text_segment_load_address().as_ptr());
  231. dbgln_if(DYNAMIC_LOAD_DEBUG, "entry point: {:p}", (void*)entry_point);
  232. g_loaders.clear();
  233. MainFunction main_function = (MainFunction)(entry_point);
  234. dbgln_if(DYNAMIC_LOAD_DEBUG, "jumping to main program entry point: {:p}", main_function);
  235. if (g_do_breakpoint_trap_before_entry) {
  236. asm("int3");
  237. }
  238. // Unmap the main executable and release our related resources.
  239. main_program_lib = nullptr;
  240. int rc = syscall(SC_msyscall, nullptr);
  241. if (rc < 0) {
  242. ASSERT_NOT_REACHED();
  243. }
  244. rc = main_function(argc, argv, envp);
  245. dbgln_if(DYNAMIC_LOAD_DEBUG, "rc: {}", rc);
  246. if (g_libc_exit != nullptr) {
  247. g_libc_exit(rc);
  248. } else {
  249. _exit(rc);
  250. }
  251. ASSERT_NOT_REACHED();
  252. }
  253. }