blob: c52f02aab2b458c6f151af07f6cae9cb85408727 [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
Florian Mayer4edc20d2024-10-30 14:24:26 -070049#include "platform/bionic/macros.h"
Ryan Prichard9a027c72023-07-21 23:04:50 -070050#include "private/KernelArgumentBlock.h"
Ryan Prichard249757b2019-11-01 17:18:28 -070051#include "private/bionic_call_ifunc_resolver.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070052#include "private/bionic_globals.h"
53#include "private/bionic_tls.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070054
Ryan Prichard8f639a42018-10-01 23:10:05 -070055#include "android-base/unique_fd.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070056#include "android-base/strings.h"
57#include "android-base/stringprintf.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070058
Christopher Ferris7a3681e2017-04-24 17:48:32 -070059#include <async_safe/log.h>
Ryan Prichard701bd0c2018-11-21 16:23:03 -080060#include <bionic/libc_init_common.h>
Ryan Prichard45d13492019-01-03 02:51:30 -080061#include <bionic/pthread_internal.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070062
Dimitry Ivanov3f660572016-09-09 10:00:39 -070063#include <vector>
64
Elliott Hughesecf83ce2025-04-14 08:16:30 -070065extern "C" void _start();
Dimitry Ivanov3f660572016-09-09 10:00:39 -070066
67static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf);
68
Ryan Prichard9729f352018-07-13 22:40:26 -070069static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
70 ElfW(Addr)* base, ElfW(Addr)* load_bias);
71
Vic Yang1bf62b22019-08-13 14:53:28 -070072static void set_bss_vma_name(soinfo* si);
73
Mitch Phillips7c1f3772023-09-28 13:45:59 +020074void __libc_init_mte(const memtag_dynamic_entries_t* memtag_dynamic_entries, const void* phdr_start,
Florian Mayerc138f812024-10-29 15:26:13 -070075 size_t phdr_count, uintptr_t load_bias);
76
77void __libc_init_mte_stack(void* stack_top);
Evgenii Stepanov8564b8d2020-12-15 13:55:32 -080078
Elliott Hughes54564df2024-07-19 13:59:51 -040079static void __linker_cannot_link(const char* argv0) {
80 __linker_error("CANNOT LINK EXECUTABLE \"%s\": %s", argv0, linker_get_error_buffer());
81}
82
Elliott Hughes00a07c72025-04-17 15:27:29 -040083// These all need to be static to avoid emitting
Dimitry Ivanov3f660572016-09-09 10:00:39 -070084// RELATIVE relocations for the part of the code running
85// before linker links itself.
86
Elliott Hughes00a07c72025-04-17 15:27:29 -040087/** The head of the list of all objects (including the executable and the linker itself), used for iteration. */
88static soinfo* solist_head;
89/** The tail of the list of all objects (including the executable and the linker itself), used for insertion. */
90static soinfo* solist_tail;
91
92/** The main executable. */
93static soinfo* somain;
94/** The linker. */
Ryan Prichard04896452018-08-20 17:44:42 -070095static soinfo* solinker;
Elliott Hughes00a07c72025-04-17 15:27:29 -040096/** The vdso (can be null). */
97static soinfo* vdso;
Dimitry Ivanov3f660572016-09-09 10:00:39 -070098
99void solist_add_soinfo(soinfo* si) {
Elliott Hughes00a07c72025-04-17 15:27:29 -0400100 if (solist_tail == nullptr) {
101 solist_head = solist_tail = si;
102 } else {
103 solist_tail->next = si;
104 solist_tail = si;
105 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700106}
107
108bool solist_remove_soinfo(soinfo* si) {
Elliott Hughes00a07c72025-04-17 15:27:29 -0400109 soinfo *prev = nullptr, *it;
110 for (it = solist_get_head(); it != nullptr; it = it->next) {
111 if (it == si) {
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700112 break;
113 }
Elliott Hughes00a07c72025-04-17 15:27:29 -0400114 prev = it;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700115 }
116
Elliott Hughes00a07c72025-04-17 15:27:29 -0400117 if (it == nullptr) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400118 DL_WARN("name \"%s\"@%p is not in solist!", si->get_realpath(), si);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700119 return false;
120 }
121
Elliott Hughes00a07c72025-04-17 15:27:29 -0400122 // prev will never be null, nor the head of the list,
123 // because the main executable and linker are first,
124 // and they can't be removed.
George Burgess IV70591002017-06-27 16:23:45 -0700125 CHECK(prev != nullptr);
Elliott Hughes00a07c72025-04-17 15:27:29 -0400126 CHECK(prev != solist_head);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700127 prev->next = si->next;
Elliott Hughes00a07c72025-04-17 15:27:29 -0400128 if (solist_tail == si) {
129 solist_tail = prev;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700130 }
131
132 return true;
133}
134
135soinfo* solist_get_head() {
Elliott Hughes00a07c72025-04-17 15:27:29 -0400136 return solist_head;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700137}
138
Elliott Hughes00a07c72025-04-17 15:27:29 -0400139soinfo* solist_get_executable() {
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700140 return somain;
141}
142
Elliott Hughes00a07c72025-04-17 15:27:29 -0400143soinfo* solist_get_linker() {
144 return solinker;
145}
146
dimitry8b142562018-05-09 15:22:38 +0200147soinfo* solist_get_vdso() {
148 return vdso;
149}
150
Elliott Hughes90f96b92019-05-09 15:56:39 -0700151bool g_is_ldd;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700152
153static std::vector<std::string> g_ld_preload_names;
154
155static std::vector<soinfo*> g_ld_preloads;
156
157static void parse_path(const char* path, const char* delimiters,
158 std::vector<std::string>* resolved_paths) {
159 std::vector<std::string> paths;
160 split_path(path, delimiters, &paths);
161 resolve_paths(paths, resolved_paths);
162}
163
164static void parse_LD_LIBRARY_PATH(const char* path) {
165 std::vector<std::string> ld_libary_paths;
166 parse_path(path, ":", &ld_libary_paths);
167 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
168}
169
170static void parse_LD_PRELOAD(const char* path) {
171 g_ld_preload_names.clear();
172 if (path != nullptr) {
173 // We have historically supported ':' as well as ' ' in LD_PRELOAD.
174 g_ld_preload_names = android::base::Split(path, " :");
Josh Gao44f6e182017-10-18 17:25:24 -0700175 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 -0700176 [](const std::string& s) { return s.empty(); }),
177 g_ld_preload_names.end());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700178 }
179}
180
181// An empty list of soinfos
182static soinfo_list_t g_empty_list;
183
Ryan Prichard07440a82018-11-22 03:16:06 -0800184static void add_vdso() {
185 ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(getauxval(AT_SYSINFO_EHDR));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700186 if (ehdr_vdso == nullptr) {
187 return;
188 }
189
Elliott Hughes54564df2024-07-19 13:59:51 -0400190 vdso = soinfo_alloc(&g_default_namespace, "[vdso]", nullptr, 0, 0);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700191
Elliott Hughes54564df2024-07-19 13:59:51 -0400192 vdso->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
193 vdso->phnum = ehdr_vdso->e_phnum;
194 vdso->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
195 vdso->size = phdr_table_get_load_size(vdso->phdr, vdso->phnum);
196 vdso->load_bias = get_elf_exec_load_bias(ehdr_vdso);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700197
Elliott Hughes54564df2024-07-19 13:59:51 -0400198 if (!vdso->prelink_image() || !vdso->link_image(SymbolLookupList(vdso), vdso, nullptr, nullptr)) {
199 __linker_cannot_link(g_argv[0]);
200 }
dimitry8b142562018-05-09 15:22:38 +0200201
Elliott Hughes54564df2024-07-19 13:59:51 -0400202 // Prevent accidental unloads...
203 vdso->set_dt_flags_1(vdso->get_dt_flags_1() | DF_1_NODELETE);
204 vdso->set_linked();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700205}
206
Ryan Prichard04896452018-08-20 17:44:42 -0700207// Initializes an soinfo's link_map_head field using other fields from the
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700208// soinfo (phdr, phnum, load_bias). The soinfo's realpath must not change after
209// this function is called.
210static void init_link_map_head(soinfo& info) {
Ryan Prichard04896452018-08-20 17:44:42 -0700211 auto& map = info.link_map_head;
212 map.l_addr = info.load_bias;
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700213 map.l_name = const_cast<char*>(info.get_realpath());
Ryan Prichard04896452018-08-20 17:44:42 -0700214 phdr_table_get_dynamic_section(info.phdr, info.phnum, info.load_bias, &map.l_ld, nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700215}
216
217extern "C" int __system_properties_init(void);
218
Ryan Prichard8f639a42018-10-01 23:10:05 -0700219struct ExecutableInfo {
220 std::string path;
221 struct stat file_stat;
222 const ElfW(Phdr)* phdr;
223 size_t phdr_count;
224 ElfW(Addr) entry_point;
Kalesh Singh4084b552024-03-13 13:35:49 -0700225 bool should_pad_segments;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700226};
227
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000228static ExecutableInfo get_executable_info(const char* arg_path) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700229 ExecutableInfo result = {};
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000230 char const* exe_path = "/proc/self/exe";
Ryan Prichard8f639a42018-10-01 23:10:05 -0700231
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000232 // Stat "/proc/self/exe" instead of executable_path because
233 // the executable could be unlinked by this point and it should
234 // not cause a crash (see http://b/31084669)
235 if (TEMP_FAILURE_RETRY(stat(exe_path, &result.file_stat) == -1)) {
236 // Fallback to argv[0] for the case where /proc isn't available
237 if (TEMP_FAILURE_RETRY(stat(arg_path, &result.file_stat) == -1)) {
Elliott Hughesf5e21d92024-07-26 11:48:19 +0000238 async_safe_fatal("unable to stat either \"/proc/self/exe\" or \"%s\": %m", arg_path);
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
Ryan Prichard8f639a42018-10-01 23:10:05 -0700254// Load an executable. Normally the kernel has already loaded the executable when the linker
255// starts. The linker can be invoked directly on an executable, though, and then the linker must
256// load it. This function doesn't load dependencies or resolve relocations.
257static ExecutableInfo load_executable(const char* orig_path) {
258 ExecutableInfo result = {};
259
260 if (orig_path[0] != '/') {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000261 __linker_error("error: expected absolute path: \"%s\"", orig_path);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700262 }
263
264 off64_t file_offset;
265 android::base::unique_fd fd(open_executable(orig_path, &file_offset, &result.path));
266 if (fd.get() == -1) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000267 __linker_error("error: unable to open file \"%s\"", orig_path);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700268 }
269
270 if (TEMP_FAILURE_RETRY(fstat(fd.get(), &result.file_stat)) == -1) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000271 __linker_error("error: unable to stat \"%s\": %m", result.path.c_str());
Ryan Prichard8f639a42018-10-01 23:10:05 -0700272 }
273
274 ElfReader elf_reader;
275 if (!elf_reader.Read(result.path.c_str(), fd.get(), file_offset, result.file_stat.st_size)) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000276 __linker_error("error: %s", linker_get_error_buffer());
Ryan Prichard8f639a42018-10-01 23:10:05 -0700277 }
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400278 address_space_params address_space;
279 if (!elf_reader.Load(&address_space)) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000280 __linker_error("error: %s", linker_get_error_buffer());
Ryan Prichard8f639a42018-10-01 23:10:05 -0700281 }
282
283 result.phdr = elf_reader.loaded_phdr();
284 result.phdr_count = elf_reader.phdr_count();
285 result.entry_point = elf_reader.entry_point();
Kalesh Singh4084b552024-03-13 13:35:49 -0700286 result.should_pad_segments = elf_reader.should_pad_segments();
Ryan Prichard8f639a42018-10-01 23:10:05 -0700287 return result;
288}
289
Tamas Petz8d55d182020-02-24 14:15:25 +0100290static void platform_properties_init() {
291#if defined(__aarch64__)
292 const unsigned long hwcap2 = getauxval(AT_HWCAP2);
293 g_platform_properties.bti_supported = (hwcap2 & HWCAP2_BTI) != 0;
294#endif
295}
296
Ryan Prichard8f639a42018-10-01 23:10:05 -0700297static ElfW(Addr) linker_main(KernelArgumentBlock& args, const char* exe_to_load) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800298 ProtectedDataGuard guard;
299
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400300 timeval t0, t1;
301 gettimeofday(&t0, nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700302
303 // Sanitize the environment.
Ryan Prichard48b11592018-11-22 02:41:36 -0800304 __libc_init_AT_SECURE(args.envp);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700305
306 // Initialize system properties
307 __system_properties_init(); // may use 'environ'
308
Tamas Petz8d55d182020-02-24 14:15:25 +0100309 // Initialize platform properties.
310 platform_properties_init();
311
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700312 // Register the debuggerd signal handler.
Ryan Prichard80e40f02019-10-31 19:54:46 -0700313 linker_debuggerd_init();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700314
315 g_linker_logger.ResetState();
316
Elliott Hughes838dbac2023-08-22 14:07:48 -0700317 // Enable debugging logs?
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700318 const char* LD_DEBUG = getenv("LD_DEBUG");
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400319 if (LD_DEBUG != nullptr) init_LD_DEBUG(LD_DEBUG);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700320
Elliott Hughes838dbac2023-08-22 14:07:48 -0700321 if (getenv("LD_SHOW_AUXV") != nullptr) ld_show_auxv(args.auxv);
322
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400323 LD_DEBUG(any, "[ Android dynamic linker (" ABI_STRING ") ]");
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700324
325 // These should have been sanitized by __libc_init_AT_SECURE, but the test
326 // doesn't cost us anything.
327 const char* ldpath_env = nullptr;
328 const char* ldpreload_env = nullptr;
329 if (!getauxval(AT_SECURE)) {
330 ldpath_env = getenv("LD_LIBRARY_PATH");
331 if (ldpath_env != nullptr) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400332 LD_DEBUG(any, "[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700333 }
334 ldpreload_env = getenv("LD_PRELOAD");
335 if (ldpreload_env != nullptr) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400336 LD_DEBUG(any, "[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700337 }
338 }
339
Ryan Prichard8f639a42018-10-01 23:10:05 -0700340 const ExecutableInfo exe_info = exe_to_load ? load_executable(exe_to_load) :
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000341 get_executable_info(args.argv[0]);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700342
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400343 LD_DEBUG(any, "[ Linking executable \"%s\" ]", exe_info.path.c_str());
Martin Stjernholm95252ee2019-02-22 22:48:59 +0000344
Ryan Prichard04896452018-08-20 17:44:42 -0700345 // Initialize the main exe's soinfo.
Elliott Hughes00a07c72025-04-17 15:27:29 -0400346 // TODO: lose `si` and go straight to somain for clarity.
Ryan Prichard8f639a42018-10-01 23:10:05 -0700347 soinfo* si = soinfo_alloc(&g_default_namespace,
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700348 exe_info.path.c_str(), &exe_info.file_stat,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700349 0, RTLD_GLOBAL);
Ryan Prichard04896452018-08-20 17:44:42 -0700350 somain = si;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700351 si->phdr = exe_info.phdr;
352 si->phnum = exe_info.phdr_count;
Kalesh Singh4084b552024-03-13 13:35:49 -0700353 si->set_should_pad_segments(exe_info.should_pad_segments);
Ryan Prichard04896452018-08-20 17:44:42 -0700354 get_elf_base_from_phdr(si->phdr, si->phnum, &si->base, &si->load_bias);
355 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
356 si->dynamic = nullptr;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700357 si->set_main_executable();
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700358 init_link_map_head(*si);
Vic Yang1bf62b22019-08-13 14:53:28 -0700359 set_bss_vma_name(si);
360
Elliott Hughes00a07c72025-04-17 15:27:29 -0400361 // Add the linker's soinfo.
362 // We need to do this manually because it's placement-new'ed by get_libdl_info(),
363 // not created by soinfo_alloc() like everything else.
364 // We do it here because we want it to come after the executable in solist.
365 solist_add_soinfo(solinker);
366
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700367 // Use the executable's PT_INTERP string as the solinker filename in the
368 // dynamic linker's module list. gdb reads both PT_INTERP and the module list,
369 // and if the paths for the linker are different, gdb will report that the
370 // PT_INTERP linker path was unloaded once the module list is initialized.
371 // There are three situations to handle:
372 // - the APEX linker (/system/bin/linker[64] -> /apex/.../linker[64])
373 // - the ASAN linker (/system/bin/linker_asan[64] -> /apex/.../linker[64])
374 // - the bootstrap linker (/system/bin/bootstrap/linker[64])
375 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
376 somain->load_bias);
377 if (interp == nullptr) {
378 // This case can happen if the linker attempts to execute itself
379 // (e.g. "linker64 /system/bin/linker64").
Elliott Hughes03eda272024-08-19 17:12:34 +0000380#if defined(__LP64__)
381#define DEFAULT_INTERP "/system/bin/linker64"
382#else
383#define DEFAULT_INTERP "/system/bin/linker"
384#endif
385 interp = DEFAULT_INTERP;
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700386 }
387 solinker->set_realpath(interp);
388 init_link_map_head(*solinker);
Florian Mayer5e136172025-03-07 15:34:05 -0800389 init_sanitizer_mode(interp);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700390
Tamas Petz8d55d182020-02-24 14:15:25 +0100391#if defined(__aarch64__)
Florian Mayer4edc20d2024-10-30 14:24:26 -0700392 __libc_init_mte(somain->memtag_dynamic_entries(), somain->phdr, somain->phnum, somain->load_bias);
393
Tamas Petz8d55d182020-02-24 14:15:25 +0100394 if (exe_to_load == nullptr) {
395 // Kernel does not add PROT_BTI to executable pages of the loaded ELF.
396 // Apply appropriate protections here if it is needed.
397 auto note_gnu_property = GnuPropertySection(somain);
398 if (note_gnu_property.IsBTICompatible() &&
Kalesh Singhb23787f2024-09-05 08:22:06 +0000399 (phdr_table_protect_segments(
400 somain->phdr, somain->phnum, somain->load_bias, somain->should_pad_segments(),
401 somain->should_use_16kib_app_compat(), &note_gnu_property) < 0)) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000402 __linker_error("error: can't protect segments for \"%s\": %m", exe_info.path.c_str());
Tamas Petz8d55d182020-02-24 14:15:25 +0100403 }
404 }
405#endif
406
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700407 // Register the main executable and the linker upfront to have
408 // gdb aware of them before loading the rest of the dependency
409 // tree.
Ryan Prichard04896452018-08-20 17:44:42 -0700410 //
411 // gdb expects the linker to be in the debug shared object list.
412 // Without this, gdb has trouble locating the linker's ".text"
413 // and ".plt" sections. Gdb could also potentially use this to
414 // relocate the offset of our exported 'rtld_db_dlactivity' symbol.
415 //
Elliott Hughes00a07c72025-04-17 15:27:29 -0400416 insert_link_map_into_debug_map(&somain->link_map_head);
Ryan Prichard04896452018-08-20 17:44:42 -0700417 insert_link_map_into_debug_map(&solinker->link_map_head);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700418
Ryan Prichard07440a82018-11-22 03:16:06 -0800419 add_vdso();
Ryan Prichard14dd9922018-08-20 17:43:44 -0700420
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700421 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800422
Elliott Hughes71abb3d2024-05-17 12:16:16 +0000423 // For security reasons we dropped non-PIE support in API level 21,
424 // and the NDK no longer supports earlier API levels.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700425 if (elf_hdr->e_type != ET_DYN) {
Elliott Hughes71abb3d2024-05-17 12:16:16 +0000426 __linker_error("error: %s: Android only supports position-independent "
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000427 "executables (-fPIE)", exe_info.path.c_str());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700428 }
429
430 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
431 parse_LD_LIBRARY_PATH(ldpath_env);
432 parse_LD_PRELOAD(ldpreload_env);
433
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700434 std::vector<android_namespace_t*> namespaces = init_default_namespaces(exe_info.path.c_str());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700435
Elliott Hughesad2d0382017-07-31 11:43:34 -0700436 if (!si->prelink_image()) __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700437
438 // add somain to global group
439 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
Jiyong Park02586a22017-05-20 01:01:24 +0900440 // ... and add it to all other linked namespaces
441 for (auto linked_ns : namespaces) {
442 if (linked_ns != &g_default_namespace) {
443 linked_ns->add_soinfo(somain);
444 somain->add_secondary_namespace(linked_ns);
445 }
446 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700447
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800448 linker_setup_exe_static_tls(g_argv[0]);
449
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700450 // Load ld_preloads and dependencies.
451 std::vector<const char*> needed_library_name_list;
452 size_t ld_preloads_count = 0;
453
454 for (const auto& ld_preload_name : g_ld_preload_names) {
455 needed_library_name_list.push_back(ld_preload_name.c_str());
456 ++ld_preloads_count;
457 }
458
Elliott Hughesd2ca7da2025-01-29 12:41:36 -0800459 for (const ElfW(Dyn)* d = si->dynamic; d->d_tag != DT_NULL; ++d) {
460 if (d->d_tag == DT_NEEDED) {
461 const char* name = fix_dt_needed(si->get_string(d->d_un.d_val), si->get_realpath());
462 needed_library_name_list.push_back(name);
463 }
464 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700465
466 const char** needed_library_names = &needed_library_name_list[0];
467 size_t needed_libraries_count = needed_library_name_list.size();
468
469 if (needed_libraries_count > 0 &&
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800470 !find_libraries(&g_default_namespace,
471 si,
472 needed_library_names,
473 needed_libraries_count,
474 nullptr,
475 &g_ld_preloads,
476 ld_preloads_count,
477 RTLD_GLOBAL,
478 nullptr,
479 true /* add_as_children */,
Jiyong Park02586a22017-05-20 01:01:24 +0900480 &namespaces)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700481 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700482 } else if (needed_libraries_count == 0) {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800483 if (!si->link_image(SymbolLookupList(si), si, nullptr, nullptr)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700484 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700485 }
486 si->increment_ref_count();
487 }
Ryan Prichard32bb3672024-03-08 16:53:06 -0800488
489 // Exit early for ldd. We don't want to run the code that was loaded, so skip
490 // the constructor calls. Skip CFI setup because it would call __cfi_init in
491 // libdl.so.
492 if (g_is_ldd) _exit(EXIT_SUCCESS);
493
Florian Mayere65e1932024-02-15 22:20:54 +0000494#if defined(__aarch64__)
495 // This has to happen after the find_libraries, which will have collected any possible
496 // libraries that request memtag_stack in the dynamic section.
Florian Mayerc138f812024-10-29 15:26:13 -0700497 __libc_init_mte_stack(args.argv);
Florian Mayere65e1932024-02-15 22:20:54 +0000498#endif
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700499
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800500 linker_finalize_static_tls();
Ryan Prichard45d13492019-01-03 02:51:30 -0800501 __libc_init_main_thread_final();
502
Elliott Hughes00a07c72025-04-17 15:27:29 -0400503 if (!get_cfi_shadow()->InitialLinkDone(solist_get_head())) __linker_cannot_link(g_argv[0]);
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700504
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800505 si->call_pre_init_constructors();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800506 si->call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700507
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400508 if (g_linker_debug_config.timing) {
509 gettimeofday(&t1, nullptr);
510 long long t0_us = (t0.tv_sec * 1000000LL) + t0.tv_usec;
511 long long t1_us = (t1.tv_sec * 1000000LL) + t1.tv_usec;
512 LD_DEBUG(timing, "LINKER TIME: %s: %lld microseconds", g_argv[0], t1_us - t0_us);
513 }
514 if (g_linker_debug_config.statistics) {
515 print_linker_stats();
516 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700517
Vic Yangbb7e1232019-01-29 20:23:16 -0800518 // We are about to hand control over to the executable loaded. We don't want
519 // to leave dirty pages behind unnecessarily.
520 purge_unused_memory();
521
Ryan Prichard8f639a42018-10-01 23:10:05 -0700522 ElfW(Addr) entry = exe_info.entry_point;
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400523 LD_DEBUG(any, "[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700524 return entry;
525}
526
527/* Compute the load-bias of an existing executable. This shall only
528 * be used to compute the load bias of an executable or shared library
529 * that was loaded by the kernel itself.
530 *
531 * Input:
532 * elf -> address of ELF header, assumed to be at the start of the file.
533 * Return:
534 * load bias, i.e. add the value of any p_vaddr in the file to get
535 * the corresponding address in memory.
536 */
537static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
538 ElfW(Addr) offset = elf->e_phoff;
539 const ElfW(Phdr)* phdr_table =
540 reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
541 const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
542
543 for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
544 if (phdr->p_type == PT_LOAD) {
545 return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
546 }
547 }
548 return 0;
549}
550
Ryan Prichard9729f352018-07-13 22:40:26 -0700551/* Find the load bias and base address of an executable or shared object loaded
552 * by the kernel. The ELF file's PHDR table must have a PT_PHDR entry.
553 *
554 * A VDSO doesn't have a PT_PHDR entry in its PHDR table.
555 */
556static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
557 ElfW(Addr)* base, ElfW(Addr)* load_bias) {
558 for (size_t i = 0; i < phdr_count; ++i) {
559 if (phdr_table[i].p_type == PT_PHDR) {
560 *load_bias = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_vaddr;
561 *base = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_offset;
562 return;
563 }
564 }
565 async_safe_fatal("Could not find a PHDR: broken executable?");
566}
567
Vic Yang1bf62b22019-08-13 14:53:28 -0700568/*
569 * Set anonymous VMA name for .bss section. For DSOs loaded by the linker, this
570 * is done by ElfReader. This function is here for DSOs loaded by the kernel,
571 * namely the linker itself and the main executable.
572 */
573static void set_bss_vma_name(soinfo* si) {
574 for (size_t i = 0; i < si->phnum; ++i) {
575 auto phdr = &si->phdr[i];
576
577 if (phdr->p_type != PT_LOAD) {
578 continue;
579 }
580
581 ElfW(Addr) seg_start = phdr->p_vaddr + si->load_bias;
Peter Collingbournebb11ee62022-05-02 12:26:16 -0700582 ElfW(Addr) seg_page_end = page_end(seg_start + phdr->p_memsz);
583 ElfW(Addr) seg_file_end = page_end(seg_start + phdr->p_filesz);
Vic Yang1bf62b22019-08-13 14:53:28 -0700584
585 if (seg_page_end > seg_file_end) {
586 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME,
587 reinterpret_cast<void*>(seg_file_end), seg_page_end - seg_file_end,
588 ".bss");
589 }
590 }
591}
592
Ryan Prichard249757b2019-11-01 17:18:28 -0700593#if defined(USE_RELA)
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700594using RelType = ElfW(Rela);
595const unsigned kRelTag = DT_RELA;
596const unsigned kRelSzTag = DT_RELASZ;
Ryan Prichard249757b2019-11-01 17:18:28 -0700597#else
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700598using RelType = ElfW(Rel);
599const unsigned kRelTag = DT_REL;
600const unsigned kRelSzTag = DT_RELSZ;
601#endif
Ryan Prichard249757b2019-11-01 17:18:28 -0700602
Elliott Hughes23839192025-04-15 10:37:48 -0700603// Magic linker-provided pointer to the ELF header.
604// Hidden so it's accessible before linker relocations have been processed.
605extern "C" const ElfW(Ehdr) __ehdr_start __attribute__((__visibility__("hidden")));
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700606
607static void call_ifunc_resolvers_for_section(RelType* begin, RelType* end) {
608 auto ehdr = reinterpret_cast<ElfW(Addr)>(&__ehdr_start);
609 for (RelType *r = begin; r != end; ++r) {
610 if (ELFW(R_TYPE)(r->r_info) != R_GENERIC_IRELATIVE) {
611 continue;
612 }
613 ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(ehdr + r->r_offset);
614#if defined(USE_RELA)
615 ElfW(Addr) resolver = ehdr + r->r_addend;
616#else
617 ElfW(Addr) resolver = ehdr + *offset;
618#endif
Ryan Prichard249757b2019-11-01 17:18:28 -0700619 *offset = __bionic_call_ifunc_resolver(resolver);
620 }
621}
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700622
Ryan Prichard2a901e62024-04-04 03:05:35 -0700623static void relocate_linker() {
624 // The linker should only have relative relocations (in RELR) and IRELATIVE
625 // relocations. Find the IRELATIVE relocations using the DT_JMPREL and
626 // DT_PLTRELSZ, or DT_RELA/DT_RELASZ (DT_REL/DT_RELSZ on ILP32).
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700627 auto ehdr = reinterpret_cast<ElfW(Addr)>(&__ehdr_start);
628 auto* phdr = reinterpret_cast<ElfW(Phdr)*>(ehdr + __ehdr_start.e_phoff);
629 for (size_t i = 0; i != __ehdr_start.e_phnum; ++i) {
630 if (phdr[i].p_type != PT_DYNAMIC) {
631 continue;
632 }
633 auto *dyn = reinterpret_cast<ElfW(Dyn)*>(ehdr + phdr[i].p_vaddr);
Ryan Prichard2a901e62024-04-04 03:05:35 -0700634 ElfW(Addr) relr = 0, relrsz = 0, pltrel = 0, pltrelsz = 0, rel = 0, relsz = 0;
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700635 for (size_t j = 0, size = phdr[i].p_filesz / sizeof(ElfW(Dyn)); j != size; ++j) {
Ryan Prichard2a901e62024-04-04 03:05:35 -0700636 const auto tag = dyn[j].d_tag;
637 const auto val = dyn[j].d_un.d_ptr;
Elliott Hughesf67f27b2024-03-28 14:54:30 +0000638 // We don't currently handle IRELATIVE relocations in DT_ANDROID_REL[A].
Peter Collingbournec630da52024-03-26 13:24:06 -0700639 // We disabled DT_ANDROID_REL[A] at build time; verify that it was actually disabled.
Ryan Prichard2a901e62024-04-04 03:05:35 -0700640 CHECK(tag != DT_ANDROID_REL && tag != DT_ANDROID_RELA);
641 if (tag == DT_RELR || tag == DT_ANDROID_RELR) {
642 relr = val;
643 } else if (tag == DT_RELRSZ || tag == DT_ANDROID_RELRSZ) {
644 relrsz = val;
645 } else if (tag == DT_JMPREL) {
646 pltrel = val;
647 } else if (tag == DT_PLTRELSZ) {
648 pltrelsz = val;
649 } else if (tag == kRelTag) {
650 rel = val;
651 } else if (tag == kRelSzTag) {
652 relsz = val;
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700653 }
654 }
Ryan Prichard2a901e62024-04-04 03:05:35 -0700655 // Apply RELR relocations first so that the GOT is initialized for ifunc
656 // resolvers.
657 if (relr && relrsz) {
Florian Mayer4edc20d2024-10-30 14:24:26 -0700658 // Nothing has tagged the memtag globals here, so it is pointless either
659 // way to handle them, the tags will be zero anyway.
660 // That is moot though, because the linker does not use memtag_globals
661 // in the first place.
Ryan Prichard2a901e62024-04-04 03:05:35 -0700662 relocate_relr(reinterpret_cast<ElfW(Relr*)>(ehdr + relr),
Florian Mayer4edc20d2024-10-30 14:24:26 -0700663 reinterpret_cast<ElfW(Relr*)>(ehdr + relr + relrsz), ehdr,
664 /*has_memtag_globals=*/ false);
Ryan Prichard2a901e62024-04-04 03:05:35 -0700665 }
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700666 if (pltrel && pltrelsz) {
667 call_ifunc_resolvers_for_section(reinterpret_cast<RelType*>(ehdr + pltrel),
668 reinterpret_cast<RelType*>(ehdr + pltrel + pltrelsz));
669 }
670 if (rel && relsz) {
671 call_ifunc_resolvers_for_section(reinterpret_cast<RelType*>(ehdr + rel),
672 reinterpret_cast<RelType*>(ehdr + rel + relsz));
673 }
674 }
675}
Ryan Prichard249757b2019-11-01 17:18:28 -0700676
Ryan Prichard94a8e852019-11-05 14:19:18 -0800677// Usable before ifunc resolvers have been called. This function is compiled with -ffreestanding.
678static void linker_memclr(void* dst, size_t cnt) {
679 for (size_t i = 0; i < cnt; ++i) {
680 reinterpret_cast<char*>(dst)[i] = '\0';
681 }
682}
683
Florian Mayer4edc20d2024-10-30 14:24:26 -0700684// Remapping MTE globals segments happens before the linker relocates itself, and so can't use
685// memcpy() from string.h. This function is compiled with -ffreestanding.
686void linker_memcpy(void* dst, const void* src, size_t n) {
687 char* dst_bytes = reinterpret_cast<char*>(dst);
688 const char* src_bytes = reinterpret_cast<const char*>(src);
689 for (size_t i = 0; i < n; ++i) {
690 dst_bytes[i] = src_bytes[i];
691 }
692}
693
Ryan Prichard1990ba52019-02-07 21:31:31 -0800694// Detect an attempt to run the linker on itself. e.g.:
695// /system/bin/linker64 /system/bin/linker64
696// Use priority-1 to run this constructor before other constructors.
697__attribute__((constructor(1))) static void detect_self_exec() {
698 // Normally, the linker initializes the auxv global before calling its
699 // constructors. If the linker loads itself, though, the first loader calls
700 // the second loader's constructors before calling __linker_init.
701 if (__libc_shared_globals()->auxv != nullptr) {
702 return;
703 }
704#if defined(__i386__)
705 // We don't have access to the auxv struct from here, so use the int 0x80
706 // fallback.
707 __libc_sysinfo = reinterpret_cast<void*>(__libc_int0x80);
708#endif
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000709 __linker_error("error: linker cannot load itself");
Ryan Prichard1990ba52019-02-07 21:31:31 -0800710}
711
Ryan Prichard742982d2018-05-30 22:32:17 -0700712static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700713__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700714
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700715/*
716 * This is the entry point for the linker, called from begin.S. This
717 * method is responsible for fixing the linker's own relocations, and
718 * then calling __linker_init_post_relocation().
719 *
720 * Because this method is called before the linker has fixed it's own
721 * relocations, any attempt to reference an extern variable, extern
722 * function, or other GOT reference will generate a segfault.
723 */
724extern "C" ElfW(Addr) __linker_init(void* raw_args) {
Ryan Prichard67e8f222023-08-18 16:21:48 -0700725 // Unlock the loader mutex immediately before transferring to the executable's
726 // entry point. This must happen after destructors are called in this function
727 // (e.g. ~soinfo), so declare this variable very early.
728 struct DlMutexUnlocker {
729 ~DlMutexUnlocker() { pthread_mutex_unlock(&g_dl_mutex); }
730 } unlocker;
731
Ryan Prichard9cfca862018-11-22 02:44:09 -0800732 // Initialize TLS early so system calls and errno work.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700733 KernelArgumentBlock args(raw_args);
Ryan Prichard94a8e852019-11-05 14:19:18 -0800734 bionic_tcb temp_tcb __attribute__((uninitialized));
735 linker_memclr(&temp_tcb, sizeof(temp_tcb));
Ryan Prichard45d13492019-01-03 02:51:30 -0800736 __libc_init_main_thread_early(args, &temp_tcb);
Ryan Prichard27475b52018-05-17 17:14:18 -0700737
Ryan Prichard8f639a42018-10-01 23:10:05 -0700738 // When the linker is run by itself (rather than as an interpreter for
739 // another program), AT_BASE is 0.
Ryan Prichard07440a82018-11-22 03:16:06 -0800740 ElfW(Addr) linker_addr = getauxval(AT_BASE);
Ryan Prichard9729f352018-07-13 22:40:26 -0700741 if (linker_addr == 0) {
Ryan Prichard1990ba52019-02-07 21:31:31 -0800742 // The AT_PHDR and AT_PHNUM aux values describe this linker instance, so use
743 // the phdr to find the linker's base address.
Ryan Prichard9729f352018-07-13 22:40:26 -0700744 ElfW(Addr) load_bias;
745 get_elf_base_from_phdr(
Ryan Prichard07440a82018-11-22 03:16:06 -0800746 reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR)), getauxval(AT_PHNUM),
Ryan Prichard9729f352018-07-13 22:40:26 -0700747 &linker_addr, &load_bias);
748 }
George Burgess IV70591002017-06-27 16:23:45 -0700749
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700750 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
751 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
752
Ryan Prichard2a901e62024-04-04 03:05:35 -0700753 // Relocate the linker. This step will initialize the GOT, which is needed for
754 // accessing non-hidden global variables. (On some targets, the stack
755 // protector uses GOT accesses rather than TLS.) Relocating the linker will
756 // also call the linker's ifunc resolvers so that string.h functions can be
757 // used.
758 relocate_linker();
Ryan Prichard249757b2019-11-01 17:18:28 -0700759
Ryan Prichard04896452018-08-20 17:44:42 -0700760 soinfo tmp_linker_so(nullptr, nullptr, nullptr, 0, 0);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700761
Ryan Prichard04896452018-08-20 17:44:42 -0700762 tmp_linker_so.base = linker_addr;
763 tmp_linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700764 tmp_linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
Ryan Prichard04896452018-08-20 17:44:42 -0700765 tmp_linker_so.dynamic = nullptr;
766 tmp_linker_so.phdr = phdr;
767 tmp_linker_so.phnum = elf_hdr->e_phnum;
768 tmp_linker_so.set_linker_flag();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700769
Ryan Prichard04896452018-08-20 17:44:42 -0700770 if (!tmp_linker_so.prelink_image()) __linker_cannot_link(args.argv[0]);
Florian Mayer81d7c822024-10-04 00:40:14 +0000771 // There is special logic in soinfo::relocate to avoid duplicating the
772 // relocations we did in relocate_linker().
Ryan Prichard339ecef2020-01-02 16:36:06 -0800773 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 -0700774
Ryan Prichard04896452018-08-20 17:44:42 -0700775 return __linker_init_post_relocation(args, tmp_linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700776}
777
778/*
779 * This code is called after the linker has linked itself and fixed its own
780 * GOT. It is safe to make references to externs and other non-local data at
781 * this point. The compiler sometimes moves GOT references earlier in a
782 * function, so avoid inlining this function (http://b/80503879).
783 */
784static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700785__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& tmp_linker_so) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800786 // Finish initializing the main thread.
Ryan Prichard07440a82018-11-22 03:16:06 -0800787 __libc_init_main_thread_late();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700788
789 // We didn't protect the linker's RELRO pages in link_image because we
790 // couldn't make system calls on x86 at that point, but we can now...
Ryan Prichard04896452018-08-20 17:44:42 -0700791 if (!tmp_linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700792
Vic Yang1bf62b22019-08-13 14:53:28 -0700793 // And we can set VMA name for the bss section now
794 set_bss_vma_name(&tmp_linker_so);
795
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700796 // Initialize the linker's static libc's globals
Ryan Prichard07440a82018-11-22 03:16:06 -0800797 __libc_init_globals();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700798
Ryan Prichard67e8f222023-08-18 16:21:48 -0700799 // A constructor could spawn a thread that calls into the loader, so as soon
800 // as we've called a constructor, we need to hold the lock until transferring
801 // to the entry point.
802 pthread_mutex_lock(&g_dl_mutex);
803
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700804 // Initialize the linker's own global variables
Ryan Prichard04896452018-08-20 17:44:42 -0700805 tmp_linker_so.call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700806
Ryan Prichardbb1e3732021-01-12 23:09:10 -0800807 // Setting the linker soinfo's soname can allocate heap memory, so delay it until here.
808 for (const ElfW(Dyn)* d = tmp_linker_so.dynamic; d->d_tag != DT_NULL; ++d) {
809 if (d->d_tag == DT_SONAME) {
810 tmp_linker_so.set_soname(tmp_linker_so.get_string(d->d_un.d_val));
811 }
812 }
813
Ryan Prichard8f639a42018-10-01 23:10:05 -0700814 // When the linker is run directly rather than acting as PT_INTERP, parse
815 // arguments and determine the executable to load. When it's instead acting
816 // as PT_INTERP, AT_ENTRY will refer to the loaded executable rather than the
817 // linker's _start.
818 const char* exe_to_load = nullptr;
Ryan Prichard07440a82018-11-22 03:16:06 -0800819 if (getauxval(AT_ENTRY) == reinterpret_cast<uintptr_t>(&_start)) {
Elliott Hughes90f96b92019-05-09 15:56:39 -0700820 if (args.argc == 3 && !strcmp(args.argv[1], "--list")) {
821 // We're being asked to behave like ldd(1).
822 g_is_ldd = true;
823 exe_to_load = args.argv[2];
824 } else if (args.argc <= 1 || !strcmp(args.argv[1], "--help")) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700825 async_safe_format_fd(STDOUT_FILENO,
Elliott Hughes90f96b92019-05-09 15:56:39 -0700826 "Usage: %s [--list] PROGRAM [ARGS-FOR-PROGRAM...]\n"
827 " %s [--list] path.zip!/PROGRAM [ARGS-FOR-PROGRAM...]\n"
Ryan Prichard8f639a42018-10-01 23:10:05 -0700828 "\n"
829 "A helper program for linking dynamic executables. Typically, the kernel loads\n"
830 "this program because it's the PT_INTERP of a dynamic executable.\n"
831 "\n"
832 "This program can also be run directly to load and run a dynamic executable. The\n"
833 "executable can be inside a zip file if it's stored uncompressed and at a\n"
Elliott Hughes90f96b92019-05-09 15:56:39 -0700834 "page-aligned offset.\n"
835 "\n"
836 "The --list option gives behavior equivalent to ldd(1) on other systems.\n",
Ryan Prichard8f639a42018-10-01 23:10:05 -0700837 args.argv[0], args.argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700838 _exit(EXIT_SUCCESS);
839 } else {
840 exe_to_load = args.argv[1];
841 __libc_shared_globals()->initial_linker_arg_count = 1;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700842 }
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700843 }
844
Elliott Hughes00a07c72025-04-17 15:27:29 -0400845 // Store argc/argv/envp to use them for calling constructors.
Ryan Prichardabf736a2018-11-22 02:40:17 -0800846 g_argc = args.argc - __libc_shared_globals()->initial_linker_arg_count;
847 g_argv = args.argv + __libc_shared_globals()->initial_linker_arg_count;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700848 g_envp = args.envp;
Ryan Prichard48b11592018-11-22 02:41:36 -0800849 __libc_shared_globals()->init_progname = g_argv[0];
Ryan Prichard8f639a42018-10-01 23:10:05 -0700850
Elliott Hughes00a07c72025-04-17 15:27:29 -0400851 solinker = get_libdl_info(tmp_linker_so);
Ryan Prichard04896452018-08-20 17:44:42 -0700852 g_default_namespace.add_soinfo(solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700853
Ryan Prichard8f639a42018-10-01 23:10:05 -0700854 ElfW(Addr) start_address = linker_main(args, exe_to_load);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700855
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700856 // Return the address that the calling assembly stub should jump to.
Elliott Hughes00a07c72025-04-17 15:27:29 -0400857 LD_DEBUG(any, "[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700858 return start_address;
859}