DynamicLinker.cpp 27 KB

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