DynamicLinker.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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/NonnullRefPtrVector.h>
  33. #include <AK/ScopeGuard.h>
  34. #include <LibC/link.h>
  35. #include <LibC/mman.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/Hashes.h>
  42. #include <dlfcn.h>
  43. #include <fcntl.h>
  44. #include <sys/types.h>
  45. #include <syscall.h>
  46. namespace ELF {
  47. namespace {
  48. HashMap<String, NonnullRefPtr<ELF::DynamicLoader>> g_loaders;
  49. Vector<NonnullRefPtr<ELF::DynamicObject>> g_global_objects;
  50. using EntryPointFunction = int (*)(int, char**, char**);
  51. using LibCExitFunction = void (*)(int);
  52. using DlIteratePhdrCallbackFunction = int (*)(struct dl_phdr_info*, size_t, void*);
  53. using DlIteratePhdrFunction = int (*)(DlIteratePhdrCallbackFunction, void*);
  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 StringView& symbol)
  62. {
  63. Optional<DynamicObject::SymbolLookupResult> weak_result;
  64. auto gnu_hash = compute_gnu_hash(symbol);
  65. auto sysv_hash = compute_sysv_hash(symbol);
  66. for (auto& lib : g_global_objects) {
  67. auto res = lib->lookup_symbol(symbol, gnu_hash, sysv_hash);
  68. if (!res.has_value())
  69. continue;
  70. if (res.value().bind == STB_GLOBAL)
  71. return res;
  72. if (res.value().bind == STB_WEAK && !weak_result.has_value())
  73. weak_result = res;
  74. // We don't want to allow local symbols to be pulled in to other modules
  75. }
  76. return weak_result;
  77. }
  78. static void map_library(const String& name, int fd)
  79. {
  80. auto loader = ELF::DynamicLoader::try_create(fd, name);
  81. if (!loader) {
  82. dbgln("Failed to create ELF::DynamicLoader for fd={}, name={}", fd, name);
  83. VERIFY_NOT_REACHED();
  84. }
  85. loader->set_tls_offset(g_current_tls_offset);
  86. g_loaders.set(name, *loader);
  87. g_current_tls_offset += loader->tls_size();
  88. }
  89. static void map_library(const String& name)
  90. {
  91. // TODO: Do we want to also look for libs in other paths too?
  92. const char* search_paths[] = { "/usr/lib/{}", "/usr/local/lib/{}" };
  93. for (auto& search_path : search_paths) {
  94. auto path = String::formatted(search_path, name);
  95. int fd = open(path.characters(), O_RDONLY);
  96. if (fd < 0)
  97. continue;
  98. map_library(name, fd);
  99. return;
  100. }
  101. fprintf(stderr, "Could not find required shared library: %s\n", name.characters());
  102. VERIFY_NOT_REACHED();
  103. }
  104. static String get_library_name(String path)
  105. {
  106. return LexicalPath(move(path)).basename();
  107. }
  108. static Vector<String> get_dependencies(const String& name)
  109. {
  110. auto lib = g_loaders.get(name).value();
  111. Vector<String> dependencies;
  112. lib->for_each_needed_library([&dependencies, &name](auto needed_name) {
  113. if (name == needed_name)
  114. return IterationDecision::Continue;
  115. dependencies.append(needed_name);
  116. return IterationDecision::Continue;
  117. });
  118. return dependencies;
  119. }
  120. static void map_dependencies(const String& name)
  121. {
  122. dbgln_if(DYNAMIC_LOAD_DEBUG, "mapping dependencies for: {}", name);
  123. for (const auto& needed_name : get_dependencies(name)) {
  124. dbgln_if(DYNAMIC_LOAD_DEBUG, "needed library: {}", needed_name.characters());
  125. String library_name = get_library_name(needed_name);
  126. if (!g_loaders.contains(library_name)) {
  127. map_library(library_name);
  128. map_dependencies(library_name);
  129. }
  130. }
  131. dbgln_if(DYNAMIC_LOAD_DEBUG, "mapped dependencies for {}", name);
  132. }
  133. static void allocate_tls()
  134. {
  135. size_t total_tls_size = 0;
  136. for (const auto& data : g_loaders) {
  137. dbgln_if(DYNAMIC_LOAD_DEBUG, "{}: TLS Size: {}", data.key, data.value->tls_size());
  138. total_tls_size += data.value->tls_size();
  139. }
  140. if (total_tls_size) {
  141. [[maybe_unused]] void* tls_address = ::allocate_tls(total_tls_size);
  142. dbgln_if(DYNAMIC_LOAD_DEBUG, "from userspace, tls_address: {:p}", tls_address);
  143. }
  144. g_total_tls_size = total_tls_size;
  145. }
  146. static int __dl_iterate_phdr(DlIteratePhdrCallbackFunction callback, void* data)
  147. {
  148. for (auto& object : g_global_objects) {
  149. auto info = dl_phdr_info {
  150. .dlpi_addr = (ElfW(Addr))object->base_address().as_ptr(),
  151. .dlpi_name = object->filename().characters(),
  152. .dlpi_phdr = object->program_headers(),
  153. .dlpi_phnum = object->program_header_count()
  154. };
  155. auto res = callback(&info, sizeof(info), data);
  156. if (res != 0)
  157. return res;
  158. }
  159. return 0;
  160. }
  161. static void initialize_libc(DynamicObject& libc)
  162. {
  163. // Traditionally, `_start` of the main program initializes libc.
  164. // However, since some libs use malloc() and getenv() in global constructors,
  165. // we have to initialize libc just after it is loaded.
  166. // Also, we can't just mark `__libc_init` with "__attribute__((constructor))"
  167. // because it uses getenv() internally, so `environ` has to be initialized before we call `__libc_init`.
  168. auto res = libc.lookup_symbol("environ"sv);
  169. VERIFY(res.has_value());
  170. *((char***)res.value().address.as_ptr()) = g_envp;
  171. res = libc.lookup_symbol("__environ_is_malloced"sv);
  172. VERIFY(res.has_value());
  173. *((bool*)res.value().address.as_ptr()) = false;
  174. res = libc.lookup_symbol("exit"sv);
  175. VERIFY(res.has_value());
  176. g_libc_exit = (LibCExitFunction)res.value().address.as_ptr();
  177. res = libc.lookup_symbol("__dl_iterate_phdr"sv);
  178. VERIFY(res.has_value());
  179. *((DlIteratePhdrFunction*)res.value().address.as_ptr()) = __dl_iterate_phdr;
  180. res = libc.lookup_symbol("__libc_init"sv);
  181. VERIFY(res.has_value());
  182. typedef void libc_init_func();
  183. ((libc_init_func*)res.value().address.as_ptr())();
  184. }
  185. template<typename Callback>
  186. static void for_each_dependency_of(const String& name, HashTable<String>& seen_names, Callback callback)
  187. {
  188. if (seen_names.contains(name))
  189. return;
  190. seen_names.set(name);
  191. for (const auto& needed_name : get_dependencies(name))
  192. for_each_dependency_of(get_library_name(needed_name), seen_names, callback);
  193. callback(*g_loaders.get(name).value());
  194. }
  195. static NonnullRefPtrVector<DynamicLoader> collect_loaders_for_executable(const String& name)
  196. {
  197. HashTable<String> seen_names;
  198. NonnullRefPtrVector<DynamicLoader> loaders;
  199. for_each_dependency_of(name, seen_names, [&](auto& loader) {
  200. loaders.append(loader);
  201. });
  202. return loaders;
  203. }
  204. static NonnullRefPtr<DynamicLoader> load_main_executable(const String& name)
  205. {
  206. // NOTE: We always map the main executable first, since it may require
  207. // placement at a specific address.
  208. auto& main_executable_loader = *g_loaders.get(name).value();
  209. auto main_executable_object = main_executable_loader.map();
  210. g_global_objects.append(*main_executable_object);
  211. auto loaders = collect_loaders_for_executable(name);
  212. for (auto& loader : loaders) {
  213. auto dynamic_object = loader.map();
  214. if (dynamic_object)
  215. g_global_objects.append(*dynamic_object);
  216. }
  217. for (auto& loader : loaders) {
  218. bool success = loader.link(RTLD_GLOBAL | RTLD_LAZY, g_total_tls_size);
  219. VERIFY(success);
  220. }
  221. for (auto& loader : loaders) {
  222. auto object = loader.load_stage_3(RTLD_GLOBAL | RTLD_LAZY, g_total_tls_size);
  223. VERIFY(object);
  224. if (loader.filename() == "libsystem.so") {
  225. if (syscall(SC_msyscall, object->base_address().as_ptr())) {
  226. VERIFY_NOT_REACHED();
  227. }
  228. }
  229. if (loader.filename() == "libc.so") {
  230. initialize_libc(*object);
  231. }
  232. }
  233. for (auto& loader : loaders) {
  234. loader.load_stage_4();
  235. }
  236. return main_executable_loader;
  237. }
  238. static void read_environment_variables()
  239. {
  240. for (char** env = g_envp; *env; ++env) {
  241. if (StringView { *env } == "_LOADER_BREAKPOINT=1") {
  242. g_do_breakpoint_trap_before_entry = true;
  243. }
  244. }
  245. }
  246. void ELF::DynamicLinker::linker_main(String&& main_program_name, int main_program_fd, bool is_secure, int argc, char** argv, char** envp)
  247. {
  248. g_envp = envp;
  249. g_allowed_to_check_environment_variables = !is_secure;
  250. if (g_allowed_to_check_environment_variables)
  251. read_environment_variables();
  252. map_library(main_program_name, main_program_fd);
  253. map_dependencies(main_program_name);
  254. dbgln_if(DYNAMIC_LOAD_DEBUG, "loaded all dependencies");
  255. for ([[maybe_unused]] auto& lib : g_loaders) {
  256. dbgln_if(DYNAMIC_LOAD_DEBUG, "{} - tls size: {}, tls offset: {}", lib.key, lib.value->tls_size(), lib.value->tls_offset());
  257. }
  258. allocate_tls();
  259. auto entry_point_function = [&main_program_name] {
  260. auto main_executable_loader = load_main_executable(main_program_name);
  261. auto entry_point = main_executable_loader->image().entry();
  262. if (main_executable_loader->is_dynamic())
  263. entry_point = entry_point.offset(main_executable_loader->base_address().get());
  264. return (EntryPointFunction)(entry_point.as_ptr());
  265. }();
  266. g_loaders.clear();
  267. int rc = syscall(SC_msyscall, nullptr);
  268. if (rc < 0) {
  269. VERIFY_NOT_REACHED();
  270. }
  271. dbgln_if(DYNAMIC_LOAD_DEBUG, "Jumping to entry point: {:p}", entry_point_function);
  272. if (g_do_breakpoint_trap_before_entry) {
  273. asm("int3");
  274. }
  275. rc = entry_point_function(argc, argv, envp);
  276. dbgln_if(DYNAMIC_LOAD_DEBUG, "rc: {}", rc);
  277. if (g_libc_exit != nullptr) {
  278. g_libc_exit(rc);
  279. } else {
  280. _exit(rc);
  281. }
  282. VERIFY_NOT_REACHED();
  283. }
  284. }