DynamicLinker.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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. * Copyright (c) 2022, Jesse Buhagiar <jooster669@gmail.com>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <AK/ByteBuffer.h>
  10. #include <AK/Debug.h>
  11. #include <AK/HashMap.h>
  12. #include <AK/HashTable.h>
  13. #include <AK/LexicalPath.h>
  14. #include <AK/NonnullRefPtrVector.h>
  15. #include <AK/Platform.h>
  16. #include <AK/ScopeGuard.h>
  17. #include <AK/Vector.h>
  18. #include <Kernel/API/VirtualMemoryAnnotations.h>
  19. #include <Kernel/API/prctl_numbers.h>
  20. #include <LibC/bits/pthread_integration.h>
  21. #include <LibC/link.h>
  22. #include <LibC/sys/mman.h>
  23. #include <LibC/unistd.h>
  24. #include <LibELF/AuxiliaryVector.h>
  25. #include <LibELF/DynamicLinker.h>
  26. #include <LibELF/DynamicLoader.h>
  27. #include <LibELF/DynamicObject.h>
  28. #include <LibELF/Hashes.h>
  29. #include <bits/dlfcn_integration.h>
  30. #include <dlfcn.h>
  31. #include <fcntl.h>
  32. #include <pthread.h>
  33. #include <string.h>
  34. #include <sys/types.h>
  35. #include <syscall.h>
  36. namespace ELF {
  37. static HashMap<DeprecatedString, NonnullRefPtr<ELF::DynamicLoader>> s_loaders;
  38. static DeprecatedString s_main_program_path;
  39. static OrderedHashMap<DeprecatedString, NonnullRefPtr<ELF::DynamicObject>> s_global_objects;
  40. using EntryPointFunction = int (*)(int, char**, char**);
  41. using LibCExitFunction = void (*)(int);
  42. using DlIteratePhdrCallbackFunction = int (*)(struct dl_phdr_info*, size_t, void*);
  43. using DlIteratePhdrFunction = int (*)(DlIteratePhdrCallbackFunction, void*);
  44. extern "C" [[noreturn]] void _invoke_entry(int argc, char** argv, char** envp, EntryPointFunction entry);
  45. static size_t s_current_tls_offset = 0;
  46. static size_t s_total_tls_size = 0;
  47. static size_t s_allocated_tls_block_size = 0;
  48. static char** s_envp = nullptr;
  49. static LibCExitFunction s_libc_exit = nullptr;
  50. static __pthread_mutex_t s_loader_lock = __PTHREAD_MUTEX_INITIALIZER;
  51. static DeprecatedString s_cwd;
  52. static bool s_allowed_to_check_environment_variables { false };
  53. static bool s_do_breakpoint_trap_before_entry { false };
  54. static StringView s_ld_library_path;
  55. static StringView s_main_program_pledge_promises;
  56. static DeprecatedString s_loader_pledge_promises;
  57. static Result<void, DlErrorMessage> __dlclose(void* handle);
  58. static Result<void*, DlErrorMessage> __dlopen(char const* filename, int flags);
  59. static Result<void*, DlErrorMessage> __dlsym(void* handle, char const* symbol_name);
  60. static Result<void, DlErrorMessage> __dladdr(void* addr, Dl_info* info);
  61. Optional<DynamicObject::SymbolLookupResult> DynamicLinker::lookup_global_symbol(StringView name)
  62. {
  63. Optional<DynamicObject::SymbolLookupResult> weak_result;
  64. auto symbol = DynamicObject::HashSymbol { name };
  65. for (auto& lib : s_global_objects) {
  66. auto res = lib.value->lookup_symbol(symbol);
  67. if (!res.has_value())
  68. continue;
  69. if (res.value().bind == STB_GLOBAL)
  70. return res;
  71. if (res.value().bind == STB_WEAK && !weak_result.has_value())
  72. weak_result = res;
  73. // We don't want to allow local symbols to be pulled in to other modules
  74. }
  75. return weak_result;
  76. }
  77. static Result<NonnullRefPtr<DynamicLoader>, DlErrorMessage> map_library(DeprecatedString const& filepath, int fd)
  78. {
  79. VERIFY(filepath.starts_with('/'));
  80. auto loader = TRY(ELF::DynamicLoader::try_create(fd, filepath));
  81. s_loaders.set(filepath, *loader);
  82. s_current_tls_offset -= loader->tls_size_of_current_object();
  83. if (loader->tls_alignment_of_current_object())
  84. s_current_tls_offset = align_down_to(s_current_tls_offset, loader->tls_alignment_of_current_object());
  85. loader->set_tls_offset(s_current_tls_offset);
  86. // This actually maps the library at the intended and final place.
  87. auto main_library_object = loader->map();
  88. s_global_objects.set(filepath, *main_library_object);
  89. return loader;
  90. }
  91. Optional<DeprecatedString> DynamicLinker::resolve_library(DeprecatedString const& name, DynamicObject const& parent_object)
  92. {
  93. // Absolute and relative (to the current working directory) paths are already considered resolved.
  94. // However, ensure that the returned path is absolute and canonical, so pass it through LexicalPath.
  95. if (name.contains('/'))
  96. return LexicalPath::absolute_path(s_cwd, name);
  97. Vector<StringView> search_paths;
  98. // Search RPATH values indicated by the ELF (only if RUNPATH is not present).
  99. if (parent_object.runpath().is_empty())
  100. search_paths.extend(parent_object.rpath().split_view(':'));
  101. // Scan the LD_LIBRARY_PATH environment variable if applicable.
  102. search_paths.extend(s_ld_library_path.split_view(':'));
  103. // Search RUNPATH values indicated by the ELF.
  104. search_paths.extend(parent_object.runpath().split_view(':'));
  105. // Last are the default search paths.
  106. search_paths.append("/usr/lib"sv);
  107. search_paths.append("/usr/local/lib"sv);
  108. for (auto const& search_path : search_paths) {
  109. LexicalPath library_path(search_path.replace("$ORIGIN"sv, LexicalPath::dirname(parent_object.filepath()), ReplaceMode::FirstOnly));
  110. DeprecatedString library_name = library_path.append(name).string();
  111. if (access(library_name.characters(), F_OK) == 0) {
  112. if (!library_name.starts_with('/')) {
  113. // FIXME: Non-absolute paths should resolve from the current working directory. However,
  114. // since that's almost never the effect that is actually desired, let's print
  115. // a warning and only implement it once something actually needs that behavior.
  116. dbgln("\033[33mWarning:\033[0m Resolving library '{}' resulted in non-absolute path '{}'. Check your binary for relative RPATHs and RUNPATHs.", name, library_name);
  117. }
  118. return library_name;
  119. }
  120. }
  121. return {};
  122. }
  123. static Result<NonnullRefPtr<DynamicLoader>, DlErrorMessage> map_library(DeprecatedString const& path)
  124. {
  125. VERIFY(path.starts_with('/'));
  126. int fd = open(path.characters(), O_RDONLY);
  127. if (fd < 0)
  128. return DlErrorMessage { DeprecatedString::formatted("Could not open shared library '{}': {}", path, strerror(errno)) };
  129. return map_library(path, fd);
  130. }
  131. static Vector<DeprecatedString> get_dependencies(DeprecatedString const& path)
  132. {
  133. VERIFY(path.starts_with('/'));
  134. auto name = LexicalPath::basename(path);
  135. auto lib = s_loaders.get(path).value();
  136. Vector<DeprecatedString> dependencies;
  137. lib->for_each_needed_library([&dependencies, &name](auto needed_name) {
  138. if (name == needed_name)
  139. return;
  140. dependencies.append(needed_name);
  141. });
  142. return dependencies;
  143. }
  144. static Result<void, DlErrorMessage> map_dependencies(DeprecatedString const& path)
  145. {
  146. VERIFY(path.starts_with('/'));
  147. dbgln_if(DYNAMIC_LOAD_DEBUG, "mapping dependencies for: {}", path);
  148. auto const& parent_object = (*s_loaders.get(path))->dynamic_object();
  149. for (auto const& needed_name : get_dependencies(path)) {
  150. dbgln_if(DYNAMIC_LOAD_DEBUG, "needed library: {}", needed_name.characters());
  151. auto dependency_path = DynamicLinker::resolve_library(needed_name, parent_object);
  152. if (!dependency_path.has_value())
  153. return DlErrorMessage { DeprecatedString::formatted("Could not find required shared library: {}", needed_name) };
  154. if (!s_loaders.contains(dependency_path.value()) && !s_global_objects.contains(dependency_path.value())) {
  155. auto loader = TRY(map_library(dependency_path.value()));
  156. TRY(map_dependencies(loader->filepath()));
  157. }
  158. }
  159. dbgln_if(DYNAMIC_LOAD_DEBUG, "mapped dependencies for {}", path);
  160. return {};
  161. }
  162. static void allocate_tls()
  163. {
  164. s_total_tls_size = 0;
  165. for (auto const& data : s_loaders) {
  166. dbgln_if(DYNAMIC_LOAD_DEBUG, "{}: TLS Size: {}, TLS Alignment: {}", data.key, data.value->tls_size_of_current_object(), data.value->tls_alignment_of_current_object());
  167. s_total_tls_size += data.value->tls_size_of_current_object() + data.value->tls_alignment_of_current_object();
  168. }
  169. if (!s_total_tls_size)
  170. return;
  171. auto page_aligned_size = align_up_to(s_total_tls_size, PAGE_SIZE);
  172. auto initial_tls_data_result = ByteBuffer::create_zeroed(page_aligned_size);
  173. if (initial_tls_data_result.is_error()) {
  174. dbgln("Failed to allocate initial TLS data");
  175. VERIFY_NOT_REACHED();
  176. }
  177. auto& initial_tls_data = initial_tls_data_result.value();
  178. // Initialize TLS data
  179. for (auto const& entry : s_loaders) {
  180. entry.value->copy_initial_tls_data_into(initial_tls_data);
  181. }
  182. void* master_tls = ::allocate_tls((char*)initial_tls_data.data(), initial_tls_data.size());
  183. VERIFY(master_tls != (void*)-1);
  184. dbgln_if(DYNAMIC_LOAD_DEBUG, "from userspace, master_tls: {:p}", master_tls);
  185. s_allocated_tls_block_size = initial_tls_data.size();
  186. }
  187. static int __dl_iterate_phdr(DlIteratePhdrCallbackFunction callback, void* data)
  188. {
  189. pthread_mutex_lock(&s_loader_lock);
  190. ScopeGuard unlock_guard = [] { pthread_mutex_unlock(&s_loader_lock); };
  191. for (auto& it : s_global_objects) {
  192. auto& object = it.value;
  193. auto info = dl_phdr_info {
  194. .dlpi_addr = (ElfW(Addr))object->base_address().as_ptr(),
  195. .dlpi_name = object->filepath().characters(),
  196. .dlpi_phdr = object->program_headers(),
  197. .dlpi_phnum = object->program_header_count()
  198. };
  199. auto res = callback(&info, sizeof(info), data);
  200. if (res != 0)
  201. return res;
  202. }
  203. return 0;
  204. }
  205. static void initialize_libc(DynamicObject& libc)
  206. {
  207. // Traditionally, `_start` of the main program initializes libc.
  208. // However, since some libs use malloc() and getenv() in global constructors,
  209. // we have to initialize libc just after it is loaded.
  210. // Also, we can't just mark `__libc_init` with "__attribute__((constructor))"
  211. // because it uses getenv() internally, so `environ` has to be initialized before we call `__libc_init`.
  212. auto res = libc.lookup_symbol("environ"sv);
  213. VERIFY(res.has_value());
  214. *((char***)res.value().address.as_ptr()) = s_envp;
  215. // __stack_chk_guard should be initialized before anything significant (read: global constructors) is running.
  216. // This is not done in __libc_init, as we definitely have to return from that, and it might affect Loader as well.
  217. res = libc.lookup_symbol("__stack_chk_guard"sv);
  218. VERIFY(res.has_value());
  219. void* stack_guard = res.value().address.as_ptr();
  220. arc4random_buf(stack_guard, sizeof(uintptr_t));
  221. #ifdef AK_ARCH_64_BIT
  222. // For 64-bit platforms we include an additional hardening: zero the first byte of the stack guard to avoid
  223. // leaking or overwriting the stack guard with C-style string functions.
  224. ((char*)stack_guard)[0] = 0;
  225. #endif
  226. res = libc.lookup_symbol("__environ_is_malloced"sv);
  227. VERIFY(res.has_value());
  228. *((bool*)res.value().address.as_ptr()) = false;
  229. res = libc.lookup_symbol("exit"sv);
  230. VERIFY(res.has_value());
  231. s_libc_exit = (LibCExitFunction)res.value().address.as_ptr();
  232. res = libc.lookup_symbol("__dl_iterate_phdr"sv);
  233. VERIFY(res.has_value());
  234. *((DlIteratePhdrFunction*)res.value().address.as_ptr()) = __dl_iterate_phdr;
  235. res = libc.lookup_symbol("__dlclose"sv);
  236. VERIFY(res.has_value());
  237. *((DlCloseFunction*)res.value().address.as_ptr()) = __dlclose;
  238. res = libc.lookup_symbol("__dlopen"sv);
  239. VERIFY(res.has_value());
  240. *((DlOpenFunction*)res.value().address.as_ptr()) = __dlopen;
  241. res = libc.lookup_symbol("__dlsym"sv);
  242. VERIFY(res.has_value());
  243. *((DlSymFunction*)res.value().address.as_ptr()) = __dlsym;
  244. res = libc.lookup_symbol("__dladdr"sv);
  245. VERIFY(res.has_value());
  246. *((DlAddrFunction*)res.value().address.as_ptr()) = __dladdr;
  247. res = libc.lookup_symbol("__libc_init"sv);
  248. VERIFY(res.has_value());
  249. typedef void libc_init_func();
  250. ((libc_init_func*)res.value().address.as_ptr())();
  251. }
  252. template<typename Callback>
  253. static void for_each_unfinished_dependency_of(DeprecatedString const& path, HashTable<DeprecatedString>& seen_names, Callback callback)
  254. {
  255. VERIFY(path.starts_with('/'));
  256. auto loader = s_loaders.get(path);
  257. if (!loader.has_value()) {
  258. // Not having a loader here means that the library has already been loaded in at an earlier point,
  259. // and the loader itself was cleared during the end of `linker_main`.
  260. return;
  261. }
  262. if (loader.value()->is_fully_relocated()) {
  263. if (!loader.value()->is_fully_initialized()) {
  264. // If we are ending up here, that possibly means that this library either dlopens itself or a library that depends
  265. // on it while running its initializers. Assuming that this is the only funny thing that the library does, there is
  266. // a reasonable chance that nothing breaks, so just warn and continue.
  267. dbgln("\033[33mWarning:\033[0m Querying for dependencies of '{}' while running its initializers", path);
  268. }
  269. return;
  270. }
  271. if (seen_names.contains(path))
  272. return;
  273. seen_names.set(path);
  274. for (auto const& needed_name : get_dependencies(path)) {
  275. auto dependency_path = *DynamicLinker::resolve_library(needed_name, loader.value()->dynamic_object());
  276. for_each_unfinished_dependency_of(dependency_path, seen_names, callback);
  277. }
  278. callback(*s_loaders.get(path).value());
  279. }
  280. static NonnullRefPtrVector<DynamicLoader> collect_loaders_for_library(DeprecatedString const& path)
  281. {
  282. VERIFY(path.starts_with('/'));
  283. HashTable<DeprecatedString> seen_names;
  284. NonnullRefPtrVector<DynamicLoader> loaders;
  285. for_each_unfinished_dependency_of(path, seen_names, [&](auto& loader) {
  286. loaders.append(loader);
  287. });
  288. return loaders;
  289. }
  290. static void drop_loader_promise(StringView promise_to_drop)
  291. {
  292. if (s_main_program_pledge_promises.is_empty() || s_loader_pledge_promises.is_empty())
  293. return;
  294. s_loader_pledge_promises = s_loader_pledge_promises.replace(promise_to_drop, ""sv, ReplaceMode::All);
  295. auto extended_promises = DeprecatedString::formatted("{} {}", s_main_program_pledge_promises, s_loader_pledge_promises);
  296. Syscall::SC_pledge_params params {
  297. { extended_promises.characters(), extended_promises.length() },
  298. { nullptr, 0 },
  299. };
  300. int rc = syscall(SC_pledge, &params);
  301. if (rc < 0 && rc > -EMAXERRNO) {
  302. warnln("Failed to drop loader pledge promise: {}. errno={}", promise_to_drop, errno);
  303. _exit(1);
  304. }
  305. }
  306. static Result<void, DlErrorMessage> link_main_library(DeprecatedString const& path, int flags)
  307. {
  308. VERIFY(path.starts_with('/'));
  309. auto loaders = collect_loaders_for_library(path);
  310. for (auto& loader : loaders) {
  311. auto dynamic_object = loader.map();
  312. if (dynamic_object)
  313. s_global_objects.set(dynamic_object->filepath(), *dynamic_object);
  314. }
  315. for (auto& loader : loaders) {
  316. bool success = loader.link(flags);
  317. if (!success) {
  318. return DlErrorMessage { DeprecatedString::formatted("Failed to link library {}", loader.filepath()) };
  319. }
  320. }
  321. for (auto& loader : loaders) {
  322. auto result = loader.load_stage_3(flags);
  323. VERIFY(!result.is_error());
  324. auto& object = result.value();
  325. if (loader.filepath().ends_with("/libc.so"sv)) {
  326. initialize_libc(*object);
  327. }
  328. if (loader.filepath().ends_with("/libsystem.so"sv)) {
  329. VERIFY(!loader.text_segments().is_empty());
  330. for (auto const& segment : loader.text_segments()) {
  331. auto flags = static_cast<int>(VirtualMemoryRangeFlags::SyscallCode) | static_cast<int>(VirtualMemoryRangeFlags::Immutable);
  332. if (syscall(SC_annotate_mapping, segment.address().get(), flags)) {
  333. VERIFY_NOT_REACHED();
  334. }
  335. }
  336. } else {
  337. for (auto const& segment : loader.text_segments()) {
  338. auto flags = static_cast<int>(VirtualMemoryRangeFlags::Immutable);
  339. if (syscall(SC_annotate_mapping, segment.address().get(), flags)) {
  340. VERIFY_NOT_REACHED();
  341. }
  342. }
  343. }
  344. }
  345. drop_loader_promise("prot_exec"sv);
  346. for (auto& loader : loaders) {
  347. loader.load_stage_4();
  348. }
  349. return {};
  350. }
  351. static Result<void, DlErrorMessage> __dlclose(void* handle)
  352. {
  353. dbgln_if(DYNAMIC_LOAD_DEBUG, "__dlclose: {}", handle);
  354. pthread_mutex_lock(&s_loader_lock);
  355. ScopeGuard unlock_guard = [] { pthread_mutex_unlock(&s_loader_lock); };
  356. // FIXME: this will not currently destroy the dynamic object
  357. // because we're intentionally holding a strong reference to it
  358. // via s_global_objects until there's proper unload support.
  359. auto object = static_cast<ELF::DynamicObject*>(handle);
  360. object->unref();
  361. return {};
  362. }
  363. static Optional<DlErrorMessage> verify_tls_for_dlopen(DynamicLoader const& loader)
  364. {
  365. if (loader.tls_size_of_current_object() == 0)
  366. return {};
  367. if (s_total_tls_size + loader.tls_size_of_current_object() + loader.tls_alignment_of_current_object() > s_allocated_tls_block_size)
  368. return DlErrorMessage("TLS size too large");
  369. bool tls_data_is_all_zero = true;
  370. loader.image().for_each_program_header([&loader, &tls_data_is_all_zero](ELF::Image::ProgramHeader program_header) {
  371. if (program_header.type() != PT_TLS)
  372. return IterationDecision::Continue;
  373. auto* tls_data = (const u8*)loader.image().base_address() + program_header.offset();
  374. for (size_t i = 0; i < program_header.size_in_image(); ++i) {
  375. if (tls_data[i] != 0) {
  376. tls_data_is_all_zero = false;
  377. break;
  378. }
  379. }
  380. return IterationDecision::Break;
  381. });
  382. if (tls_data_is_all_zero)
  383. return {};
  384. return DlErrorMessage("Using dlopen() with libraries that have non-zeroed TLS is currently not supported");
  385. }
  386. static Result<void*, DlErrorMessage> __dlopen(char const* filename, int flags)
  387. {
  388. // FIXME: RTLD_NOW and RTLD_LOCAL are not supported
  389. flags &= ~RTLD_NOW;
  390. flags |= RTLD_LAZY;
  391. flags &= ~RTLD_LOCAL;
  392. flags |= RTLD_GLOBAL;
  393. dbgln_if(DYNAMIC_LOAD_DEBUG, "__dlopen invoked, filename={}, flags={}", filename, flags);
  394. if (pthread_mutex_trylock(&s_loader_lock) != 0)
  395. return DlErrorMessage { "Nested calls to dlopen() are not permitted." };
  396. ScopeGuard unlock_guard = [] { pthread_mutex_unlock(&s_loader_lock); };
  397. auto const& parent_object = **s_global_objects.get(s_main_program_path);
  398. auto library_path = (filename ? DynamicLinker::resolve_library(filename, parent_object) : s_main_program_path);
  399. if (!library_path.has_value())
  400. return DlErrorMessage { DeprecatedString::formatted("Could not find required shared library: {}", filename) };
  401. auto existing_elf_object = s_global_objects.get(library_path.value());
  402. if (existing_elf_object.has_value()) {
  403. // It's up to the caller to release the ref with dlclose().
  404. existing_elf_object.value()->ref();
  405. return *existing_elf_object;
  406. }
  407. auto loader = TRY(map_library(library_path.value()));
  408. if (auto error = verify_tls_for_dlopen(loader); error.has_value())
  409. return error.value();
  410. TRY(map_dependencies(loader->filepath()));
  411. TRY(link_main_library(loader->filepath(), flags));
  412. s_total_tls_size += loader->tls_size_of_current_object() + loader->tls_alignment_of_current_object();
  413. auto object = s_global_objects.get(library_path.value());
  414. if (!object.has_value())
  415. return DlErrorMessage { "Could not load ELF object." };
  416. // It's up to the caller to release the ref with dlclose().
  417. object.value()->ref();
  418. return *object;
  419. }
  420. static Result<void*, DlErrorMessage> __dlsym(void* handle, char const* symbol_name)
  421. {
  422. dbgln_if(DYNAMIC_LOAD_DEBUG, "__dlsym: {}, {}", handle, symbol_name);
  423. pthread_mutex_lock(&s_loader_lock);
  424. ScopeGuard unlock_guard = [] { pthread_mutex_unlock(&s_loader_lock); };
  425. StringView symbol_name_view { symbol_name, strlen(symbol_name) };
  426. Optional<DynamicObject::SymbolLookupResult> symbol;
  427. if (handle) {
  428. auto object = static_cast<DynamicObject*>(handle);
  429. symbol = object->lookup_symbol(symbol_name_view);
  430. } else {
  431. // When handle is 0 (RTLD_DEFAULT) we should look up the symbol in all global modules
  432. // https://pubs.opengroup.org/onlinepubs/009604499/functions/dlsym.html
  433. symbol = DynamicLinker::lookup_global_symbol(symbol_name_view);
  434. }
  435. if (!symbol.has_value())
  436. return DlErrorMessage { DeprecatedString::formatted("Symbol {} not found", symbol_name_view) };
  437. if (symbol.value().type == STT_GNU_IFUNC)
  438. return (void*)reinterpret_cast<DynamicObject::IfuncResolver>(symbol.value().address.as_ptr())();
  439. return symbol.value().address.as_ptr();
  440. }
  441. static Result<void, DlErrorMessage> __dladdr(void* addr, Dl_info* info)
  442. {
  443. VirtualAddress user_addr { addr };
  444. pthread_mutex_lock(&s_loader_lock);
  445. ScopeGuard unlock_guard = [] { pthread_mutex_unlock(&s_loader_lock); };
  446. RefPtr<DynamicObject> best_matching_library;
  447. VirtualAddress best_library_offset;
  448. for (auto& lib : s_global_objects) {
  449. if (user_addr < lib.value->base_address())
  450. continue;
  451. auto offset = user_addr - lib.value->base_address();
  452. if (!best_matching_library || offset < best_library_offset) {
  453. best_matching_library = lib.value;
  454. best_library_offset = offset;
  455. }
  456. }
  457. if (!best_matching_library) {
  458. return DlErrorMessage { "No library found which contains the specified address" };
  459. }
  460. Optional<DynamicObject::Symbol> best_matching_symbol;
  461. best_matching_library->for_each_symbol([&](auto const& symbol) {
  462. if (user_addr < symbol.address() || user_addr > symbol.address().offset(symbol.size()))
  463. return;
  464. best_matching_symbol = symbol;
  465. });
  466. info->dli_fbase = best_matching_library->base_address().as_ptr();
  467. // This works because we don't support unloading objects.
  468. info->dli_fname = best_matching_library->filepath().characters();
  469. if (best_matching_symbol.has_value()) {
  470. info->dli_saddr = best_matching_symbol.value().address().as_ptr();
  471. info->dli_sname = best_matching_symbol.value().raw_name();
  472. } else {
  473. info->dli_saddr = nullptr;
  474. info->dli_sname = nullptr;
  475. }
  476. return {};
  477. }
  478. static void read_environment_variables()
  479. {
  480. for (char** env = s_envp; *env; ++env) {
  481. StringView env_string { *env, strlen(*env) };
  482. if (env_string == "_LOADER_BREAKPOINT=1"sv) {
  483. s_do_breakpoint_trap_before_entry = true;
  484. }
  485. constexpr auto library_path_string = "LD_LIBRARY_PATH="sv;
  486. if (env_string.starts_with(library_path_string)) {
  487. s_ld_library_path = env_string.substring_view(library_path_string.length());
  488. }
  489. constexpr auto main_pledge_promises_key = "_LOADER_MAIN_PROGRAM_PLEDGE_PROMISES="sv;
  490. if (env_string.starts_with(main_pledge_promises_key)) {
  491. s_main_program_pledge_promises = env_string.substring_view(main_pledge_promises_key.length());
  492. }
  493. constexpr auto loader_pledge_promises_key = "_LOADER_PLEDGE_PROMISES="sv;
  494. if (env_string.starts_with(loader_pledge_promises_key)) {
  495. s_loader_pledge_promises = env_string.substring_view(loader_pledge_promises_key.length());
  496. }
  497. }
  498. }
  499. void ELF::DynamicLinker::linker_main(DeprecatedString&& main_program_path, int main_program_fd, bool is_secure, int argc, char** argv, char** envp)
  500. {
  501. VERIFY(main_program_path.starts_with('/'));
  502. s_envp = envp;
  503. char* raw_current_directory = getcwd(nullptr, 0);
  504. s_cwd = raw_current_directory;
  505. free(raw_current_directory);
  506. s_allowed_to_check_environment_variables = !is_secure;
  507. if (s_allowed_to_check_environment_variables)
  508. read_environment_variables();
  509. s_main_program_path = main_program_path;
  510. // NOTE: We always map the main library first, since it may require
  511. // placement at a specific address.
  512. auto result1 = map_library(main_program_path, main_program_fd);
  513. if (result1.is_error()) {
  514. warnln("{}", result1.error().text);
  515. fflush(stderr);
  516. _exit(1);
  517. }
  518. (void)result1.release_value();
  519. auto result2 = map_dependencies(main_program_path);
  520. if (result2.is_error()) {
  521. warnln("{}", result2.error().text);
  522. fflush(stderr);
  523. _exit(1);
  524. }
  525. dbgln_if(DYNAMIC_LOAD_DEBUG, "loaded all dependencies");
  526. for ([[maybe_unused]] auto& lib : s_loaders) {
  527. dbgln_if(DYNAMIC_LOAD_DEBUG, "{} - tls size: {}, tls alignment: {}, tls offset: {}", lib.key, lib.value->tls_size_of_current_object(), lib.value->tls_alignment_of_current_object(), lib.value->tls_offset());
  528. }
  529. allocate_tls();
  530. auto entry_point_function = [&main_program_path] {
  531. auto result = link_main_library(main_program_path, RTLD_GLOBAL | RTLD_LAZY);
  532. if (result.is_error()) {
  533. warnln("{}", result.error().text);
  534. _exit(1);
  535. }
  536. drop_loader_promise("rpath"sv);
  537. auto& main_executable_loader = *s_loaders.get(main_program_path);
  538. auto entry_point = main_executable_loader->image().entry();
  539. if (main_executable_loader->is_dynamic())
  540. entry_point = entry_point.offset(main_executable_loader->base_address().get());
  541. return (EntryPointFunction)(entry_point.as_ptr());
  542. }();
  543. s_loaders.clear();
  544. int rc = syscall(SC_prctl, PR_SET_NO_NEW_SYSCALL_REGION_ANNOTATIONS, 1, 0);
  545. if (rc < 0) {
  546. VERIFY_NOT_REACHED();
  547. }
  548. dbgln_if(DYNAMIC_LOAD_DEBUG, "Jumping to entry point: {:p}", entry_point_function);
  549. if (s_do_breakpoint_trap_before_entry) {
  550. #ifdef AK_ARCH_AARCH64
  551. asm("brk #0");
  552. #else
  553. asm("int3");
  554. #endif
  555. }
  556. _invoke_entry(argc, argv, envp, entry_point_function);
  557. VERIFY_NOT_REACHED();
  558. }
  559. }