blob: cdc4b86ffcdfec24a95024bbadf389e1d5b41736 [file] [log] [blame]
Dimitry Ivanov3f660572016-09-09 10:00:39 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29#include "linker_main.h"
30
Ryan Prichard701bd0c2018-11-21 16:23:03 -080031#include <link.h>
chenxinyuanchen8d7c0f42024-04-19 15:58:23 +080032#include <stdlib.h>
Ryan Prichard701bd0c2018-11-21 16:23:03 -080033#include <sys/auxv.h>
Elliott Hughes8f653f82024-05-29 22:25:37 +000034#include <sys/prctl.h>
Ryan Prichard701bd0c2018-11-21 16:23:03 -080035
Collin Fijalkovich47d27aa2021-03-24 10:17:39 -070036#include "linker.h"
Elliott Hughes838dbac2023-08-22 14:07:48 -070037#include "linker_auxv.h"
Collin Fijalkovich47d27aa2021-03-24 10:17:39 -070038#include "linker_cfi.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070039#include "linker_debug.h"
Ryan Prichard80e40f02019-10-31 19:54:46 -070040#include "linker_debuggerd.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070041#include "linker_gdb_support.h"
42#include "linker_globals.h"
43#include "linker_phdr.h"
Ryan Prichard339ecef2020-01-02 16:36:06 -080044#include "linker_relocate.h"
Peter Collingbourne1583cd22021-08-18 17:04:23 -070045#include "linker_relocs.h"
Ryan Prichard45d13492019-01-03 02:51:30 -080046#include "linker_tls.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070047#include "linker_utils.h"
48
Ryan Prichard9a027c72023-07-21 23:04:50 -070049#include "private/KernelArgumentBlock.h"
Ryan Prichard249757b2019-11-01 17:18:28 -070050#include "private/bionic_call_ifunc_resolver.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070051#include "private/bionic_globals.h"
52#include "private/bionic_tls.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070053
Ryan Prichard8f639a42018-10-01 23:10:05 -070054#include "android-base/unique_fd.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070055#include "android-base/strings.h"
56#include "android-base/stringprintf.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070057
Christopher Ferris7a3681e2017-04-24 17:48:32 -070058#include <async_safe/log.h>
Ryan Prichard701bd0c2018-11-21 16:23:03 -080059#include <bionic/libc_init_common.h>
Ryan Prichard45d13492019-01-03 02:51:30 -080060#include <bionic/pthread_internal.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070061
Dimitry Ivanov3f660572016-09-09 10:00:39 -070062#include <vector>
63
Ryan Prichard8f639a42018-10-01 23:10:05 -070064__LIBC_HIDDEN__ extern "C" void _start();
Dimitry Ivanov3f660572016-09-09 10:00:39 -070065
66static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf);
67
Ryan Prichard9729f352018-07-13 22:40:26 -070068static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
69 ElfW(Addr)* base, ElfW(Addr)* load_bias);
70
Vic Yang1bf62b22019-08-13 14:53:28 -070071static void set_bss_vma_name(soinfo* si);
72
Mitch Phillips7c1f3772023-09-28 13:45:59 +020073void __libc_init_mte(const memtag_dynamic_entries_t* memtag_dynamic_entries, const void* phdr_start,
74 size_t phdr_count, uintptr_t load_bias, void* stack_top);
Evgenii Stepanov8564b8d2020-12-15 13:55:32 -080075
Elliott Hughes54564df2024-07-19 13:59:51 -040076__printflike(1, 2) static void __linker_error(const char* fmt, ...) {
77 va_list ap;
78
79 va_start(ap, fmt);
80 async_safe_format_fd_va_list(STDERR_FILENO, fmt, ap);
81 write(STDERR_FILENO, "\n", 1);
82 va_end(ap);
83
84 va_start(ap, fmt);
85 async_safe_format_log_va_list(ANDROID_LOG_FATAL, "linker", fmt, ap);
86 va_end(ap);
87
88 _exit(EXIT_FAILURE);
89}
90
91static void __linker_cannot_link(const char* argv0) {
92 __linker_error("CANNOT LINK EXECUTABLE \"%s\": %s", argv0, linker_get_error_buffer());
93}
94
Dimitry Ivanov3f660572016-09-09 10:00:39 -070095// These should be preserved static to avoid emitting
96// RELATIVE relocations for the part of the code running
97// before linker links itself.
98
99// TODO (dimtiry): remove somain, rename solist to solist_head
100static soinfo* solist;
101static soinfo* sonext;
Evgenii Stepanov6bbb75a2023-12-06 18:54:45 +0000102static soinfo* somain; // main process, always the one after libdl_info
Ryan Prichard04896452018-08-20 17:44:42 -0700103static soinfo* solinker;
dimitry8b142562018-05-09 15:22:38 +0200104static soinfo* vdso; // vdso if present
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700105
106void solist_add_soinfo(soinfo* si) {
107 sonext->next = si;
108 sonext = si;
109}
110
111bool solist_remove_soinfo(soinfo* si) {
112 soinfo *prev = nullptr, *trav;
113 for (trav = solist; trav != nullptr; trav = trav->next) {
114 if (trav == si) {
115 break;
116 }
117 prev = trav;
118 }
119
120 if (trav == nullptr) {
121 // si was not in solist
122 PRINT("name \"%s\"@%p is not in solist!", si->get_realpath(), si);
123 return false;
124 }
125
126 // prev will never be null, because the first entry in solist is
127 // always the static libdl_info.
George Burgess IV70591002017-06-27 16:23:45 -0700128 CHECK(prev != nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700129 prev->next = si->next;
130 if (si == sonext) {
131 sonext = prev;
132 }
133
134 return true;
135}
136
137soinfo* solist_get_head() {
138 return solist;
139}
140
141soinfo* solist_get_somain() {
142 return somain;
143}
144
dimitry8b142562018-05-09 15:22:38 +0200145soinfo* solist_get_vdso() {
146 return vdso;
147}
148
Elliott Hughes90f96b92019-05-09 15:56:39 -0700149bool g_is_ldd;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700150int g_ld_debug_verbosity;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700151
152static std::vector<std::string> g_ld_preload_names;
153
154static std::vector<soinfo*> g_ld_preloads;
155
156static void parse_path(const char* path, const char* delimiters,
157 std::vector<std::string>* resolved_paths) {
158 std::vector<std::string> paths;
159 split_path(path, delimiters, &paths);
160 resolve_paths(paths, resolved_paths);
161}
162
163static void parse_LD_LIBRARY_PATH(const char* path) {
164 std::vector<std::string> ld_libary_paths;
165 parse_path(path, ":", &ld_libary_paths);
166 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
167}
168
169static void parse_LD_PRELOAD(const char* path) {
170 g_ld_preload_names.clear();
171 if (path != nullptr) {
172 // We have historically supported ':' as well as ' ' in LD_PRELOAD.
173 g_ld_preload_names = android::base::Split(path, " :");
Josh Gao44f6e182017-10-18 17:25:24 -0700174 g_ld_preload_names.erase(std::remove_if(g_ld_preload_names.begin(), g_ld_preload_names.end(),
Josh Gao27242c62017-10-20 17:45:13 -0700175 [](const std::string& s) { return s.empty(); }),
176 g_ld_preload_names.end());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700177 }
178}
179
180// An empty list of soinfos
181static soinfo_list_t g_empty_list;
182
Ryan Prichard07440a82018-11-22 03:16:06 -0800183static void add_vdso() {
184 ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(getauxval(AT_SYSINFO_EHDR));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700185 if (ehdr_vdso == nullptr) {
186 return;
187 }
188
Elliott Hughes54564df2024-07-19 13:59:51 -0400189 vdso = soinfo_alloc(&g_default_namespace, "[vdso]", nullptr, 0, 0);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700190
Elliott Hughes54564df2024-07-19 13:59:51 -0400191 vdso->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
192 vdso->phnum = ehdr_vdso->e_phnum;
193 vdso->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
194 vdso->size = phdr_table_get_load_size(vdso->phdr, vdso->phnum);
195 vdso->load_bias = get_elf_exec_load_bias(ehdr_vdso);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700196
Elliott Hughes54564df2024-07-19 13:59:51 -0400197 if (!vdso->prelink_image() || !vdso->link_image(SymbolLookupList(vdso), vdso, nullptr, nullptr)) {
198 __linker_cannot_link(g_argv[0]);
199 }
dimitry8b142562018-05-09 15:22:38 +0200200
Elliott Hughes54564df2024-07-19 13:59:51 -0400201 // Prevent accidental unloads...
202 vdso->set_dt_flags_1(vdso->get_dt_flags_1() | DF_1_NODELETE);
203 vdso->set_linked();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700204}
205
Ryan Prichard04896452018-08-20 17:44:42 -0700206// Initializes an soinfo's link_map_head field using other fields from the
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700207// soinfo (phdr, phnum, load_bias). The soinfo's realpath must not change after
208// this function is called.
209static void init_link_map_head(soinfo& info) {
Ryan Prichard04896452018-08-20 17:44:42 -0700210 auto& map = info.link_map_head;
211 map.l_addr = info.load_bias;
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700212 map.l_name = const_cast<char*>(info.get_realpath());
Ryan Prichard04896452018-08-20 17:44:42 -0700213 phdr_table_get_dynamic_section(info.phdr, info.phnum, info.load_bias, &map.l_ld, nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700214}
215
216extern "C" int __system_properties_init(void);
217
Ryan Prichard8f639a42018-10-01 23:10:05 -0700218struct ExecutableInfo {
219 std::string path;
220 struct stat file_stat;
221 const ElfW(Phdr)* phdr;
222 size_t phdr_count;
223 ElfW(Addr) entry_point;
Kalesh Singh4084b552024-03-13 13:35:49 -0700224 bool should_pad_segments;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700225};
226
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000227static ExecutableInfo get_executable_info(const char* arg_path) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700228 ExecutableInfo result = {};
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000229 char const* exe_path = "/proc/self/exe";
Ryan Prichard8f639a42018-10-01 23:10:05 -0700230
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000231 // Stat "/proc/self/exe" instead of executable_path because
232 // the executable could be unlinked by this point and it should
233 // not cause a crash (see http://b/31084669)
234 if (TEMP_FAILURE_RETRY(stat(exe_path, &result.file_stat) == -1)) {
235 // Fallback to argv[0] for the case where /proc isn't available
236 if (TEMP_FAILURE_RETRY(stat(arg_path, &result.file_stat) == -1)) {
237 async_safe_fatal("unable to stat either \"/proc/self/exe\" or \"%s\": %s",
238 arg_path, strerror(errno));
Tom Cherry66bc4282018-11-08 13:40:52 -0800239 }
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000240 exe_path = arg_path;
241 }
242
Elliott Hughes33de2732024-04-25 16:44:48 +0000243 // Path might be a symlink; we need the target so that we get the right
244 // linker configuration later.
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000245 char sym_path[PATH_MAX];
Elliott Hughes33de2732024-04-25 16:44:48 +0000246 result.path = std::string(realpath(exe_path, sym_path) != nullptr ? sym_path : exe_path);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700247
Ryan Prichard07440a82018-11-22 03:16:06 -0800248 result.phdr = reinterpret_cast<const ElfW(Phdr)*>(getauxval(AT_PHDR));
249 result.phdr_count = getauxval(AT_PHNUM);
250 result.entry_point = getauxval(AT_ENTRY);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700251 return result;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700252}
253
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800254#if defined(__LP64__)
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700255static char kFallbackLinkerPath[] = "/system/bin/linker64";
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800256#else
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700257static char kFallbackLinkerPath[] = "/system/bin/linker";
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800258#endif
259
Ryan Prichard8f639a42018-10-01 23:10:05 -0700260// Load an executable. Normally the kernel has already loaded the executable when the linker
261// starts. The linker can be invoked directly on an executable, though, and then the linker must
262// load it. This function doesn't load dependencies or resolve relocations.
263static ExecutableInfo load_executable(const char* orig_path) {
264 ExecutableInfo result = {};
265
266 if (orig_path[0] != '/') {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000267 __linker_error("error: expected absolute path: \"%s\"", orig_path);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700268 }
269
270 off64_t file_offset;
271 android::base::unique_fd fd(open_executable(orig_path, &file_offset, &result.path));
272 if (fd.get() == -1) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000273 __linker_error("error: unable to open file \"%s\"", orig_path);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700274 }
275
276 if (TEMP_FAILURE_RETRY(fstat(fd.get(), &result.file_stat)) == -1) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000277 __linker_error("error: unable to stat \"%s\": %m", result.path.c_str());
Ryan Prichard8f639a42018-10-01 23:10:05 -0700278 }
279
280 ElfReader elf_reader;
281 if (!elf_reader.Read(result.path.c_str(), fd.get(), file_offset, result.file_stat.st_size)) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000282 __linker_error("error: %s", linker_get_error_buffer());
Ryan Prichard8f639a42018-10-01 23:10:05 -0700283 }
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400284 address_space_params address_space;
285 if (!elf_reader.Load(&address_space)) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000286 __linker_error("error: %s", linker_get_error_buffer());
Ryan Prichard8f639a42018-10-01 23:10:05 -0700287 }
288
289 result.phdr = elf_reader.loaded_phdr();
290 result.phdr_count = elf_reader.phdr_count();
291 result.entry_point = elf_reader.entry_point();
Kalesh Singh4084b552024-03-13 13:35:49 -0700292 result.should_pad_segments = elf_reader.should_pad_segments();
Ryan Prichard8f639a42018-10-01 23:10:05 -0700293 return result;
294}
295
Tamas Petz8d55d182020-02-24 14:15:25 +0100296static void platform_properties_init() {
297#if defined(__aarch64__)
298 const unsigned long hwcap2 = getauxval(AT_HWCAP2);
299 g_platform_properties.bti_supported = (hwcap2 & HWCAP2_BTI) != 0;
300#endif
301}
302
Ryan Prichard8f639a42018-10-01 23:10:05 -0700303static ElfW(Addr) linker_main(KernelArgumentBlock& args, const char* exe_to_load) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800304 ProtectedDataGuard guard;
305
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700306#if TIMING
307 struct timeval t0, t1;
308 gettimeofday(&t0, 0);
309#endif
310
311 // Sanitize the environment.
Ryan Prichard48b11592018-11-22 02:41:36 -0800312 __libc_init_AT_SECURE(args.envp);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700313
314 // Initialize system properties
315 __system_properties_init(); // may use 'environ'
316
Tamas Petz8d55d182020-02-24 14:15:25 +0100317 // Initialize platform properties.
318 platform_properties_init();
319
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700320 // Register the debuggerd signal handler.
Ryan Prichard80e40f02019-10-31 19:54:46 -0700321 linker_debuggerd_init();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700322
323 g_linker_logger.ResetState();
324
Elliott Hughes838dbac2023-08-22 14:07:48 -0700325 // Enable debugging logs?
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700326 const char* LD_DEBUG = getenv("LD_DEBUG");
327 if (LD_DEBUG != nullptr) {
328 g_ld_debug_verbosity = atoi(LD_DEBUG);
329 }
330
Elliott Hughes838dbac2023-08-22 14:07:48 -0700331 if (getenv("LD_SHOW_AUXV") != nullptr) ld_show_auxv(args.auxv);
332
Elliott Hughes0f1e4012024-07-17 12:01:56 -0400333 INFO("[ Android dynamic linker (" ABI_STRING ") ]");
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700334
335 // These should have been sanitized by __libc_init_AT_SECURE, but the test
336 // doesn't cost us anything.
337 const char* ldpath_env = nullptr;
338 const char* ldpreload_env = nullptr;
339 if (!getauxval(AT_SECURE)) {
340 ldpath_env = getenv("LD_LIBRARY_PATH");
341 if (ldpath_env != nullptr) {
342 INFO("[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
343 }
344 ldpreload_env = getenv("LD_PRELOAD");
345 if (ldpreload_env != nullptr) {
346 INFO("[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
347 }
348 }
349
Ryan Prichard8f639a42018-10-01 23:10:05 -0700350 const ExecutableInfo exe_info = exe_to_load ? load_executable(exe_to_load) :
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000351 get_executable_info(args.argv[0]);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700352
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700353 INFO("[ Linking executable \"%s\" ]", exe_info.path.c_str());
Martin Stjernholm95252ee2019-02-22 22:48:59 +0000354
Ryan Prichard04896452018-08-20 17:44:42 -0700355 // Initialize the main exe's soinfo.
Ryan Prichard8f639a42018-10-01 23:10:05 -0700356 soinfo* si = soinfo_alloc(&g_default_namespace,
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700357 exe_info.path.c_str(), &exe_info.file_stat,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700358 0, RTLD_GLOBAL);
Ryan Prichard04896452018-08-20 17:44:42 -0700359 somain = si;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700360 si->phdr = exe_info.phdr;
361 si->phnum = exe_info.phdr_count;
Kalesh Singh4084b552024-03-13 13:35:49 -0700362 si->set_should_pad_segments(exe_info.should_pad_segments);
Ryan Prichard04896452018-08-20 17:44:42 -0700363 get_elf_base_from_phdr(si->phdr, si->phnum, &si->base, &si->load_bias);
364 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
365 si->dynamic = nullptr;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700366 si->set_main_executable();
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700367 init_link_map_head(*si);
368
Vic Yang1bf62b22019-08-13 14:53:28 -0700369 set_bss_vma_name(si);
370
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700371 // Use the executable's PT_INTERP string as the solinker filename in the
372 // dynamic linker's module list. gdb reads both PT_INTERP and the module list,
373 // and if the paths for the linker are different, gdb will report that the
374 // PT_INTERP linker path was unloaded once the module list is initialized.
375 // There are three situations to handle:
376 // - the APEX linker (/system/bin/linker[64] -> /apex/.../linker[64])
377 // - the ASAN linker (/system/bin/linker_asan[64] -> /apex/.../linker[64])
378 // - the bootstrap linker (/system/bin/bootstrap/linker[64])
379 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
380 somain->load_bias);
381 if (interp == nullptr) {
382 // This case can happen if the linker attempts to execute itself
383 // (e.g. "linker64 /system/bin/linker64").
384 interp = kFallbackLinkerPath;
385 }
386 solinker->set_realpath(interp);
387 init_link_map_head(*solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700388
Tamas Petz8d55d182020-02-24 14:15:25 +0100389#if defined(__aarch64__)
390 if (exe_to_load == nullptr) {
391 // Kernel does not add PROT_BTI to executable pages of the loaded ELF.
392 // Apply appropriate protections here if it is needed.
393 auto note_gnu_property = GnuPropertySection(somain);
394 if (note_gnu_property.IsBTICompatible() &&
395 (phdr_table_protect_segments(somain->phdr, somain->phnum, somain->load_bias,
Kalesh Singh4084b552024-03-13 13:35:49 -0700396 somain->should_pad_segments(), &note_gnu_property) < 0)) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000397 __linker_error("error: can't protect segments for \"%s\": %m", exe_info.path.c_str());
Tamas Petz8d55d182020-02-24 14:15:25 +0100398 }
399 }
400#endif
401
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700402 // Register the main executable and the linker upfront to have
403 // gdb aware of them before loading the rest of the dependency
404 // tree.
Ryan Prichard04896452018-08-20 17:44:42 -0700405 //
406 // gdb expects the linker to be in the debug shared object list.
407 // Without this, gdb has trouble locating the linker's ".text"
408 // and ".plt" sections. Gdb could also potentially use this to
409 // relocate the offset of our exported 'rtld_db_dlactivity' symbol.
410 //
411 insert_link_map_into_debug_map(&si->link_map_head);
412 insert_link_map_into_debug_map(&solinker->link_map_head);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700413
Ryan Prichard07440a82018-11-22 03:16:06 -0800414 add_vdso();
Ryan Prichard14dd9922018-08-20 17:43:44 -0700415
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700416 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800417
Elliott Hughes71abb3d2024-05-17 12:16:16 +0000418 // For security reasons we dropped non-PIE support in API level 21,
419 // and the NDK no longer supports earlier API levels.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700420 if (elf_hdr->e_type != ET_DYN) {
Elliott Hughes71abb3d2024-05-17 12:16:16 +0000421 __linker_error("error: %s: Android only supports position-independent "
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000422 "executables (-fPIE)", exe_info.path.c_str());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700423 }
424
425 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
426 parse_LD_LIBRARY_PATH(ldpath_env);
427 parse_LD_PRELOAD(ldpreload_env);
428
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700429 std::vector<android_namespace_t*> namespaces = init_default_namespaces(exe_info.path.c_str());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700430
Elliott Hughesad2d0382017-07-31 11:43:34 -0700431 if (!si->prelink_image()) __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700432
433 // add somain to global group
434 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
Jiyong Park02586a22017-05-20 01:01:24 +0900435 // ... and add it to all other linked namespaces
436 for (auto linked_ns : namespaces) {
437 if (linked_ns != &g_default_namespace) {
438 linked_ns->add_soinfo(somain);
439 somain->add_secondary_namespace(linked_ns);
440 }
441 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700442
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800443 linker_setup_exe_static_tls(g_argv[0]);
444
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700445 // Load ld_preloads and dependencies.
446 std::vector<const char*> needed_library_name_list;
447 size_t ld_preloads_count = 0;
448
449 for (const auto& ld_preload_name : g_ld_preload_names) {
450 needed_library_name_list.push_back(ld_preload_name.c_str());
451 ++ld_preloads_count;
452 }
453
454 for_each_dt_needed(si, [&](const char* name) {
455 needed_library_name_list.push_back(name);
456 });
457
458 const char** needed_library_names = &needed_library_name_list[0];
459 size_t needed_libraries_count = needed_library_name_list.size();
460
461 if (needed_libraries_count > 0 &&
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800462 !find_libraries(&g_default_namespace,
463 si,
464 needed_library_names,
465 needed_libraries_count,
466 nullptr,
467 &g_ld_preloads,
468 ld_preloads_count,
469 RTLD_GLOBAL,
470 nullptr,
471 true /* add_as_children */,
Jiyong Park02586a22017-05-20 01:01:24 +0900472 &namespaces)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700473 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700474 } else if (needed_libraries_count == 0) {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800475 if (!si->link_image(SymbolLookupList(si), si, nullptr, nullptr)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700476 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700477 }
478 si->increment_ref_count();
479 }
Ryan Prichard32bb3672024-03-08 16:53:06 -0800480
481 // Exit early for ldd. We don't want to run the code that was loaded, so skip
482 // the constructor calls. Skip CFI setup because it would call __cfi_init in
483 // libdl.so.
484 if (g_is_ldd) _exit(EXIT_SUCCESS);
485
Florian Mayere65e1932024-02-15 22:20:54 +0000486#if defined(__aarch64__)
487 // This has to happen after the find_libraries, which will have collected any possible
488 // libraries that request memtag_stack in the dynamic section.
489 __libc_init_mte(somain->memtag_dynamic_entries(), somain->phdr, somain->phnum, somain->load_bias,
490 args.argv);
491#endif
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700492
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800493 linker_finalize_static_tls();
Ryan Prichard45d13492019-01-03 02:51:30 -0800494 __libc_init_main_thread_final();
495
Elliott Hughesad2d0382017-07-31 11:43:34 -0700496 if (!get_cfi_shadow()->InitialLinkDone(solist)) __linker_cannot_link(g_argv[0]);
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700497
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800498 si->call_pre_init_constructors();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800499 si->call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700500
501#if TIMING
502 gettimeofday(&t1, nullptr);
Vic Yang7b9db342019-04-16 14:54:58 -0700503 PRINT("LINKER TIME: %s: %d microseconds", g_argv[0],
504 static_cast<int>(((static_cast<long long>(t1.tv_sec) * 1000000LL) +
505 static_cast<long long>(t1.tv_usec)) -
506 ((static_cast<long long>(t0.tv_sec) * 1000000LL) +
507 static_cast<long long>(t0.tv_usec))));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700508#endif
509#if STATS
Vic Yang542db792019-07-25 10:39:27 -0700510 print_linker_stats();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700511#endif
Ryan Prichard78cd2832019-10-25 17:46:43 -0700512#if TIMING || STATS
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700513 fflush(stdout);
514#endif
515
Vic Yangbb7e1232019-01-29 20:23:16 -0800516 // We are about to hand control over to the executable loaded. We don't want
517 // to leave dirty pages behind unnecessarily.
518 purge_unused_memory();
519
Ryan Prichard8f639a42018-10-01 23:10:05 -0700520 ElfW(Addr) entry = exe_info.entry_point;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700521 TRACE("[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
522 return entry;
523}
524
525/* Compute the load-bias of an existing executable. This shall only
526 * be used to compute the load bias of an executable or shared library
527 * that was loaded by the kernel itself.
528 *
529 * Input:
530 * elf -> address of ELF header, assumed to be at the start of the file.
531 * Return:
532 * load bias, i.e. add the value of any p_vaddr in the file to get
533 * the corresponding address in memory.
534 */
535static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
536 ElfW(Addr) offset = elf->e_phoff;
537 const ElfW(Phdr)* phdr_table =
538 reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
539 const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
540
541 for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
542 if (phdr->p_type == PT_LOAD) {
543 return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
544 }
545 }
546 return 0;
547}
548
Ryan Prichard9729f352018-07-13 22:40:26 -0700549/* Find the load bias and base address of an executable or shared object loaded
550 * by the kernel. The ELF file's PHDR table must have a PT_PHDR entry.
551 *
552 * A VDSO doesn't have a PT_PHDR entry in its PHDR table.
553 */
554static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
555 ElfW(Addr)* base, ElfW(Addr)* load_bias) {
556 for (size_t i = 0; i < phdr_count; ++i) {
557 if (phdr_table[i].p_type == PT_PHDR) {
558 *load_bias = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_vaddr;
559 *base = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_offset;
560 return;
561 }
562 }
563 async_safe_fatal("Could not find a PHDR: broken executable?");
564}
565
Vic Yang1bf62b22019-08-13 14:53:28 -0700566/*
567 * Set anonymous VMA name for .bss section. For DSOs loaded by the linker, this
568 * is done by ElfReader. This function is here for DSOs loaded by the kernel,
569 * namely the linker itself and the main executable.
570 */
571static void set_bss_vma_name(soinfo* si) {
572 for (size_t i = 0; i < si->phnum; ++i) {
573 auto phdr = &si->phdr[i];
574
575 if (phdr->p_type != PT_LOAD) {
576 continue;
577 }
578
579 ElfW(Addr) seg_start = phdr->p_vaddr + si->load_bias;
Peter Collingbournebb11ee62022-05-02 12:26:16 -0700580 ElfW(Addr) seg_page_end = page_end(seg_start + phdr->p_memsz);
581 ElfW(Addr) seg_file_end = page_end(seg_start + phdr->p_filesz);
Vic Yang1bf62b22019-08-13 14:53:28 -0700582
583 if (seg_page_end > seg_file_end) {
584 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME,
585 reinterpret_cast<void*>(seg_file_end), seg_page_end - seg_file_end,
586 ".bss");
587 }
588 }
589}
590
Ryan Prichard249757b2019-11-01 17:18:28 -0700591#if defined(USE_RELA)
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700592using RelType = ElfW(Rela);
593const unsigned kRelTag = DT_RELA;
594const unsigned kRelSzTag = DT_RELASZ;
Ryan Prichard249757b2019-11-01 17:18:28 -0700595#else
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700596using RelType = ElfW(Rel);
597const unsigned kRelTag = DT_REL;
598const unsigned kRelSzTag = DT_RELSZ;
599#endif
Ryan Prichard249757b2019-11-01 17:18:28 -0700600
Evgenii Stepanov6bbb75a2023-12-06 18:54:45 +0000601extern __LIBC_HIDDEN__ ElfW(Ehdr) __ehdr_start;
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700602
603static void call_ifunc_resolvers_for_section(RelType* begin, RelType* end) {
604 auto ehdr = reinterpret_cast<ElfW(Addr)>(&__ehdr_start);
605 for (RelType *r = begin; r != end; ++r) {
606 if (ELFW(R_TYPE)(r->r_info) != R_GENERIC_IRELATIVE) {
607 continue;
608 }
609 ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(ehdr + r->r_offset);
610#if defined(USE_RELA)
611 ElfW(Addr) resolver = ehdr + r->r_addend;
612#else
613 ElfW(Addr) resolver = ehdr + *offset;
614#endif
Ryan Prichard249757b2019-11-01 17:18:28 -0700615 *offset = __bionic_call_ifunc_resolver(resolver);
616 }
617}
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700618
Ryan Prichard2a901e62024-04-04 03:05:35 -0700619static void relocate_linker() {
620 // The linker should only have relative relocations (in RELR) and IRELATIVE
621 // relocations. Find the IRELATIVE relocations using the DT_JMPREL and
622 // DT_PLTRELSZ, or DT_RELA/DT_RELASZ (DT_REL/DT_RELSZ on ILP32).
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700623 auto ehdr = reinterpret_cast<ElfW(Addr)>(&__ehdr_start);
624 auto* phdr = reinterpret_cast<ElfW(Phdr)*>(ehdr + __ehdr_start.e_phoff);
625 for (size_t i = 0; i != __ehdr_start.e_phnum; ++i) {
626 if (phdr[i].p_type != PT_DYNAMIC) {
627 continue;
628 }
629 auto *dyn = reinterpret_cast<ElfW(Dyn)*>(ehdr + phdr[i].p_vaddr);
Ryan Prichard2a901e62024-04-04 03:05:35 -0700630 ElfW(Addr) relr = 0, relrsz = 0, pltrel = 0, pltrelsz = 0, rel = 0, relsz = 0;
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700631 for (size_t j = 0, size = phdr[i].p_filesz / sizeof(ElfW(Dyn)); j != size; ++j) {
Ryan Prichard2a901e62024-04-04 03:05:35 -0700632 const auto tag = dyn[j].d_tag;
633 const auto val = dyn[j].d_un.d_ptr;
Elliott Hughesf67f27b2024-03-28 14:54:30 +0000634 // We don't currently handle IRELATIVE relocations in DT_ANDROID_REL[A].
Peter Collingbournec630da52024-03-26 13:24:06 -0700635 // We disabled DT_ANDROID_REL[A] at build time; verify that it was actually disabled.
Ryan Prichard2a901e62024-04-04 03:05:35 -0700636 CHECK(tag != DT_ANDROID_REL && tag != DT_ANDROID_RELA);
637 if (tag == DT_RELR || tag == DT_ANDROID_RELR) {
638 relr = val;
639 } else if (tag == DT_RELRSZ || tag == DT_ANDROID_RELRSZ) {
640 relrsz = val;
641 } else if (tag == DT_JMPREL) {
642 pltrel = val;
643 } else if (tag == DT_PLTRELSZ) {
644 pltrelsz = val;
645 } else if (tag == kRelTag) {
646 rel = val;
647 } else if (tag == kRelSzTag) {
648 relsz = val;
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700649 }
650 }
Ryan Prichard2a901e62024-04-04 03:05:35 -0700651 // Apply RELR relocations first so that the GOT is initialized for ifunc
652 // resolvers.
653 if (relr && relrsz) {
654 relocate_relr(reinterpret_cast<ElfW(Relr*)>(ehdr + relr),
655 reinterpret_cast<ElfW(Relr*)>(ehdr + relr + relrsz), ehdr);
656 }
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700657 if (pltrel && pltrelsz) {
658 call_ifunc_resolvers_for_section(reinterpret_cast<RelType*>(ehdr + pltrel),
659 reinterpret_cast<RelType*>(ehdr + pltrel + pltrelsz));
660 }
661 if (rel && relsz) {
662 call_ifunc_resolvers_for_section(reinterpret_cast<RelType*>(ehdr + rel),
663 reinterpret_cast<RelType*>(ehdr + rel + relsz));
664 }
665 }
666}
Ryan Prichard249757b2019-11-01 17:18:28 -0700667
Ryan Prichard94a8e852019-11-05 14:19:18 -0800668// Usable before ifunc resolvers have been called. This function is compiled with -ffreestanding.
669static void linker_memclr(void* dst, size_t cnt) {
670 for (size_t i = 0; i < cnt; ++i) {
671 reinterpret_cast<char*>(dst)[i] = '\0';
672 }
673}
674
Ryan Prichard1990ba52019-02-07 21:31:31 -0800675// Detect an attempt to run the linker on itself. e.g.:
676// /system/bin/linker64 /system/bin/linker64
677// Use priority-1 to run this constructor before other constructors.
678__attribute__((constructor(1))) static void detect_self_exec() {
679 // Normally, the linker initializes the auxv global before calling its
680 // constructors. If the linker loads itself, though, the first loader calls
681 // the second loader's constructors before calling __linker_init.
682 if (__libc_shared_globals()->auxv != nullptr) {
683 return;
684 }
685#if defined(__i386__)
686 // We don't have access to the auxv struct from here, so use the int 0x80
687 // fallback.
688 __libc_sysinfo = reinterpret_cast<void*>(__libc_int0x80);
689#endif
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000690 __linker_error("error: linker cannot load itself");
Ryan Prichard1990ba52019-02-07 21:31:31 -0800691}
692
Ryan Prichard742982d2018-05-30 22:32:17 -0700693static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700694__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700695
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700696/*
697 * This is the entry point for the linker, called from begin.S. This
698 * method is responsible for fixing the linker's own relocations, and
699 * then calling __linker_init_post_relocation().
700 *
701 * Because this method is called before the linker has fixed it's own
702 * relocations, any attempt to reference an extern variable, extern
703 * function, or other GOT reference will generate a segfault.
704 */
705extern "C" ElfW(Addr) __linker_init(void* raw_args) {
Ryan Prichard67e8f222023-08-18 16:21:48 -0700706 // Unlock the loader mutex immediately before transferring to the executable's
707 // entry point. This must happen after destructors are called in this function
708 // (e.g. ~soinfo), so declare this variable very early.
709 struct DlMutexUnlocker {
710 ~DlMutexUnlocker() { pthread_mutex_unlock(&g_dl_mutex); }
711 } unlocker;
712
Ryan Prichard9cfca862018-11-22 02:44:09 -0800713 // Initialize TLS early so system calls and errno work.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700714 KernelArgumentBlock args(raw_args);
Ryan Prichard94a8e852019-11-05 14:19:18 -0800715 bionic_tcb temp_tcb __attribute__((uninitialized));
716 linker_memclr(&temp_tcb, sizeof(temp_tcb));
Ryan Prichard45d13492019-01-03 02:51:30 -0800717 __libc_init_main_thread_early(args, &temp_tcb);
Ryan Prichard27475b52018-05-17 17:14:18 -0700718
Ryan Prichard8f639a42018-10-01 23:10:05 -0700719 // When the linker is run by itself (rather than as an interpreter for
720 // another program), AT_BASE is 0.
Ryan Prichard07440a82018-11-22 03:16:06 -0800721 ElfW(Addr) linker_addr = getauxval(AT_BASE);
Ryan Prichard9729f352018-07-13 22:40:26 -0700722 if (linker_addr == 0) {
Ryan Prichard1990ba52019-02-07 21:31:31 -0800723 // The AT_PHDR and AT_PHNUM aux values describe this linker instance, so use
724 // the phdr to find the linker's base address.
Ryan Prichard9729f352018-07-13 22:40:26 -0700725 ElfW(Addr) load_bias;
726 get_elf_base_from_phdr(
Ryan Prichard07440a82018-11-22 03:16:06 -0800727 reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR)), getauxval(AT_PHNUM),
Ryan Prichard9729f352018-07-13 22:40:26 -0700728 &linker_addr, &load_bias);
729 }
George Burgess IV70591002017-06-27 16:23:45 -0700730
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700731 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
732 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
733
Ryan Prichard2a901e62024-04-04 03:05:35 -0700734 // Relocate the linker. This step will initialize the GOT, which is needed for
735 // accessing non-hidden global variables. (On some targets, the stack
736 // protector uses GOT accesses rather than TLS.) Relocating the linker will
737 // also call the linker's ifunc resolvers so that string.h functions can be
738 // used.
739 relocate_linker();
Ryan Prichard249757b2019-11-01 17:18:28 -0700740
Ryan Prichard04896452018-08-20 17:44:42 -0700741 soinfo tmp_linker_so(nullptr, nullptr, nullptr, 0, 0);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700742
Ryan Prichard04896452018-08-20 17:44:42 -0700743 tmp_linker_so.base = linker_addr;
744 tmp_linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700745 tmp_linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
Ryan Prichard04896452018-08-20 17:44:42 -0700746 tmp_linker_so.dynamic = nullptr;
747 tmp_linker_so.phdr = phdr;
748 tmp_linker_so.phnum = elf_hdr->e_phnum;
749 tmp_linker_so.set_linker_flag();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700750
Ryan Prichard04896452018-08-20 17:44:42 -0700751 if (!tmp_linker_so.prelink_image()) __linker_cannot_link(args.argv[0]);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800752 if (!tmp_linker_so.link_image(SymbolLookupList(&tmp_linker_so), &tmp_linker_so, nullptr, nullptr)) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700753
Ryan Prichard04896452018-08-20 17:44:42 -0700754 return __linker_init_post_relocation(args, tmp_linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700755}
756
757/*
758 * This code is called after the linker has linked itself and fixed its own
759 * GOT. It is safe to make references to externs and other non-local data at
760 * this point. The compiler sometimes moves GOT references earlier in a
761 * function, so avoid inlining this function (http://b/80503879).
762 */
763static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700764__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& tmp_linker_so) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800765 // Finish initializing the main thread.
Ryan Prichard07440a82018-11-22 03:16:06 -0800766 __libc_init_main_thread_late();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700767
768 // We didn't protect the linker's RELRO pages in link_image because we
769 // couldn't make system calls on x86 at that point, but we can now...
Ryan Prichard04896452018-08-20 17:44:42 -0700770 if (!tmp_linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700771
Vic Yang1bf62b22019-08-13 14:53:28 -0700772 // And we can set VMA name for the bss section now
773 set_bss_vma_name(&tmp_linker_so);
774
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700775 // Initialize the linker's static libc's globals
Ryan Prichard07440a82018-11-22 03:16:06 -0800776 __libc_init_globals();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700777
Ryan Prichard67e8f222023-08-18 16:21:48 -0700778 // A constructor could spawn a thread that calls into the loader, so as soon
779 // as we've called a constructor, we need to hold the lock until transferring
780 // to the entry point.
781 pthread_mutex_lock(&g_dl_mutex);
782
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700783 // Initialize the linker's own global variables
Ryan Prichard04896452018-08-20 17:44:42 -0700784 tmp_linker_so.call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700785
Ryan Prichardbb1e3732021-01-12 23:09:10 -0800786 // Setting the linker soinfo's soname can allocate heap memory, so delay it until here.
787 for (const ElfW(Dyn)* d = tmp_linker_so.dynamic; d->d_tag != DT_NULL; ++d) {
788 if (d->d_tag == DT_SONAME) {
789 tmp_linker_so.set_soname(tmp_linker_so.get_string(d->d_un.d_val));
790 }
791 }
792
Ryan Prichard8f639a42018-10-01 23:10:05 -0700793 // When the linker is run directly rather than acting as PT_INTERP, parse
794 // arguments and determine the executable to load. When it's instead acting
795 // as PT_INTERP, AT_ENTRY will refer to the loaded executable rather than the
796 // linker's _start.
797 const char* exe_to_load = nullptr;
Ryan Prichard07440a82018-11-22 03:16:06 -0800798 if (getauxval(AT_ENTRY) == reinterpret_cast<uintptr_t>(&_start)) {
Elliott Hughes90f96b92019-05-09 15:56:39 -0700799 if (args.argc == 3 && !strcmp(args.argv[1], "--list")) {
800 // We're being asked to behave like ldd(1).
801 g_is_ldd = true;
802 exe_to_load = args.argv[2];
803 } else if (args.argc <= 1 || !strcmp(args.argv[1], "--help")) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700804 async_safe_format_fd(STDOUT_FILENO,
Elliott Hughes90f96b92019-05-09 15:56:39 -0700805 "Usage: %s [--list] PROGRAM [ARGS-FOR-PROGRAM...]\n"
806 " %s [--list] path.zip!/PROGRAM [ARGS-FOR-PROGRAM...]\n"
Ryan Prichard8f639a42018-10-01 23:10:05 -0700807 "\n"
808 "A helper program for linking dynamic executables. Typically, the kernel loads\n"
809 "this program because it's the PT_INTERP of a dynamic executable.\n"
810 "\n"
811 "This program can also be run directly to load and run a dynamic executable. The\n"
812 "executable can be inside a zip file if it's stored uncompressed and at a\n"
Elliott Hughes90f96b92019-05-09 15:56:39 -0700813 "page-aligned offset.\n"
814 "\n"
815 "The --list option gives behavior equivalent to ldd(1) on other systems.\n",
Ryan Prichard8f639a42018-10-01 23:10:05 -0700816 args.argv[0], args.argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700817 _exit(EXIT_SUCCESS);
818 } else {
819 exe_to_load = args.argv[1];
820 __libc_shared_globals()->initial_linker_arg_count = 1;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700821 }
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700822 }
823
Ryan Prichard8f639a42018-10-01 23:10:05 -0700824 // store argc/argv/envp to use them for calling constructors
Ryan Prichardabf736a2018-11-22 02:40:17 -0800825 g_argc = args.argc - __libc_shared_globals()->initial_linker_arg_count;
826 g_argv = args.argv + __libc_shared_globals()->initial_linker_arg_count;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700827 g_envp = args.envp;
Ryan Prichard48b11592018-11-22 02:41:36 -0800828 __libc_shared_globals()->init_progname = g_argv[0];
Ryan Prichard8f639a42018-10-01 23:10:05 -0700829
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700830 // Initialize static variables. Note that in order to
831 // get correct libdl_info we need to call constructors
832 // before get_libdl_info().
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700833 sonext = solist = solinker = get_libdl_info(tmp_linker_so);
Ryan Prichard04896452018-08-20 17:44:42 -0700834 g_default_namespace.add_soinfo(solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700835
Ryan Prichard8f639a42018-10-01 23:10:05 -0700836 ElfW(Addr) start_address = linker_main(args, exe_to_load);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700837
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700838 INFO("[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
839
840 // Return the address that the calling assembly stub should jump to.
841 return start_address;
842}