DynamicLinker.cpp 9.1 KB

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