blob: f65f82d5bf82111ece29458dc467f4e8e896a912 [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
Ryan Prichard8f639a42018-10-01 23:10:05 -070065__LIBC_HIDDEN__ extern "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
Dimitry Ivanov3f660572016-09-09 10:00:39 -070083// These should be preserved static to avoid emitting
84// RELATIVE relocations for the part of the code running
85// before linker links itself.
86
87// TODO (dimtiry): remove somain, rename solist to solist_head
88static soinfo* solist;
89static soinfo* sonext;
Evgenii Stepanov6bbb75a2023-12-06 18:54:45 +000090static soinfo* somain; // main process, always the one after libdl_info
Ryan Prichard04896452018-08-20 17:44:42 -070091static soinfo* solinker;
dimitry8b142562018-05-09 15:22:38 +020092static soinfo* vdso; // vdso if present
Dimitry Ivanov3f660572016-09-09 10:00:39 -070093
94void solist_add_soinfo(soinfo* si) {
95 sonext->next = si;
96 sonext = si;
97}
98
99bool solist_remove_soinfo(soinfo* si) {
100 soinfo *prev = nullptr, *trav;
101 for (trav = solist; trav != nullptr; trav = trav->next) {
102 if (trav == si) {
103 break;
104 }
105 prev = trav;
106 }
107
108 if (trav == nullptr) {
109 // si was not in solist
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400110 DL_WARN("name \"%s\"@%p is not in solist!", si->get_realpath(), si);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700111 return false;
112 }
113
114 // prev will never be null, because the first entry in solist is
115 // always the static libdl_info.
George Burgess IV70591002017-06-27 16:23:45 -0700116 CHECK(prev != nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700117 prev->next = si->next;
118 if (si == sonext) {
119 sonext = prev;
120 }
121
122 return true;
123}
124
125soinfo* solist_get_head() {
126 return solist;
127}
128
129soinfo* solist_get_somain() {
130 return somain;
131}
132
dimitry8b142562018-05-09 15:22:38 +0200133soinfo* solist_get_vdso() {
134 return vdso;
135}
136
Elliott Hughes90f96b92019-05-09 15:56:39 -0700137bool g_is_ldd;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700138
139static std::vector<std::string> g_ld_preload_names;
140
141static std::vector<soinfo*> g_ld_preloads;
142
143static void parse_path(const char* path, const char* delimiters,
144 std::vector<std::string>* resolved_paths) {
145 std::vector<std::string> paths;
146 split_path(path, delimiters, &paths);
147 resolve_paths(paths, resolved_paths);
148}
149
150static void parse_LD_LIBRARY_PATH(const char* path) {
151 std::vector<std::string> ld_libary_paths;
152 parse_path(path, ":", &ld_libary_paths);
153 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
154}
155
156static void parse_LD_PRELOAD(const char* path) {
157 g_ld_preload_names.clear();
158 if (path != nullptr) {
159 // We have historically supported ':' as well as ' ' in LD_PRELOAD.
160 g_ld_preload_names = android::base::Split(path, " :");
Josh Gao44f6e182017-10-18 17:25:24 -0700161 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 -0700162 [](const std::string& s) { return s.empty(); }),
163 g_ld_preload_names.end());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700164 }
165}
166
167// An empty list of soinfos
168static soinfo_list_t g_empty_list;
169
Ryan Prichard07440a82018-11-22 03:16:06 -0800170static void add_vdso() {
171 ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(getauxval(AT_SYSINFO_EHDR));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700172 if (ehdr_vdso == nullptr) {
173 return;
174 }
175
Elliott Hughes54564df2024-07-19 13:59:51 -0400176 vdso = soinfo_alloc(&g_default_namespace, "[vdso]", nullptr, 0, 0);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700177
Elliott Hughes54564df2024-07-19 13:59:51 -0400178 vdso->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
179 vdso->phnum = ehdr_vdso->e_phnum;
180 vdso->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
181 vdso->size = phdr_table_get_load_size(vdso->phdr, vdso->phnum);
182 vdso->load_bias = get_elf_exec_load_bias(ehdr_vdso);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700183
Elliott Hughes54564df2024-07-19 13:59:51 -0400184 if (!vdso->prelink_image() || !vdso->link_image(SymbolLookupList(vdso), vdso, nullptr, nullptr)) {
185 __linker_cannot_link(g_argv[0]);
186 }
dimitry8b142562018-05-09 15:22:38 +0200187
Elliott Hughes54564df2024-07-19 13:59:51 -0400188 // Prevent accidental unloads...
189 vdso->set_dt_flags_1(vdso->get_dt_flags_1() | DF_1_NODELETE);
190 vdso->set_linked();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700191}
192
Ryan Prichard04896452018-08-20 17:44:42 -0700193// Initializes an soinfo's link_map_head field using other fields from the
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700194// soinfo (phdr, phnum, load_bias). The soinfo's realpath must not change after
195// this function is called.
196static void init_link_map_head(soinfo& info) {
Ryan Prichard04896452018-08-20 17:44:42 -0700197 auto& map = info.link_map_head;
198 map.l_addr = info.load_bias;
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700199 map.l_name = const_cast<char*>(info.get_realpath());
Ryan Prichard04896452018-08-20 17:44:42 -0700200 phdr_table_get_dynamic_section(info.phdr, info.phnum, info.load_bias, &map.l_ld, nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700201}
202
203extern "C" int __system_properties_init(void);
204
Ryan Prichard8f639a42018-10-01 23:10:05 -0700205struct ExecutableInfo {
206 std::string path;
207 struct stat file_stat;
208 const ElfW(Phdr)* phdr;
209 size_t phdr_count;
210 ElfW(Addr) entry_point;
Kalesh Singh4084b552024-03-13 13:35:49 -0700211 bool should_pad_segments;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700212};
213
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000214static ExecutableInfo get_executable_info(const char* arg_path) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700215 ExecutableInfo result = {};
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000216 char const* exe_path = "/proc/self/exe";
Ryan Prichard8f639a42018-10-01 23:10:05 -0700217
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000218 // Stat "/proc/self/exe" instead of executable_path because
219 // the executable could be unlinked by this point and it should
220 // not cause a crash (see http://b/31084669)
221 if (TEMP_FAILURE_RETRY(stat(exe_path, &result.file_stat) == -1)) {
222 // Fallback to argv[0] for the case where /proc isn't available
223 if (TEMP_FAILURE_RETRY(stat(arg_path, &result.file_stat) == -1)) {
Elliott Hughesf5e21d92024-07-26 11:48:19 +0000224 async_safe_fatal("unable to stat either \"/proc/self/exe\" or \"%s\": %m", arg_path);
Tom Cherry66bc4282018-11-08 13:40:52 -0800225 }
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000226 exe_path = arg_path;
227 }
228
Elliott Hughes33de2732024-04-25 16:44:48 +0000229 // Path might be a symlink; we need the target so that we get the right
230 // linker configuration later.
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000231 char sym_path[PATH_MAX];
Elliott Hughes33de2732024-04-25 16:44:48 +0000232 result.path = std::string(realpath(exe_path, sym_path) != nullptr ? sym_path : exe_path);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700233
Ryan Prichard07440a82018-11-22 03:16:06 -0800234 result.phdr = reinterpret_cast<const ElfW(Phdr)*>(getauxval(AT_PHDR));
235 result.phdr_count = getauxval(AT_PHNUM);
236 result.entry_point = getauxval(AT_ENTRY);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700237 return result;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700238}
239
Ryan Prichard8f639a42018-10-01 23:10:05 -0700240// Load an executable. Normally the kernel has already loaded the executable when the linker
241// starts. The linker can be invoked directly on an executable, though, and then the linker must
242// load it. This function doesn't load dependencies or resolve relocations.
243static ExecutableInfo load_executable(const char* orig_path) {
244 ExecutableInfo result = {};
245
246 if (orig_path[0] != '/') {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000247 __linker_error("error: expected absolute path: \"%s\"", orig_path);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700248 }
249
250 off64_t file_offset;
251 android::base::unique_fd fd(open_executable(orig_path, &file_offset, &result.path));
252 if (fd.get() == -1) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000253 __linker_error("error: unable to open file \"%s\"", orig_path);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700254 }
255
256 if (TEMP_FAILURE_RETRY(fstat(fd.get(), &result.file_stat)) == -1) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000257 __linker_error("error: unable to stat \"%s\": %m", result.path.c_str());
Ryan Prichard8f639a42018-10-01 23:10:05 -0700258 }
259
260 ElfReader elf_reader;
261 if (!elf_reader.Read(result.path.c_str(), fd.get(), file_offset, result.file_stat.st_size)) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000262 __linker_error("error: %s", linker_get_error_buffer());
Ryan Prichard8f639a42018-10-01 23:10:05 -0700263 }
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400264 address_space_params address_space;
265 if (!elf_reader.Load(&address_space)) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000266 __linker_error("error: %s", linker_get_error_buffer());
Ryan Prichard8f639a42018-10-01 23:10:05 -0700267 }
268
269 result.phdr = elf_reader.loaded_phdr();
270 result.phdr_count = elf_reader.phdr_count();
271 result.entry_point = elf_reader.entry_point();
Kalesh Singh4084b552024-03-13 13:35:49 -0700272 result.should_pad_segments = elf_reader.should_pad_segments();
Ryan Prichard8f639a42018-10-01 23:10:05 -0700273 return result;
274}
275
Tamas Petz8d55d182020-02-24 14:15:25 +0100276static void platform_properties_init() {
277#if defined(__aarch64__)
278 const unsigned long hwcap2 = getauxval(AT_HWCAP2);
279 g_platform_properties.bti_supported = (hwcap2 & HWCAP2_BTI) != 0;
280#endif
281}
282
Ryan Prichard8f639a42018-10-01 23:10:05 -0700283static ElfW(Addr) linker_main(KernelArgumentBlock& args, const char* exe_to_load) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800284 ProtectedDataGuard guard;
285
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400286 timeval t0, t1;
287 gettimeofday(&t0, nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700288
289 // Sanitize the environment.
Ryan Prichard48b11592018-11-22 02:41:36 -0800290 __libc_init_AT_SECURE(args.envp);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700291
292 // Initialize system properties
293 __system_properties_init(); // may use 'environ'
294
Tamas Petz8d55d182020-02-24 14:15:25 +0100295 // Initialize platform properties.
296 platform_properties_init();
297
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700298 // Register the debuggerd signal handler.
Ryan Prichard80e40f02019-10-31 19:54:46 -0700299 linker_debuggerd_init();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700300
301 g_linker_logger.ResetState();
302
Elliott Hughes838dbac2023-08-22 14:07:48 -0700303 // Enable debugging logs?
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700304 const char* LD_DEBUG = getenv("LD_DEBUG");
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400305 if (LD_DEBUG != nullptr) init_LD_DEBUG(LD_DEBUG);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700306
Elliott Hughes838dbac2023-08-22 14:07:48 -0700307 if (getenv("LD_SHOW_AUXV") != nullptr) ld_show_auxv(args.auxv);
308
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400309 LD_DEBUG(any, "[ Android dynamic linker (" ABI_STRING ") ]");
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700310
311 // These should have been sanitized by __libc_init_AT_SECURE, but the test
312 // doesn't cost us anything.
313 const char* ldpath_env = nullptr;
314 const char* ldpreload_env = nullptr;
315 if (!getauxval(AT_SECURE)) {
316 ldpath_env = getenv("LD_LIBRARY_PATH");
317 if (ldpath_env != nullptr) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400318 LD_DEBUG(any, "[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700319 }
320 ldpreload_env = getenv("LD_PRELOAD");
321 if (ldpreload_env != nullptr) {
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400322 LD_DEBUG(any, "[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700323 }
324 }
325
Ryan Prichard8f639a42018-10-01 23:10:05 -0700326 const ExecutableInfo exe_info = exe_to_load ? load_executable(exe_to_load) :
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000327 get_executable_info(args.argv[0]);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700328
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400329 LD_DEBUG(any, "[ Linking executable \"%s\" ]", exe_info.path.c_str());
Martin Stjernholm95252ee2019-02-22 22:48:59 +0000330
Ryan Prichard04896452018-08-20 17:44:42 -0700331 // Initialize the main exe's soinfo.
Ryan Prichard8f639a42018-10-01 23:10:05 -0700332 soinfo* si = soinfo_alloc(&g_default_namespace,
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700333 exe_info.path.c_str(), &exe_info.file_stat,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700334 0, RTLD_GLOBAL);
Ryan Prichard04896452018-08-20 17:44:42 -0700335 somain = si;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700336 si->phdr = exe_info.phdr;
337 si->phnum = exe_info.phdr_count;
Kalesh Singh4084b552024-03-13 13:35:49 -0700338 si->set_should_pad_segments(exe_info.should_pad_segments);
Ryan Prichard04896452018-08-20 17:44:42 -0700339 get_elf_base_from_phdr(si->phdr, si->phnum, &si->base, &si->load_bias);
340 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
341 si->dynamic = nullptr;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700342 si->set_main_executable();
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700343 init_link_map_head(*si);
344
Vic Yang1bf62b22019-08-13 14:53:28 -0700345 set_bss_vma_name(si);
346
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700347 // Use the executable's PT_INTERP string as the solinker filename in the
348 // dynamic linker's module list. gdb reads both PT_INTERP and the module list,
349 // and if the paths for the linker are different, gdb will report that the
350 // PT_INTERP linker path was unloaded once the module list is initialized.
351 // There are three situations to handle:
352 // - the APEX linker (/system/bin/linker[64] -> /apex/.../linker[64])
353 // - the ASAN linker (/system/bin/linker_asan[64] -> /apex/.../linker[64])
354 // - the bootstrap linker (/system/bin/bootstrap/linker[64])
355 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
356 somain->load_bias);
357 if (interp == nullptr) {
358 // This case can happen if the linker attempts to execute itself
359 // (e.g. "linker64 /system/bin/linker64").
Elliott Hughes03eda272024-08-19 17:12:34 +0000360#if defined(__LP64__)
361#define DEFAULT_INTERP "/system/bin/linker64"
362#else
363#define DEFAULT_INTERP "/system/bin/linker"
364#endif
365 interp = DEFAULT_INTERP;
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700366 }
367 solinker->set_realpath(interp);
368 init_link_map_head(*solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700369
Tamas Petz8d55d182020-02-24 14:15:25 +0100370#if defined(__aarch64__)
Florian Mayer4edc20d2024-10-30 14:24:26 -0700371 __libc_init_mte(somain->memtag_dynamic_entries(), somain->phdr, somain->phnum, somain->load_bias);
372
Tamas Petz8d55d182020-02-24 14:15:25 +0100373 if (exe_to_load == nullptr) {
374 // Kernel does not add PROT_BTI to executable pages of the loaded ELF.
375 // Apply appropriate protections here if it is needed.
376 auto note_gnu_property = GnuPropertySection(somain);
377 if (note_gnu_property.IsBTICompatible() &&
Kalesh Singhb23787f2024-09-05 08:22:06 +0000378 (phdr_table_protect_segments(
379 somain->phdr, somain->phnum, somain->load_bias, somain->should_pad_segments(),
380 somain->should_use_16kib_app_compat(), &note_gnu_property) < 0)) {
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000381 __linker_error("error: can't protect segments for \"%s\": %m", exe_info.path.c_str());
Tamas Petz8d55d182020-02-24 14:15:25 +0100382 }
383 }
384#endif
385
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700386 // Register the main executable and the linker upfront to have
387 // gdb aware of them before loading the rest of the dependency
388 // tree.
Ryan Prichard04896452018-08-20 17:44:42 -0700389 //
390 // gdb expects the linker to be in the debug shared object list.
391 // Without this, gdb has trouble locating the linker's ".text"
392 // and ".plt" sections. Gdb could also potentially use this to
393 // relocate the offset of our exported 'rtld_db_dlactivity' symbol.
394 //
395 insert_link_map_into_debug_map(&si->link_map_head);
396 insert_link_map_into_debug_map(&solinker->link_map_head);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700397
Ryan Prichard07440a82018-11-22 03:16:06 -0800398 add_vdso();
Ryan Prichard14dd9922018-08-20 17:43:44 -0700399
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700400 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800401
Elliott Hughes71abb3d2024-05-17 12:16:16 +0000402 // For security reasons we dropped non-PIE support in API level 21,
403 // and the NDK no longer supports earlier API levels.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700404 if (elf_hdr->e_type != ET_DYN) {
Elliott Hughes71abb3d2024-05-17 12:16:16 +0000405 __linker_error("error: %s: Android only supports position-independent "
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000406 "executables (-fPIE)", exe_info.path.c_str());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700407 }
408
409 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
410 parse_LD_LIBRARY_PATH(ldpath_env);
411 parse_LD_PRELOAD(ldpreload_env);
412
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700413 std::vector<android_namespace_t*> namespaces = init_default_namespaces(exe_info.path.c_str());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700414
Elliott Hughesad2d0382017-07-31 11:43:34 -0700415 if (!si->prelink_image()) __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700416
417 // add somain to global group
418 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
Jiyong Park02586a22017-05-20 01:01:24 +0900419 // ... and add it to all other linked namespaces
420 for (auto linked_ns : namespaces) {
421 if (linked_ns != &g_default_namespace) {
422 linked_ns->add_soinfo(somain);
423 somain->add_secondary_namespace(linked_ns);
424 }
425 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700426
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800427 linker_setup_exe_static_tls(g_argv[0]);
428
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700429 // Load ld_preloads and dependencies.
430 std::vector<const char*> needed_library_name_list;
431 size_t ld_preloads_count = 0;
432
433 for (const auto& ld_preload_name : g_ld_preload_names) {
434 needed_library_name_list.push_back(ld_preload_name.c_str());
435 ++ld_preloads_count;
436 }
437
438 for_each_dt_needed(si, [&](const char* name) {
439 needed_library_name_list.push_back(name);
440 });
441
442 const char** needed_library_names = &needed_library_name_list[0];
443 size_t needed_libraries_count = needed_library_name_list.size();
444
445 if (needed_libraries_count > 0 &&
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800446 !find_libraries(&g_default_namespace,
447 si,
448 needed_library_names,
449 needed_libraries_count,
450 nullptr,
451 &g_ld_preloads,
452 ld_preloads_count,
453 RTLD_GLOBAL,
454 nullptr,
455 true /* add_as_children */,
Jiyong Park02586a22017-05-20 01:01:24 +0900456 &namespaces)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700457 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700458 } else if (needed_libraries_count == 0) {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800459 if (!si->link_image(SymbolLookupList(si), si, nullptr, nullptr)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700460 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700461 }
462 si->increment_ref_count();
463 }
Ryan Prichard32bb3672024-03-08 16:53:06 -0800464
465 // Exit early for ldd. We don't want to run the code that was loaded, so skip
466 // the constructor calls. Skip CFI setup because it would call __cfi_init in
467 // libdl.so.
468 if (g_is_ldd) _exit(EXIT_SUCCESS);
469
Florian Mayere65e1932024-02-15 22:20:54 +0000470#if defined(__aarch64__)
471 // This has to happen after the find_libraries, which will have collected any possible
472 // libraries that request memtag_stack in the dynamic section.
Florian Mayerc138f812024-10-29 15:26:13 -0700473 __libc_init_mte_stack(args.argv);
Florian Mayere65e1932024-02-15 22:20:54 +0000474#endif
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700475
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800476 linker_finalize_static_tls();
Ryan Prichard45d13492019-01-03 02:51:30 -0800477 __libc_init_main_thread_final();
478
Elliott Hughesad2d0382017-07-31 11:43:34 -0700479 if (!get_cfi_shadow()->InitialLinkDone(solist)) __linker_cannot_link(g_argv[0]);
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700480
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800481 si->call_pre_init_constructors();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800482 si->call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700483
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400484 if (g_linker_debug_config.timing) {
485 gettimeofday(&t1, nullptr);
486 long long t0_us = (t0.tv_sec * 1000000LL) + t0.tv_usec;
487 long long t1_us = (t1.tv_sec * 1000000LL) + t1.tv_usec;
488 LD_DEBUG(timing, "LINKER TIME: %s: %lld microseconds", g_argv[0], t1_us - t0_us);
489 }
490 if (g_linker_debug_config.statistics) {
491 print_linker_stats();
492 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700493
Vic Yangbb7e1232019-01-29 20:23:16 -0800494 // We are about to hand control over to the executable loaded. We don't want
495 // to leave dirty pages behind unnecessarily.
496 purge_unused_memory();
497
Ryan Prichard8f639a42018-10-01 23:10:05 -0700498 ElfW(Addr) entry = exe_info.entry_point;
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400499 LD_DEBUG(any, "[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700500 return entry;
501}
502
503/* Compute the load-bias of an existing executable. This shall only
504 * be used to compute the load bias of an executable or shared library
505 * that was loaded by the kernel itself.
506 *
507 * Input:
508 * elf -> address of ELF header, assumed to be at the start of the file.
509 * Return:
510 * load bias, i.e. add the value of any p_vaddr in the file to get
511 * the corresponding address in memory.
512 */
513static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
514 ElfW(Addr) offset = elf->e_phoff;
515 const ElfW(Phdr)* phdr_table =
516 reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
517 const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
518
519 for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
520 if (phdr->p_type == PT_LOAD) {
521 return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
522 }
523 }
524 return 0;
525}
526
Ryan Prichard9729f352018-07-13 22:40:26 -0700527/* Find the load bias and base address of an executable or shared object loaded
528 * by the kernel. The ELF file's PHDR table must have a PT_PHDR entry.
529 *
530 * A VDSO doesn't have a PT_PHDR entry in its PHDR table.
531 */
532static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
533 ElfW(Addr)* base, ElfW(Addr)* load_bias) {
534 for (size_t i = 0; i < phdr_count; ++i) {
535 if (phdr_table[i].p_type == PT_PHDR) {
536 *load_bias = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_vaddr;
537 *base = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_offset;
538 return;
539 }
540 }
541 async_safe_fatal("Could not find a PHDR: broken executable?");
542}
543
Vic Yang1bf62b22019-08-13 14:53:28 -0700544/*
545 * Set anonymous VMA name for .bss section. For DSOs loaded by the linker, this
546 * is done by ElfReader. This function is here for DSOs loaded by the kernel,
547 * namely the linker itself and the main executable.
548 */
549static void set_bss_vma_name(soinfo* si) {
550 for (size_t i = 0; i < si->phnum; ++i) {
551 auto phdr = &si->phdr[i];
552
553 if (phdr->p_type != PT_LOAD) {
554 continue;
555 }
556
557 ElfW(Addr) seg_start = phdr->p_vaddr + si->load_bias;
Peter Collingbournebb11ee62022-05-02 12:26:16 -0700558 ElfW(Addr) seg_page_end = page_end(seg_start + phdr->p_memsz);
559 ElfW(Addr) seg_file_end = page_end(seg_start + phdr->p_filesz);
Vic Yang1bf62b22019-08-13 14:53:28 -0700560
561 if (seg_page_end > seg_file_end) {
562 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME,
563 reinterpret_cast<void*>(seg_file_end), seg_page_end - seg_file_end,
564 ".bss");
565 }
566 }
567}
568
Ryan Prichard249757b2019-11-01 17:18:28 -0700569#if defined(USE_RELA)
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700570using RelType = ElfW(Rela);
571const unsigned kRelTag = DT_RELA;
572const unsigned kRelSzTag = DT_RELASZ;
Ryan Prichard249757b2019-11-01 17:18:28 -0700573#else
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700574using RelType = ElfW(Rel);
575const unsigned kRelTag = DT_REL;
576const unsigned kRelSzTag = DT_RELSZ;
577#endif
Ryan Prichard249757b2019-11-01 17:18:28 -0700578
Evgenii Stepanov6bbb75a2023-12-06 18:54:45 +0000579extern __LIBC_HIDDEN__ ElfW(Ehdr) __ehdr_start;
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700580
581static void call_ifunc_resolvers_for_section(RelType* begin, RelType* end) {
582 auto ehdr = reinterpret_cast<ElfW(Addr)>(&__ehdr_start);
583 for (RelType *r = begin; r != end; ++r) {
584 if (ELFW(R_TYPE)(r->r_info) != R_GENERIC_IRELATIVE) {
585 continue;
586 }
587 ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(ehdr + r->r_offset);
588#if defined(USE_RELA)
589 ElfW(Addr) resolver = ehdr + r->r_addend;
590#else
591 ElfW(Addr) resolver = ehdr + *offset;
592#endif
Ryan Prichard249757b2019-11-01 17:18:28 -0700593 *offset = __bionic_call_ifunc_resolver(resolver);
594 }
595}
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700596
Ryan Prichard2a901e62024-04-04 03:05:35 -0700597static void relocate_linker() {
598 // The linker should only have relative relocations (in RELR) and IRELATIVE
599 // relocations. Find the IRELATIVE relocations using the DT_JMPREL and
600 // DT_PLTRELSZ, or DT_RELA/DT_RELASZ (DT_REL/DT_RELSZ on ILP32).
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700601 auto ehdr = reinterpret_cast<ElfW(Addr)>(&__ehdr_start);
602 auto* phdr = reinterpret_cast<ElfW(Phdr)*>(ehdr + __ehdr_start.e_phoff);
603 for (size_t i = 0; i != __ehdr_start.e_phnum; ++i) {
604 if (phdr[i].p_type != PT_DYNAMIC) {
605 continue;
606 }
607 auto *dyn = reinterpret_cast<ElfW(Dyn)*>(ehdr + phdr[i].p_vaddr);
Ryan Prichard2a901e62024-04-04 03:05:35 -0700608 ElfW(Addr) relr = 0, relrsz = 0, pltrel = 0, pltrelsz = 0, rel = 0, relsz = 0;
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700609 for (size_t j = 0, size = phdr[i].p_filesz / sizeof(ElfW(Dyn)); j != size; ++j) {
Ryan Prichard2a901e62024-04-04 03:05:35 -0700610 const auto tag = dyn[j].d_tag;
611 const auto val = dyn[j].d_un.d_ptr;
Elliott Hughesf67f27b2024-03-28 14:54:30 +0000612 // We don't currently handle IRELATIVE relocations in DT_ANDROID_REL[A].
Peter Collingbournec630da52024-03-26 13:24:06 -0700613 // We disabled DT_ANDROID_REL[A] at build time; verify that it was actually disabled.
Ryan Prichard2a901e62024-04-04 03:05:35 -0700614 CHECK(tag != DT_ANDROID_REL && tag != DT_ANDROID_RELA);
615 if (tag == DT_RELR || tag == DT_ANDROID_RELR) {
616 relr = val;
617 } else if (tag == DT_RELRSZ || tag == DT_ANDROID_RELRSZ) {
618 relrsz = val;
619 } else if (tag == DT_JMPREL) {
620 pltrel = val;
621 } else if (tag == DT_PLTRELSZ) {
622 pltrelsz = val;
623 } else if (tag == kRelTag) {
624 rel = val;
625 } else if (tag == kRelSzTag) {
626 relsz = val;
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700627 }
628 }
Ryan Prichard2a901e62024-04-04 03:05:35 -0700629 // Apply RELR relocations first so that the GOT is initialized for ifunc
630 // resolvers.
631 if (relr && relrsz) {
Florian Mayer4edc20d2024-10-30 14:24:26 -0700632 // Nothing has tagged the memtag globals here, so it is pointless either
633 // way to handle them, the tags will be zero anyway.
634 // That is moot though, because the linker does not use memtag_globals
635 // in the first place.
Ryan Prichard2a901e62024-04-04 03:05:35 -0700636 relocate_relr(reinterpret_cast<ElfW(Relr*)>(ehdr + relr),
Florian Mayer4edc20d2024-10-30 14:24:26 -0700637 reinterpret_cast<ElfW(Relr*)>(ehdr + relr + relrsz), ehdr,
638 /*has_memtag_globals=*/ false);
Ryan Prichard2a901e62024-04-04 03:05:35 -0700639 }
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700640 if (pltrel && pltrelsz) {
641 call_ifunc_resolvers_for_section(reinterpret_cast<RelType*>(ehdr + pltrel),
642 reinterpret_cast<RelType*>(ehdr + pltrel + pltrelsz));
643 }
644 if (rel && relsz) {
645 call_ifunc_resolvers_for_section(reinterpret_cast<RelType*>(ehdr + rel),
646 reinterpret_cast<RelType*>(ehdr + rel + relsz));
647 }
648 }
649}
Ryan Prichard249757b2019-11-01 17:18:28 -0700650
Ryan Prichard94a8e852019-11-05 14:19:18 -0800651// Usable before ifunc resolvers have been called. This function is compiled with -ffreestanding.
652static void linker_memclr(void* dst, size_t cnt) {
653 for (size_t i = 0; i < cnt; ++i) {
654 reinterpret_cast<char*>(dst)[i] = '\0';
655 }
656}
657
Florian Mayer4edc20d2024-10-30 14:24:26 -0700658// Remapping MTE globals segments happens before the linker relocates itself, and so can't use
659// memcpy() from string.h. This function is compiled with -ffreestanding.
660void linker_memcpy(void* dst, const void* src, size_t n) {
661 char* dst_bytes = reinterpret_cast<char*>(dst);
662 const char* src_bytes = reinterpret_cast<const char*>(src);
663 for (size_t i = 0; i < n; ++i) {
664 dst_bytes[i] = src_bytes[i];
665 }
666}
667
Ryan Prichard1990ba52019-02-07 21:31:31 -0800668// Detect an attempt to run the linker on itself. e.g.:
669// /system/bin/linker64 /system/bin/linker64
670// Use priority-1 to run this constructor before other constructors.
671__attribute__((constructor(1))) static void detect_self_exec() {
672 // Normally, the linker initializes the auxv global before calling its
673 // constructors. If the linker loads itself, though, the first loader calls
674 // the second loader's constructors before calling __linker_init.
675 if (__libc_shared_globals()->auxv != nullptr) {
676 return;
677 }
678#if defined(__i386__)
679 // We don't have access to the auxv struct from here, so use the int 0x80
680 // fallback.
681 __libc_sysinfo = reinterpret_cast<void*>(__libc_int0x80);
682#endif
Elliott Hughesc863e6e2024-07-17 15:34:38 +0000683 __linker_error("error: linker cannot load itself");
Ryan Prichard1990ba52019-02-07 21:31:31 -0800684}
685
Ryan Prichard742982d2018-05-30 22:32:17 -0700686static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700687__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700688
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700689/*
690 * This is the entry point for the linker, called from begin.S. This
691 * method is responsible for fixing the linker's own relocations, and
692 * then calling __linker_init_post_relocation().
693 *
694 * Because this method is called before the linker has fixed it's own
695 * relocations, any attempt to reference an extern variable, extern
696 * function, or other GOT reference will generate a segfault.
697 */
698extern "C" ElfW(Addr) __linker_init(void* raw_args) {
Ryan Prichard67e8f222023-08-18 16:21:48 -0700699 // Unlock the loader mutex immediately before transferring to the executable's
700 // entry point. This must happen after destructors are called in this function
701 // (e.g. ~soinfo), so declare this variable very early.
702 struct DlMutexUnlocker {
703 ~DlMutexUnlocker() { pthread_mutex_unlock(&g_dl_mutex); }
704 } unlocker;
705
Ryan Prichard9cfca862018-11-22 02:44:09 -0800706 // Initialize TLS early so system calls and errno work.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700707 KernelArgumentBlock args(raw_args);
Ryan Prichard94a8e852019-11-05 14:19:18 -0800708 bionic_tcb temp_tcb __attribute__((uninitialized));
709 linker_memclr(&temp_tcb, sizeof(temp_tcb));
Ryan Prichard45d13492019-01-03 02:51:30 -0800710 __libc_init_main_thread_early(args, &temp_tcb);
Ryan Prichard27475b52018-05-17 17:14:18 -0700711
Ryan Prichard8f639a42018-10-01 23:10:05 -0700712 // When the linker is run by itself (rather than as an interpreter for
713 // another program), AT_BASE is 0.
Ryan Prichard07440a82018-11-22 03:16:06 -0800714 ElfW(Addr) linker_addr = getauxval(AT_BASE);
Ryan Prichard9729f352018-07-13 22:40:26 -0700715 if (linker_addr == 0) {
Ryan Prichard1990ba52019-02-07 21:31:31 -0800716 // The AT_PHDR and AT_PHNUM aux values describe this linker instance, so use
717 // the phdr to find the linker's base address.
Ryan Prichard9729f352018-07-13 22:40:26 -0700718 ElfW(Addr) load_bias;
719 get_elf_base_from_phdr(
Ryan Prichard07440a82018-11-22 03:16:06 -0800720 reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR)), getauxval(AT_PHNUM),
Ryan Prichard9729f352018-07-13 22:40:26 -0700721 &linker_addr, &load_bias);
722 }
George Burgess IV70591002017-06-27 16:23:45 -0700723
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700724 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
725 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
726
Ryan Prichard2a901e62024-04-04 03:05:35 -0700727 // Relocate the linker. This step will initialize the GOT, which is needed for
728 // accessing non-hidden global variables. (On some targets, the stack
729 // protector uses GOT accesses rather than TLS.) Relocating the linker will
730 // also call the linker's ifunc resolvers so that string.h functions can be
731 // used.
732 relocate_linker();
Ryan Prichard249757b2019-11-01 17:18:28 -0700733
Ryan Prichard04896452018-08-20 17:44:42 -0700734 soinfo tmp_linker_so(nullptr, nullptr, nullptr, 0, 0);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700735
Ryan Prichard04896452018-08-20 17:44:42 -0700736 tmp_linker_so.base = linker_addr;
737 tmp_linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700738 tmp_linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
Ryan Prichard04896452018-08-20 17:44:42 -0700739 tmp_linker_so.dynamic = nullptr;
740 tmp_linker_so.phdr = phdr;
741 tmp_linker_so.phnum = elf_hdr->e_phnum;
742 tmp_linker_so.set_linker_flag();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700743
Ryan Prichard04896452018-08-20 17:44:42 -0700744 if (!tmp_linker_so.prelink_image()) __linker_cannot_link(args.argv[0]);
Florian Mayer81d7c822024-10-04 00:40:14 +0000745 // There is special logic in soinfo::relocate to avoid duplicating the
746 // relocations we did in relocate_linker().
Ryan Prichard339ecef2020-01-02 16:36:06 -0800747 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 -0700748
Ryan Prichard04896452018-08-20 17:44:42 -0700749 return __linker_init_post_relocation(args, tmp_linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700750}
751
752/*
753 * This code is called after the linker has linked itself and fixed its own
754 * GOT. It is safe to make references to externs and other non-local data at
755 * this point. The compiler sometimes moves GOT references earlier in a
756 * function, so avoid inlining this function (http://b/80503879).
757 */
758static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700759__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& tmp_linker_so) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800760 // Finish initializing the main thread.
Ryan Prichard07440a82018-11-22 03:16:06 -0800761 __libc_init_main_thread_late();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700762
763 // We didn't protect the linker's RELRO pages in link_image because we
764 // couldn't make system calls on x86 at that point, but we can now...
Ryan Prichard04896452018-08-20 17:44:42 -0700765 if (!tmp_linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700766
Vic Yang1bf62b22019-08-13 14:53:28 -0700767 // And we can set VMA name for the bss section now
768 set_bss_vma_name(&tmp_linker_so);
769
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700770 // Initialize the linker's static libc's globals
Ryan Prichard07440a82018-11-22 03:16:06 -0800771 __libc_init_globals();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700772
Ryan Prichard67e8f222023-08-18 16:21:48 -0700773 // A constructor could spawn a thread that calls into the loader, so as soon
774 // as we've called a constructor, we need to hold the lock until transferring
775 // to the entry point.
776 pthread_mutex_lock(&g_dl_mutex);
777
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700778 // Initialize the linker's own global variables
Ryan Prichard04896452018-08-20 17:44:42 -0700779 tmp_linker_so.call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700780
Ryan Prichardbb1e3732021-01-12 23:09:10 -0800781 // Setting the linker soinfo's soname can allocate heap memory, so delay it until here.
782 for (const ElfW(Dyn)* d = tmp_linker_so.dynamic; d->d_tag != DT_NULL; ++d) {
783 if (d->d_tag == DT_SONAME) {
784 tmp_linker_so.set_soname(tmp_linker_so.get_string(d->d_un.d_val));
785 }
786 }
787
Ryan Prichard8f639a42018-10-01 23:10:05 -0700788 // When the linker is run directly rather than acting as PT_INTERP, parse
789 // arguments and determine the executable to load. When it's instead acting
790 // as PT_INTERP, AT_ENTRY will refer to the loaded executable rather than the
791 // linker's _start.
792 const char* exe_to_load = nullptr;
Ryan Prichard07440a82018-11-22 03:16:06 -0800793 if (getauxval(AT_ENTRY) == reinterpret_cast<uintptr_t>(&_start)) {
Elliott Hughes90f96b92019-05-09 15:56:39 -0700794 if (args.argc == 3 && !strcmp(args.argv[1], "--list")) {
795 // We're being asked to behave like ldd(1).
796 g_is_ldd = true;
797 exe_to_load = args.argv[2];
798 } else if (args.argc <= 1 || !strcmp(args.argv[1], "--help")) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700799 async_safe_format_fd(STDOUT_FILENO,
Elliott Hughes90f96b92019-05-09 15:56:39 -0700800 "Usage: %s [--list] PROGRAM [ARGS-FOR-PROGRAM...]\n"
801 " %s [--list] path.zip!/PROGRAM [ARGS-FOR-PROGRAM...]\n"
Ryan Prichard8f639a42018-10-01 23:10:05 -0700802 "\n"
803 "A helper program for linking dynamic executables. Typically, the kernel loads\n"
804 "this program because it's the PT_INTERP of a dynamic executable.\n"
805 "\n"
806 "This program can also be run directly to load and run a dynamic executable. The\n"
807 "executable can be inside a zip file if it's stored uncompressed and at a\n"
Elliott Hughes90f96b92019-05-09 15:56:39 -0700808 "page-aligned offset.\n"
809 "\n"
810 "The --list option gives behavior equivalent to ldd(1) on other systems.\n",
Ryan Prichard8f639a42018-10-01 23:10:05 -0700811 args.argv[0], args.argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700812 _exit(EXIT_SUCCESS);
813 } else {
814 exe_to_load = args.argv[1];
815 __libc_shared_globals()->initial_linker_arg_count = 1;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700816 }
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700817 }
818
Ryan Prichard8f639a42018-10-01 23:10:05 -0700819 // store argc/argv/envp to use them for calling constructors
Ryan Prichardabf736a2018-11-22 02:40:17 -0800820 g_argc = args.argc - __libc_shared_globals()->initial_linker_arg_count;
821 g_argv = args.argv + __libc_shared_globals()->initial_linker_arg_count;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700822 g_envp = args.envp;
Ryan Prichard48b11592018-11-22 02:41:36 -0800823 __libc_shared_globals()->init_progname = g_argv[0];
Ryan Prichard8f639a42018-10-01 23:10:05 -0700824
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700825 // Initialize static variables. Note that in order to
826 // get correct libdl_info we need to call constructors
827 // before get_libdl_info().
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700828 sonext = solist = solinker = get_libdl_info(tmp_linker_so);
Ryan Prichard04896452018-08-20 17:44:42 -0700829 g_default_namespace.add_soinfo(solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700830
Ryan Prichard8f639a42018-10-01 23:10:05 -0700831 ElfW(Addr) start_address = linker_main(args, exe_to_load);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700832
Elliott Hughesf08d0eb2024-09-03 17:31:29 -0400833 LD_DEBUG(any, "[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700834
835 // Return the address that the calling assembly stub should jump to.
836 return start_address;
837}