DynamicLinker.cpp 26 KB

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