DynamicLinker.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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/Random.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 <LibELF/Arch/tls.h>
  21. #include <LibELF/AuxiliaryVector.h>
  22. #include <LibELF/DynamicLinker.h>
  23. #include <LibELF/DynamicLoader.h>
  24. #include <LibELF/DynamicObject.h>
  25. #include <LibELF/Hashes.h>
  26. #include <bits/dlfcn_integration.h>
  27. #include <bits/pthread_integration.h>
  28. #include <dlfcn.h>
  29. #include <fcntl.h>
  30. #include <link.h>
  31. #include <pthread.h>
  32. #include <string.h>
  33. #include <sys/internals.h>
  34. #include <sys/mman.h>
  35. #include <sys/types.h>
  36. #include <syscall.h>
  37. #include <unistd.h>
  38. namespace ELF {
  39. static HashMap<ByteString, NonnullRefPtr<ELF::DynamicLoader>> s_loaders;
  40. static ByteString s_main_program_path;
  41. // Dependencies have to always be added after the object that depends on them in `s_global_objects`.
  42. // This is needed for calling the destructors in the correct order.
  43. static OrderedHashMap<ByteString, NonnullRefPtr<ELF::DynamicObject>> s_global_objects;
  44. using EntryPointFunction = int (*)(int, char**, char**);
  45. using LibCExitFunction = void (*)(int);
  46. using DlIteratePhdrCallbackFunction = int (*)(struct dl_phdr_info*, size_t, void*);
  47. using DlIteratePhdrFunction = int (*)(DlIteratePhdrCallbackFunction, void*);
  48. using CallFiniFunctionsFunction = void (*)();
  49. extern "C" [[noreturn]] void _invoke_entry(int argc, char** argv, char** envp, EntryPointFunction entry);
  50. struct TLSData {
  51. size_t total_tls_size { 0 };
  52. void* tls_template { nullptr };
  53. size_t tls_template_size { 0 };
  54. size_t alignment { 0 };
  55. size_t static_tls_region_size { 0 };
  56. size_t static_tls_region_alignment { 0 };
  57. };
  58. static TLSData s_tls_data;
  59. static char** s_envp = nullptr;
  60. static __pthread_mutex_t s_loader_lock = __PTHREAD_MUTEX_INITIALIZER;
  61. static ByteString s_cwd;
  62. static bool s_allowed_to_check_environment_variables { false };
  63. static bool s_do_breakpoint_trap_before_entry { false };
  64. static StringView s_ld_library_path;
  65. static StringView s_main_program_pledge_promises;
  66. static ByteString s_loader_pledge_promises;
  67. static HashMap<StringView, DynamicObject::SymbolLookupResult> s_magic_functions;
  68. Optional<DynamicObject::SymbolLookupResult> DynamicLinker::lookup_global_symbol(StringView name)
  69. {
  70. auto symbol = DynamicObject::HashSymbol { name };
  71. for (auto& lib : s_global_objects) {
  72. auto res = lib.value->lookup_symbol(symbol);
  73. if (!res.has_value())
  74. continue;
  75. if (res.value().bind == STB_GLOBAL || res.value().bind == STB_WEAK)
  76. return res;
  77. // We don't want to allow local symbols to be pulled in to other modules
  78. }
  79. if (auto magic_lookup = s_magic_functions.get(name); magic_lookup.has_value())
  80. return *magic_lookup;
  81. return {};
  82. }
  83. static Result<NonnullRefPtr<DynamicLoader>, DlErrorMessage> map_library(ByteString const& filepath, int fd)
  84. {
  85. VERIFY(filepath.starts_with('/'));
  86. auto loader = TRY(ELF::DynamicLoader::try_create(fd, filepath));
  87. s_loaders.set(filepath, *loader);
  88. static size_t s_current_tls_offset = 0;
  89. if constexpr (TLS_VARIANT == 1) {
  90. if (loader->tls_alignment_of_current_object() != 0)
  91. s_current_tls_offset = align_up_to(s_current_tls_offset, loader->tls_alignment_of_current_object());
  92. loader->set_tls_offset(s_current_tls_offset);
  93. s_current_tls_offset += loader->tls_size_of_current_object();
  94. } else if constexpr (TLS_VARIANT == 2) {
  95. s_current_tls_offset -= loader->tls_size_of_current_object();
  96. if (loader->tls_alignment_of_current_object() != 0)
  97. s_current_tls_offset = align_down_to(s_current_tls_offset, loader->tls_alignment_of_current_object());
  98. loader->set_tls_offset(s_current_tls_offset);
  99. }
  100. // This actually maps the library at the intended and final place.
  101. auto main_library_object = loader->map();
  102. s_global_objects.set(filepath, *main_library_object);
  103. return loader;
  104. }
  105. Optional<ByteString> DynamicLinker::resolve_library(ByteString const& name, DynamicObject const& parent_object)
  106. {
  107. // Absolute and relative (to the current working directory) paths are already considered resolved.
  108. // However, ensure that the returned path is absolute and canonical, so pass it through LexicalPath.
  109. if (name.contains('/'))
  110. return LexicalPath::absolute_path(s_cwd, name);
  111. Vector<StringView> search_paths;
  112. // Search RPATH values indicated by the ELF (only if RUNPATH is not present).
  113. if (parent_object.runpath().is_empty())
  114. search_paths.extend(parent_object.rpath().split_view(':'));
  115. // Scan the LD_LIBRARY_PATH environment variable if applicable.
  116. search_paths.extend(s_ld_library_path.split_view(':'));
  117. // Search RUNPATH values indicated by the ELF.
  118. search_paths.extend(parent_object.runpath().split_view(':'));
  119. // Last are the default search paths.
  120. search_paths.append("/usr/lib"sv);
  121. search_paths.append("/usr/local/lib"sv);
  122. for (auto const& search_path : search_paths) {
  123. LexicalPath library_path(search_path.replace("$ORIGIN"sv, LexicalPath::dirname(parent_object.filepath()), ReplaceMode::FirstOnly));
  124. ByteString library_name = library_path.append(name).string();
  125. if (access(library_name.characters(), F_OK) == 0) {
  126. if (!library_name.starts_with('/')) {
  127. // FIXME: Non-absolute paths should resolve from the current working directory. However,
  128. // since that's almost never the effect that is actually desired, let's print
  129. // a warning and only implement it once something actually needs that behavior.
  130. dbgln("\033[33mWarning:\033[0m Resolving library '{}' resulted in non-absolute path '{}'. Check your binary for relative RPATHs and RUNPATHs.", name, library_name);
  131. }
  132. return library_name;
  133. }
  134. }
  135. return {};
  136. }
  137. static Result<NonnullRefPtr<DynamicLoader>, DlErrorMessage> map_library(ByteString const& path)
  138. {
  139. VERIFY(path.starts_with('/'));
  140. int fd = open(path.characters(), O_RDONLY);
  141. if (fd < 0)
  142. return DlErrorMessage { ByteString::formatted("Could not open shared library '{}': {}", path, strerror(errno)) };
  143. return map_library(path, fd);
  144. }
  145. static Vector<ByteString> get_dependencies(ByteString const& path)
  146. {
  147. VERIFY(path.starts_with('/'));
  148. auto name = LexicalPath::basename(path);
  149. auto lib = s_loaders.get(path).value();
  150. Vector<ByteString> dependencies;
  151. lib->for_each_needed_library([&dependencies, &name](auto needed_name) {
  152. if (name == needed_name)
  153. return;
  154. dependencies.append(needed_name);
  155. });
  156. return dependencies;
  157. }
  158. static Result<void, DlErrorMessage> map_dependencies(ByteString const& path)
  159. {
  160. VERIFY(path.starts_with('/'));
  161. dbgln_if(DYNAMIC_LOAD_DEBUG, "mapping dependencies for: {}", path);
  162. auto const& parent_object = (*s_loaders.get(path))->dynamic_object();
  163. for (auto const& needed_name : get_dependencies(path)) {
  164. dbgln_if(DYNAMIC_LOAD_DEBUG, "needed library: {}", needed_name.characters());
  165. auto dependency_path = DynamicLinker::resolve_library(needed_name, parent_object);
  166. if (!dependency_path.has_value())
  167. return DlErrorMessage { ByteString::formatted("Could not find required shared library: {}", needed_name) };
  168. if (!s_loaders.contains(dependency_path.value()) && !s_global_objects.contains(dependency_path.value())) {
  169. auto loader = TRY(map_library(dependency_path.value()));
  170. TRY(map_dependencies(loader->filepath()));
  171. }
  172. }
  173. dbgln_if(DYNAMIC_LOAD_DEBUG, "mapped dependencies for {}", path);
  174. return {};
  175. }
  176. static ErrorOr<FlatPtr> __create_new_tls_region()
  177. {
  178. void* static_tls_region = serenity_mmap(nullptr, s_tls_data.static_tls_region_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0, s_tls_data.static_tls_region_alignment, "Static TLS Data");
  179. if (static_tls_region == MAP_FAILED)
  180. return Error::from_syscall("mmap"sv, -errno);
  181. auto thread_pointer = calculate_tp_value_from_static_tls_region_address(bit_cast<FlatPtr>(static_tls_region), s_tls_data.tls_template_size, s_tls_data.static_tls_region_alignment);
  182. VERIFY(thread_pointer % s_tls_data.static_tls_region_alignment == 0);
  183. auto* tcb = get_tcb_pointer_from_thread_pointer(thread_pointer);
  184. // FIXME: Add support for dynamically-allocated TLS blocks.
  185. tcb->dynamic_thread_vector = nullptr;
  186. #if ARCH(X86_64)
  187. tcb->thread_pointer = bit_cast<void*>(thread_pointer);
  188. #endif
  189. auto* static_tls_blocks = get_pointer_to_first_static_tls_block_from_thread_pointer(thread_pointer, s_tls_data.tls_template_size, s_tls_data.static_tls_region_alignment);
  190. if (s_tls_data.tls_template_size != 0)
  191. memcpy(static_tls_blocks, s_tls_data.tls_template, s_tls_data.tls_template_size);
  192. return thread_pointer;
  193. }
  194. static ErrorOr<void> __free_tls_region(FlatPtr thread_pointer)
  195. {
  196. auto* static_tls_region = get_pointer_to_static_tls_region_from_thread_pointer(thread_pointer, s_tls_data.tls_template_size, s_tls_data.static_tls_region_alignment);
  197. if (munmap(static_tls_region, s_tls_data.static_tls_region_size) != 0)
  198. return Error::from_syscall("mmap"sv, -errno);
  199. return {};
  200. }
  201. static void allocate_tls()
  202. {
  203. // FIXME: Use the max p_align of all TLS segments.
  204. // We currently pass s_tls_data.static_tls_region_alignment as the alignment to mmap,
  205. // so we would have to manually insert padding, as mmap only accepts alignments that
  206. // are multiples of PAGE_SIZE. Or instead use aligned_alloc/posix_memalign?
  207. s_tls_data.alignment = PAGE_SIZE;
  208. for (auto const& data : s_loaders) {
  209. 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());
  210. s_tls_data.total_tls_size += data.value->tls_size_of_current_object() + data.value->tls_alignment_of_current_object();
  211. }
  212. if (s_tls_data.total_tls_size == 0)
  213. return;
  214. s_tls_data.tls_template_size = align_up_to(s_tls_data.total_tls_size, PAGE_SIZE);
  215. s_tls_data.tls_template = mmap_with_name(nullptr, s_tls_data.tls_template_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0, "TLS Template");
  216. if (s_tls_data.tls_template == MAP_FAILED) {
  217. dbgln("Failed to allocate memory for the TLS template");
  218. VERIFY_NOT_REACHED();
  219. }
  220. s_tls_data.static_tls_region_alignment = max(s_tls_data.alignment, sizeof(ThreadControlBlock));
  221. s_tls_data.static_tls_region_size = calculate_static_tls_region_size(s_tls_data.tls_template_size, s_tls_data.static_tls_region_alignment);
  222. auto tls_template = Bytes(s_tls_data.tls_template, s_tls_data.tls_template_size);
  223. // Initialize TLS data
  224. for (auto const& entry : s_loaders) {
  225. entry.value->copy_initial_tls_data_into(tls_template);
  226. }
  227. set_thread_pointer_register(MUST(__create_new_tls_region()));
  228. }
  229. static int __dl_iterate_phdr(DlIteratePhdrCallbackFunction callback, void* data)
  230. {
  231. pthread_mutex_lock(&s_loader_lock);
  232. ScopeGuard unlock_guard = [] { pthread_mutex_unlock(&s_loader_lock); };
  233. for (auto& it : s_global_objects) {
  234. auto& object = it.value;
  235. auto info = dl_phdr_info {
  236. .dlpi_addr = (Elf_Addr)object->base_address().as_ptr(),
  237. .dlpi_name = object->filepath().characters(),
  238. .dlpi_phdr = object->program_headers(),
  239. .dlpi_phnum = object->program_header_count()
  240. };
  241. auto res = callback(&info, sizeof(info), data);
  242. if (res != 0)
  243. return res;
  244. }
  245. return 0;
  246. }
  247. static void initialize_libc(DynamicObject& libc)
  248. {
  249. auto res = libc.lookup_symbol("__libc_init"sv);
  250. VERIFY(res.has_value());
  251. using libc_init_func = decltype(__libc_init);
  252. ((libc_init_func*)res.value().address.as_ptr())();
  253. }
  254. template<typename Callback>
  255. static void for_each_unfinished_dependency_of(ByteString const& path, HashTable<ByteString>& seen_names, Callback callback)
  256. {
  257. VERIFY(path.starts_with('/'));
  258. auto loader = s_loaders.get(path);
  259. if (!loader.has_value()) {
  260. // Not having a loader here means that the library has already been loaded in at an earlier point,
  261. // and the loader itself was cleared during the end of `linker_main`.
  262. return;
  263. }
  264. if (loader.value()->is_fully_relocated()) {
  265. if (!loader.value()->is_fully_initialized()) {
  266. // If we are ending up here, that possibly means that this library either dlopens itself or a library that depends
  267. // on it while running its initializers. Assuming that this is the only funny thing that the library does, there is
  268. // a reasonable chance that nothing breaks, so just warn and continue.
  269. dbgln("\033[33mWarning:\033[0m Querying for dependencies of '{}' while running its initializers", path);
  270. }
  271. return;
  272. }
  273. if (seen_names.contains(path))
  274. return;
  275. seen_names.set(path);
  276. for (auto const& needed_name : get_dependencies(path)) {
  277. auto dependency_path = *DynamicLinker::resolve_library(needed_name, loader.value()->dynamic_object());
  278. for_each_unfinished_dependency_of(dependency_path, seen_names, callback);
  279. }
  280. callback(*s_loaders.get(path).value());
  281. }
  282. static Vector<NonnullRefPtr<DynamicLoader>> collect_loaders_for_library(ByteString const& path)
  283. {
  284. VERIFY(path.starts_with('/'));
  285. HashTable<ByteString> seen_names;
  286. Vector<NonnullRefPtr<DynamicLoader>> loaders;
  287. for_each_unfinished_dependency_of(path, seen_names, [&](auto& loader) {
  288. loaders.append(loader);
  289. });
  290. return loaders;
  291. }
  292. static void drop_loader_promise(StringView promise_to_drop)
  293. {
  294. if (s_main_program_pledge_promises.is_empty() || s_loader_pledge_promises.is_empty())
  295. return;
  296. s_loader_pledge_promises = s_loader_pledge_promises.replace(promise_to_drop, ""sv, ReplaceMode::All);
  297. auto extended_promises = ByteString::formatted("{} {}", s_main_program_pledge_promises, s_loader_pledge_promises);
  298. Syscall::SC_pledge_params params {
  299. { extended_promises.characters(), extended_promises.length() },
  300. { nullptr, 0 },
  301. };
  302. int rc = syscall(SC_pledge, &params);
  303. if (rc < 0 && rc > -EMAXERRNO) {
  304. warnln("Failed to drop loader pledge promise: {}. errno={}", promise_to_drop, errno);
  305. _exit(1);
  306. }
  307. }
  308. static Result<void, DlErrorMessage> link_main_library(ByteString const& path, int flags)
  309. {
  310. VERIFY(path.starts_with('/'));
  311. auto loaders = collect_loaders_for_library(path);
  312. // Verify that all objects are already mapped
  313. for (auto& loader : loaders)
  314. VERIFY(!loader->map());
  315. for (auto& loader : loaders) {
  316. bool success = loader->link(flags);
  317. if (!success) {
  318. return DlErrorMessage { ByteString::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_tls_data.total_tls_size + loader.tls_size_of_current_object() + loader.tls_alignment_of_current_object() > s_tls_data.tls_template_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 = (u8 const*)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 { ByteString::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_tls_data.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 { ByteString::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 const* 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 __call_fini_functions()
  479. {
  480. typedef void (*FiniFunc)();
  481. for (auto& it : s_global_objects) {
  482. auto object = it.value;
  483. if (object->has_fini_array_section()) {
  484. auto fini_array_section = object->fini_array_section();
  485. FiniFunc* fini_begin = (FiniFunc*)(fini_array_section.address().as_ptr());
  486. FiniFunc* fini_end = fini_begin + fini_array_section.entry_count();
  487. while (fini_begin != fini_end) {
  488. --fini_end;
  489. // Android sources claim that these can be -1, to be ignored.
  490. // 0 deffiniely shows up. Apparently 0/-1 are valid? Confusing.
  491. if (!*fini_end || ((FlatPtr)*fini_end == (FlatPtr)-1))
  492. continue;
  493. (*fini_end)();
  494. }
  495. }
  496. if (object->has_fini_section()) {
  497. auto fini_function = object->fini_section_function();
  498. (fini_function)();
  499. }
  500. }
  501. }
  502. static char** __environ_value()
  503. {
  504. return s_envp;
  505. }
  506. static void read_environment_variables()
  507. {
  508. for (char** env = s_envp; *env; ++env) {
  509. StringView env_string { *env, strlen(*env) };
  510. if (env_string == "_LOADER_BREAKPOINT=1"sv) {
  511. s_do_breakpoint_trap_before_entry = true;
  512. }
  513. constexpr auto library_path_string = "LD_LIBRARY_PATH="sv;
  514. if (env_string.starts_with(library_path_string)) {
  515. s_ld_library_path = env_string.substring_view(library_path_string.length());
  516. }
  517. constexpr auto main_pledge_promises_key = "_LOADER_MAIN_PROGRAM_PLEDGE_PROMISES="sv;
  518. if (env_string.starts_with(main_pledge_promises_key)) {
  519. s_main_program_pledge_promises = env_string.substring_view(main_pledge_promises_key.length());
  520. }
  521. constexpr auto loader_pledge_promises_key = "_LOADER_PLEDGE_PROMISES="sv;
  522. if (env_string.starts_with(loader_pledge_promises_key)) {
  523. s_loader_pledge_promises = env_string.substring_view(loader_pledge_promises_key.length());
  524. }
  525. }
  526. }
  527. void ELF::DynamicLinker::linker_main(ByteString&& main_program_path, int main_program_fd, bool is_secure, int argc, char** argv, char** envp)
  528. {
  529. VERIFY(main_program_path.starts_with('/'));
  530. s_envp = envp;
  531. auto define_magic_function = [&](StringView name, auto function) {
  532. s_magic_functions.set(name,
  533. DynamicObject::SymbolLookupResult {
  534. .size = 8,
  535. .address = VirtualAddress { reinterpret_cast<void*>(function) },
  536. .bind = STB_GLOBAL,
  537. .type = STT_FUNC,
  538. });
  539. };
  540. define_magic_function("__call_fini_functions"sv, __call_fini_functions);
  541. define_magic_function("__create_new_tls_region"sv, __create_new_tls_region);
  542. define_magic_function("__dl_iterate_phdr"sv, __dl_iterate_phdr);
  543. define_magic_function("__dladdr"sv, __dladdr);
  544. define_magic_function("__dlclose"sv, __dlclose);
  545. define_magic_function("__dlopen"sv, __dlopen);
  546. define_magic_function("__dlsym"sv, __dlsym);
  547. define_magic_function("__environ_value"sv, __environ_value);
  548. define_magic_function("__free_tls_region"sv, __free_tls_region);
  549. char* raw_current_directory = getcwd(nullptr, 0);
  550. s_cwd = raw_current_directory;
  551. free(raw_current_directory);
  552. s_allowed_to_check_environment_variables = !is_secure;
  553. if (s_allowed_to_check_environment_variables)
  554. read_environment_variables();
  555. s_main_program_path = main_program_path;
  556. // NOTE: We always map the main library first, since it may require
  557. // placement at a specific address.
  558. auto result1 = map_library(main_program_path, main_program_fd);
  559. if (result1.is_error()) {
  560. warnln("{}", result1.error().text);
  561. fflush(stderr);
  562. _exit(1);
  563. }
  564. auto loader = result1.release_value();
  565. size_t needed_dependencies = 0;
  566. loader->for_each_needed_library([&needed_dependencies](auto) {
  567. needed_dependencies++;
  568. });
  569. bool has_interpreter = false;
  570. loader->image().for_each_program_header([&has_interpreter](const ELF::Image::ProgramHeader& program_header) {
  571. if (program_header.type() == PT_INTERP)
  572. has_interpreter = true;
  573. });
  574. // NOTE: Refuse to run a program if it has a dynamic section,
  575. // it is pie, and does not have an interpreter or needed libraries
  576. // which is also called "static-pie". These binaries are probably
  577. // some sort of ELF packers or dynamic loaders, and there's no added
  578. // value in trying to run them, as they will probably crash due to trying
  579. // to invoke syscalls from a non-syscall memory executable (code) region.
  580. if (loader->is_dynamic() && (!has_interpreter || needed_dependencies == 0) && loader->dynamic_object().is_pie()) {
  581. char const message[] = R"(error: the dynamic loader can't reasonably run static-pie ELF. static-pie ELFs might run executable code that invokes syscalls
  582. outside of the defined syscall memory executable (code) region security measure we implement.
  583. Examples of static-pie ELF objects are ELF packers, and the system dynamic loader itself.)";
  584. fprintf(stderr, "%s", message);
  585. fflush(stderr);
  586. _exit(1);
  587. }
  588. auto result2 = map_dependencies(main_program_path);
  589. if (result2.is_error()) {
  590. warnln("{}", result2.error().text);
  591. fflush(stderr);
  592. _exit(1);
  593. }
  594. dbgln_if(DYNAMIC_LOAD_DEBUG, "loaded all dependencies");
  595. for ([[maybe_unused]] auto& lib : s_loaders) {
  596. 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());
  597. }
  598. allocate_tls();
  599. auto entry_point_function = [&main_program_path] {
  600. auto result = link_main_library(main_program_path, RTLD_GLOBAL | RTLD_LAZY);
  601. if (result.is_error()) {
  602. warnln("{}", result.error().text);
  603. _exit(1);
  604. }
  605. drop_loader_promise("rpath"sv);
  606. auto& main_executable_loader = *s_loaders.get(main_program_path);
  607. auto entry_point = main_executable_loader->image().entry();
  608. if (main_executable_loader->is_dynamic())
  609. entry_point = entry_point.offset(main_executable_loader->base_address().get());
  610. return (EntryPointFunction)(entry_point.as_ptr());
  611. }();
  612. s_loaders.clear();
  613. int rc = syscall(SC_prctl, PR_SET_NO_NEW_SYSCALL_REGION_ANNOTATIONS, 1, 0, nullptr);
  614. if (rc < 0) {
  615. VERIFY_NOT_REACHED();
  616. }
  617. dbgln_if(DYNAMIC_LOAD_DEBUG, "Jumping to entry point: {:p}", entry_point_function);
  618. if (s_do_breakpoint_trap_before_entry) {
  619. #if ARCH(AARCH64)
  620. asm("brk #0");
  621. #elif ARCH(RISCV64)
  622. asm("ebreak");
  623. #elif ARCH(X86_64)
  624. asm("int3");
  625. #else
  626. # error "Unknown architecture"
  627. #endif
  628. }
  629. _invoke_entry(argc, argv, envp, entry_point_function);
  630. VERIFY_NOT_REACHED();
  631. }
  632. }