blob: c1a89293e944f1b28fad82485ce2504e52ad4bfe [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>
32#include <sys/auxv.h>
33
Collin Fijalkovich47d27aa2021-03-24 10:17:39 -070034#include "linker.h"
Elliott Hughes838dbac2023-08-22 14:07:48 -070035#include "linker_auxv.h"
Collin Fijalkovich47d27aa2021-03-24 10:17:39 -070036#include "linker_cfi.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070037#include "linker_debug.h"
Ryan Prichard80e40f02019-10-31 19:54:46 -070038#include "linker_debuggerd.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070039#include "linker_gdb_support.h"
40#include "linker_globals.h"
41#include "linker_phdr.h"
Ryan Prichard339ecef2020-01-02 16:36:06 -080042#include "linker_relocate.h"
Peter Collingbourne1583cd22021-08-18 17:04:23 -070043#include "linker_relocs.h"
Ryan Prichard45d13492019-01-03 02:51:30 -080044#include "linker_tls.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070045#include "linker_utils.h"
46
Mitch Phillipse8139f52022-11-23 15:18:01 -080047#include "platform/bionic/macros.h"
Ryan Prichard9a027c72023-07-21 23:04:50 -070048#include "private/KernelArgumentBlock.h"
Mitch Phillipse8139f52022-11-23 15:18:01 -080049#include "private/bionic_auxv.h"
Ryan Prichard249757b2019-11-01 17:18:28 -070050#include "private/bionic_call_ifunc_resolver.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070051#include "private/bionic_globals.h"
52#include "private/bionic_tls.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070053
Ryan Prichard8f639a42018-10-01 23:10:05 -070054#include "android-base/unique_fd.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070055#include "android-base/strings.h"
56#include "android-base/stringprintf.h"
Dimitry Ivanov3f660572016-09-09 10:00:39 -070057
Christopher Ferris7a3681e2017-04-24 17:48:32 -070058#include <async_safe/log.h>
Ryan Prichard701bd0c2018-11-21 16:23:03 -080059#include <bionic/libc_init_common.h>
Ryan Prichard45d13492019-01-03 02:51:30 -080060#include <bionic/pthread_internal.h>
Christopher Ferris7a3681e2017-04-24 17:48:32 -070061
Dimitry Ivanov3f660572016-09-09 10:00:39 -070062#include <vector>
63
Ryan Prichard8f639a42018-10-01 23:10:05 -070064__LIBC_HIDDEN__ extern "C" void _start();
Dimitry Ivanov3f660572016-09-09 10:00:39 -070065
66static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf);
67
Ryan Prichard9729f352018-07-13 22:40:26 -070068static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
69 ElfW(Addr)* base, ElfW(Addr)* load_bias);
70
Vic Yang1bf62b22019-08-13 14:53:28 -070071static void set_bss_vma_name(soinfo* si);
72
Mitch Phillips7c1f3772023-09-28 13:45:59 +020073void __libc_init_mte(const memtag_dynamic_entries_t* memtag_dynamic_entries, const void* phdr_start,
74 size_t phdr_count, uintptr_t load_bias, void* stack_top);
Evgenii Stepanov8564b8d2020-12-15 13:55:32 -080075
Dimitry Ivanov3f660572016-09-09 10:00:39 -070076// These should be preserved static to avoid emitting
77// RELATIVE relocations for the part of the code running
78// before linker links itself.
79
80// TODO (dimtiry): remove somain, rename solist to solist_head
81static soinfo* solist;
82static soinfo* sonext;
Mitch Phillipse8139f52022-11-23 15:18:01 -080083// main process, always the one after libdl_info
84BIONIC_USED_BEFORE_LINKER_RELOCATES static soinfo* somain;
Ryan Prichard04896452018-08-20 17:44:42 -070085static soinfo* solinker;
dimitry8b142562018-05-09 15:22:38 +020086static soinfo* vdso; // vdso if present
Dimitry Ivanov3f660572016-09-09 10:00:39 -070087
88void solist_add_soinfo(soinfo* si) {
89 sonext->next = si;
90 sonext = si;
91}
92
93bool solist_remove_soinfo(soinfo* si) {
94 soinfo *prev = nullptr, *trav;
95 for (trav = solist; trav != nullptr; trav = trav->next) {
96 if (trav == si) {
97 break;
98 }
99 prev = trav;
100 }
101
102 if (trav == nullptr) {
103 // si was not in solist
104 PRINT("name \"%s\"@%p is not in solist!", si->get_realpath(), si);
105 return false;
106 }
107
108 // prev will never be null, because the first entry in solist is
109 // always the static libdl_info.
George Burgess IV70591002017-06-27 16:23:45 -0700110 CHECK(prev != nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700111 prev->next = si->next;
112 if (si == sonext) {
113 sonext = prev;
114 }
115
116 return true;
117}
118
119soinfo* solist_get_head() {
120 return solist;
121}
122
123soinfo* solist_get_somain() {
124 return somain;
125}
126
dimitry8b142562018-05-09 15:22:38 +0200127soinfo* solist_get_vdso() {
128 return vdso;
129}
130
Elliott Hughes90f96b92019-05-09 15:56:39 -0700131bool g_is_ldd;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700132int g_ld_debug_verbosity;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700133
134static std::vector<std::string> g_ld_preload_names;
135
136static std::vector<soinfo*> g_ld_preloads;
137
138static void parse_path(const char* path, const char* delimiters,
139 std::vector<std::string>* resolved_paths) {
140 std::vector<std::string> paths;
141 split_path(path, delimiters, &paths);
142 resolve_paths(paths, resolved_paths);
143}
144
145static void parse_LD_LIBRARY_PATH(const char* path) {
146 std::vector<std::string> ld_libary_paths;
147 parse_path(path, ":", &ld_libary_paths);
148 g_default_namespace.set_ld_library_paths(std::move(ld_libary_paths));
149}
150
151static void parse_LD_PRELOAD(const char* path) {
152 g_ld_preload_names.clear();
153 if (path != nullptr) {
154 // We have historically supported ':' as well as ' ' in LD_PRELOAD.
155 g_ld_preload_names = android::base::Split(path, " :");
Josh Gao44f6e182017-10-18 17:25:24 -0700156 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 -0700157 [](const std::string& s) { return s.empty(); }),
158 g_ld_preload_names.end());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700159 }
160}
161
162// An empty list of soinfos
163static soinfo_list_t g_empty_list;
164
Ryan Prichard07440a82018-11-22 03:16:06 -0800165static void add_vdso() {
166 ElfW(Ehdr)* ehdr_vdso = reinterpret_cast<ElfW(Ehdr)*>(getauxval(AT_SYSINFO_EHDR));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700167 if (ehdr_vdso == nullptr) {
168 return;
169 }
170
171 soinfo* si = soinfo_alloc(&g_default_namespace, "[vdso]", nullptr, 0, 0);
172
173 si->phdr = reinterpret_cast<ElfW(Phdr)*>(reinterpret_cast<char*>(ehdr_vdso) + ehdr_vdso->e_phoff);
174 si->phnum = ehdr_vdso->e_phnum;
175 si->base = reinterpret_cast<ElfW(Addr)>(ehdr_vdso);
176 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
177 si->load_bias = get_elf_exec_load_bias(ehdr_vdso);
178
179 si->prelink_image();
Ryan Prichard339ecef2020-01-02 16:36:06 -0800180 si->link_image(SymbolLookupList(si), si, nullptr, nullptr);
dimitryc18de1b2017-09-26 14:31:35 +0200181 // prevents accidental unloads...
182 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_NODELETE);
183 si->set_linked();
184 si->call_constructors();
dimitry8b142562018-05-09 15:22:38 +0200185
186 vdso = si;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700187}
188
Ryan Prichard04896452018-08-20 17:44:42 -0700189// Initializes an soinfo's link_map_head field using other fields from the
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700190// soinfo (phdr, phnum, load_bias). The soinfo's realpath must not change after
191// this function is called.
192static void init_link_map_head(soinfo& info) {
Ryan Prichard04896452018-08-20 17:44:42 -0700193 auto& map = info.link_map_head;
194 map.l_addr = info.load_bias;
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700195 map.l_name = const_cast<char*>(info.get_realpath());
Ryan Prichard04896452018-08-20 17:44:42 -0700196 phdr_table_get_dynamic_section(info.phdr, info.phnum, info.load_bias, &map.l_ld, nullptr);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700197}
198
199extern "C" int __system_properties_init(void);
200
Ryan Prichard8f639a42018-10-01 23:10:05 -0700201struct ExecutableInfo {
202 std::string path;
203 struct stat file_stat;
204 const ElfW(Phdr)* phdr;
205 size_t phdr_count;
206 ElfW(Addr) entry_point;
207};
208
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000209static ExecutableInfo get_executable_info(const char* arg_path) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700210 ExecutableInfo result = {};
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000211 char const* exe_path = "/proc/self/exe";
Ryan Prichard8f639a42018-10-01 23:10:05 -0700212
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000213 // Stat "/proc/self/exe" instead of executable_path because
214 // the executable could be unlinked by this point and it should
215 // not cause a crash (see http://b/31084669)
216 if (TEMP_FAILURE_RETRY(stat(exe_path, &result.file_stat) == -1)) {
217 // Fallback to argv[0] for the case where /proc isn't available
218 if (TEMP_FAILURE_RETRY(stat(arg_path, &result.file_stat) == -1)) {
219 async_safe_fatal("unable to stat either \"/proc/self/exe\" or \"%s\": %s",
220 arg_path, strerror(errno));
Tom Cherry66bc4282018-11-08 13:40:52 -0800221 }
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000222 exe_path = arg_path;
223 }
224
225 // Path might be a symlink
226 char sym_path[PATH_MAX];
227 ssize_t sym_path_len = readlink(exe_path, sym_path, sizeof(sym_path));
228 if (sym_path_len > 0 && sym_path_len < static_cast<ssize_t>(sizeof(sym_path))) {
229 result.path = std::string(sym_path, sym_path_len);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700230 } else {
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000231 result.path = std::string(exe_path, strlen(exe_path));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700232 }
233
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
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800240#if defined(__LP64__)
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700241static char kFallbackLinkerPath[] = "/system/bin/linker64";
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800242#else
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700243static char kFallbackLinkerPath[] = "/system/bin/linker";
Dimitry Ivanovd9e427c2016-11-22 16:55:25 -0800244#endif
245
Ryan Prichard8f639a42018-10-01 23:10:05 -0700246__printflike(1, 2)
247static void __linker_error(const char* fmt, ...) {
248 va_list ap;
dimitry04f7a792017-09-29 11:52:17 +0200249
Ryan Prichard8f639a42018-10-01 23:10:05 -0700250 va_start(ap, fmt);
251 async_safe_format_fd_va_list(STDERR_FILENO, fmt, ap);
252 va_end(ap);
253
254 va_start(ap, fmt);
255 async_safe_format_log_va_list(ANDROID_LOG_FATAL, "linker", fmt, ap);
256 va_end(ap);
257
dimitry04f7a792017-09-29 11:52:17 +0200258 _exit(EXIT_FAILURE);
Elliott Hughesad2d0382017-07-31 11:43:34 -0700259}
260
Ryan Prichard8f639a42018-10-01 23:10:05 -0700261static void __linker_cannot_link(const char* argv0) {
262 __linker_error("CANNOT LINK EXECUTABLE \"%s\": %s\n",
263 argv0,
264 linker_get_error_buffer());
265}
266
267// Load an executable. Normally the kernel has already loaded the executable when the linker
268// starts. The linker can be invoked directly on an executable, though, and then the linker must
269// load it. This function doesn't load dependencies or resolve relocations.
270static ExecutableInfo load_executable(const char* orig_path) {
271 ExecutableInfo result = {};
272
273 if (orig_path[0] != '/') {
274 __linker_error("error: expected absolute path: \"%s\"\n", orig_path);
275 }
276
277 off64_t file_offset;
278 android::base::unique_fd fd(open_executable(orig_path, &file_offset, &result.path));
279 if (fd.get() == -1) {
280 __linker_error("error: unable to open file \"%s\"\n", orig_path);
281 }
282
283 if (TEMP_FAILURE_RETRY(fstat(fd.get(), &result.file_stat)) == -1) {
284 __linker_error("error: unable to stat \"%s\": %s\n", result.path.c_str(), strerror(errno));
285 }
286
287 ElfReader elf_reader;
288 if (!elf_reader.Read(result.path.c_str(), fd.get(), file_offset, result.file_stat.st_size)) {
289 __linker_error("error: %s\n", linker_get_error_buffer());
290 }
Torne (Richard Coles)efbe9a52018-10-17 15:59:38 -0400291 address_space_params address_space;
292 if (!elf_reader.Load(&address_space)) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700293 __linker_error("error: %s\n", linker_get_error_buffer());
294 }
295
296 result.phdr = elf_reader.loaded_phdr();
297 result.phdr_count = elf_reader.phdr_count();
298 result.entry_point = elf_reader.entry_point();
299 return result;
300}
301
Tamas Petz8d55d182020-02-24 14:15:25 +0100302static void platform_properties_init() {
303#if defined(__aarch64__)
304 const unsigned long hwcap2 = getauxval(AT_HWCAP2);
305 g_platform_properties.bti_supported = (hwcap2 & HWCAP2_BTI) != 0;
306#endif
307}
308
Ryan Prichard8f639a42018-10-01 23:10:05 -0700309static ElfW(Addr) linker_main(KernelArgumentBlock& args, const char* exe_to_load) {
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800310 ProtectedDataGuard guard;
311
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700312#if TIMING
313 struct timeval t0, t1;
314 gettimeofday(&t0, 0);
315#endif
316
317 // Sanitize the environment.
Ryan Prichard48b11592018-11-22 02:41:36 -0800318 __libc_init_AT_SECURE(args.envp);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700319
320 // Initialize system properties
321 __system_properties_init(); // may use 'environ'
322
Tamas Petz8d55d182020-02-24 14:15:25 +0100323 // Initialize platform properties.
324 platform_properties_init();
325
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700326 // Register the debuggerd signal handler.
Ryan Prichard80e40f02019-10-31 19:54:46 -0700327 linker_debuggerd_init();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700328
329 g_linker_logger.ResetState();
330
Elliott Hughes838dbac2023-08-22 14:07:48 -0700331 // Enable debugging logs?
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700332 const char* LD_DEBUG = getenv("LD_DEBUG");
333 if (LD_DEBUG != nullptr) {
334 g_ld_debug_verbosity = atoi(LD_DEBUG);
335 }
336
Elliott Hughes838dbac2023-08-22 14:07:48 -0700337 if (getenv("LD_SHOW_AUXV") != nullptr) ld_show_auxv(args.auxv);
338
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700339#if defined(__LP64__)
340 INFO("[ Android dynamic linker (64-bit) ]");
341#else
342 INFO("[ Android dynamic linker (32-bit) ]");
343#endif
344
345 // These should have been sanitized by __libc_init_AT_SECURE, but the test
346 // doesn't cost us anything.
347 const char* ldpath_env = nullptr;
348 const char* ldpreload_env = nullptr;
349 if (!getauxval(AT_SECURE)) {
350 ldpath_env = getenv("LD_LIBRARY_PATH");
351 if (ldpath_env != nullptr) {
352 INFO("[ LD_LIBRARY_PATH set to \"%s\" ]", ldpath_env);
353 }
354 ldpreload_env = getenv("LD_PRELOAD");
355 if (ldpreload_env != nullptr) {
356 INFO("[ LD_PRELOAD set to \"%s\" ]", ldpreload_env);
357 }
358 }
359
Ryan Prichard8f639a42018-10-01 23:10:05 -0700360 const ExecutableInfo exe_info = exe_to_load ? load_executable(exe_to_load) :
Vincent Donnefort2efa0172023-01-24 18:00:03 +0000361 get_executable_info(args.argv[0]);
Ryan Prichard8f639a42018-10-01 23:10:05 -0700362
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700363 INFO("[ Linking executable \"%s\" ]", exe_info.path.c_str());
Martin Stjernholm95252ee2019-02-22 22:48:59 +0000364
Ryan Prichard04896452018-08-20 17:44:42 -0700365 // Initialize the main exe's soinfo.
Ryan Prichard8f639a42018-10-01 23:10:05 -0700366 soinfo* si = soinfo_alloc(&g_default_namespace,
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700367 exe_info.path.c_str(), &exe_info.file_stat,
Ryan Prichard8f639a42018-10-01 23:10:05 -0700368 0, RTLD_GLOBAL);
Ryan Prichard04896452018-08-20 17:44:42 -0700369 somain = si;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700370 si->phdr = exe_info.phdr;
371 si->phnum = exe_info.phdr_count;
Ryan Prichard04896452018-08-20 17:44:42 -0700372 get_elf_base_from_phdr(si->phdr, si->phnum, &si->base, &si->load_bias);
373 si->size = phdr_table_get_load_size(si->phdr, si->phnum);
374 si->dynamic = nullptr;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700375 si->set_main_executable();
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700376 init_link_map_head(*si);
377
Vic Yang1bf62b22019-08-13 14:53:28 -0700378 set_bss_vma_name(si);
379
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700380 // Use the executable's PT_INTERP string as the solinker filename in the
381 // dynamic linker's module list. gdb reads both PT_INTERP and the module list,
382 // and if the paths for the linker are different, gdb will report that the
383 // PT_INTERP linker path was unloaded once the module list is initialized.
384 // There are three situations to handle:
385 // - the APEX linker (/system/bin/linker[64] -> /apex/.../linker[64])
386 // - the ASAN linker (/system/bin/linker_asan[64] -> /apex/.../linker[64])
387 // - the bootstrap linker (/system/bin/bootstrap/linker[64])
388 const char *interp = phdr_table_get_interpreter_name(somain->phdr, somain->phnum,
389 somain->load_bias);
390 if (interp == nullptr) {
391 // This case can happen if the linker attempts to execute itself
392 // (e.g. "linker64 /system/bin/linker64").
393 interp = kFallbackLinkerPath;
394 }
395 solinker->set_realpath(interp);
Mitch Phillipse8139f52022-11-23 15:18:01 -0800396 if (solinker->memtag_globals() && solinker->memtag_globalssz()) {
397 name_memtag_globals_segments(solinker->phdr, solinker->phnum, solinker->load_bias,
398 solinker->get_realpath());
399 }
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700400 init_link_map_head(*solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700401
Tamas Petz8d55d182020-02-24 14:15:25 +0100402#if defined(__aarch64__)
Mitch Phillipse8139f52022-11-23 15:18:01 -0800403 __libc_init_mte(somain->memtag_dynamic_entries(), somain->phdr, somain->phnum, somain->load_bias,
404 args.argv);
405
Tamas Petz8d55d182020-02-24 14:15:25 +0100406 if (exe_to_load == nullptr) {
407 // Kernel does not add PROT_BTI to executable pages of the loaded ELF.
408 // Apply appropriate protections here if it is needed.
409 auto note_gnu_property = GnuPropertySection(somain);
410 if (note_gnu_property.IsBTICompatible() &&
411 (phdr_table_protect_segments(somain->phdr, somain->phnum, somain->load_bias,
412 &note_gnu_property) < 0)) {
413 __linker_error("error: can't protect segments for \"%s\": %s", exe_info.path.c_str(),
414 strerror(errno));
415 }
416 }
417#endif
418
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700419 // Register the main executable and the linker upfront to have
420 // gdb aware of them before loading the rest of the dependency
421 // tree.
Ryan Prichard04896452018-08-20 17:44:42 -0700422 //
423 // gdb expects the linker to be in the debug shared object list.
424 // Without this, gdb has trouble locating the linker's ".text"
425 // and ".plt" sections. Gdb could also potentially use this to
426 // relocate the offset of our exported 'rtld_db_dlactivity' symbol.
427 //
428 insert_link_map_into_debug_map(&si->link_map_head);
429 insert_link_map_into_debug_map(&solinker->link_map_head);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700430
Ryan Prichard07440a82018-11-22 03:16:06 -0800431 add_vdso();
Ryan Prichard14dd9922018-08-20 17:43:44 -0700432
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700433 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(si->base);
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800434
435 // We haven't supported non-PIE since Lollipop for security reasons.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700436 if (elf_hdr->e_type != ET_DYN) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700437 // We don't use async_safe_fatal here because we don't want a tombstone:
438 // even after several years we still find ourselves on app compatibility
Elliott Hughes3bdb31b2017-01-07 10:38:20 -0800439 // investigations because some app's trying to launch an executable that
440 // hasn't worked in at least three years, and we've "helpfully" dropped a
441 // tombstone for them. The tombstone never provided any detail relevant to
442 // fixing the problem anyway, and the utility of drawing extra attention
443 // to the problem is non-existent at this late date.
Christopher Ferris7a3681e2017-04-24 17:48:32 -0700444 async_safe_format_fd(STDERR_FILENO,
Elliott Hughesad2d0382017-07-31 11:43:34 -0700445 "\"%s\": error: Android 5.0 and later only support "
446 "position-independent executables (-fPIE).\n",
447 g_argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700448 _exit(EXIT_FAILURE);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700449 }
450
451 // Use LD_LIBRARY_PATH and LD_PRELOAD (but only if we aren't setuid/setgid).
452 parse_LD_LIBRARY_PATH(ldpath_env);
453 parse_LD_PRELOAD(ldpreload_env);
454
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700455 std::vector<android_namespace_t*> namespaces = init_default_namespaces(exe_info.path.c_str());
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700456
Elliott Hughesad2d0382017-07-31 11:43:34 -0700457 if (!si->prelink_image()) __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700458
459 // add somain to global group
460 si->set_dt_flags_1(si->get_dt_flags_1() | DF_1_GLOBAL);
Jiyong Park02586a22017-05-20 01:01:24 +0900461 // ... and add it to all other linked namespaces
462 for (auto linked_ns : namespaces) {
463 if (linked_ns != &g_default_namespace) {
464 linked_ns->add_soinfo(somain);
465 somain->add_secondary_namespace(linked_ns);
466 }
467 }
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700468
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800469 linker_setup_exe_static_tls(g_argv[0]);
470
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700471 // Load ld_preloads and dependencies.
472 std::vector<const char*> needed_library_name_list;
473 size_t ld_preloads_count = 0;
474
475 for (const auto& ld_preload_name : g_ld_preload_names) {
476 needed_library_name_list.push_back(ld_preload_name.c_str());
477 ++ld_preloads_count;
478 }
479
480 for_each_dt_needed(si, [&](const char* name) {
481 needed_library_name_list.push_back(name);
482 });
483
484 const char** needed_library_names = &needed_library_name_list[0];
485 size_t needed_libraries_count = needed_library_name_list.size();
486
487 if (needed_libraries_count > 0 &&
Dimitry Ivanov7d429d32017-02-01 15:28:52 -0800488 !find_libraries(&g_default_namespace,
489 si,
490 needed_library_names,
491 needed_libraries_count,
492 nullptr,
493 &g_ld_preloads,
494 ld_preloads_count,
495 RTLD_GLOBAL,
496 nullptr,
497 true /* add_as_children */,
Jiyong Park02586a22017-05-20 01:01:24 +0900498 &namespaces)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700499 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700500 } else if (needed_libraries_count == 0) {
Ryan Prichard339ecef2020-01-02 16:36:06 -0800501 if (!si->link_image(SymbolLookupList(si), si, nullptr, nullptr)) {
Elliott Hughesad2d0382017-07-31 11:43:34 -0700502 __linker_cannot_link(g_argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700503 }
504 si->increment_ref_count();
505 }
506
Ryan Pricharde5e69e02019-01-01 18:53:48 -0800507 linker_finalize_static_tls();
Ryan Prichard45d13492019-01-03 02:51:30 -0800508 __libc_init_main_thread_final();
509
Elliott Hughesad2d0382017-07-31 11:43:34 -0700510 if (!get_cfi_shadow()->InitialLinkDone(solist)) __linker_cannot_link(g_argv[0]);
Evgenii Stepanov0a3637d2016-07-06 13:20:59 -0700511
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800512 si->call_pre_init_constructors();
Dimitry Ivanov4cabfaa2017-03-07 11:19:05 -0800513 si->call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700514
515#if TIMING
516 gettimeofday(&t1, nullptr);
Vic Yang7b9db342019-04-16 14:54:58 -0700517 PRINT("LINKER TIME: %s: %d microseconds", g_argv[0],
518 static_cast<int>(((static_cast<long long>(t1.tv_sec) * 1000000LL) +
519 static_cast<long long>(t1.tv_usec)) -
520 ((static_cast<long long>(t0.tv_sec) * 1000000LL) +
521 static_cast<long long>(t0.tv_usec))));
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700522#endif
523#if STATS
Vic Yang542db792019-07-25 10:39:27 -0700524 print_linker_stats();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700525#endif
Ryan Prichard78cd2832019-10-25 17:46:43 -0700526#if TIMING || STATS
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700527 fflush(stdout);
528#endif
529
Vic Yangbb7e1232019-01-29 20:23:16 -0800530 // We are about to hand control over to the executable loaded. We don't want
531 // to leave dirty pages behind unnecessarily.
532 purge_unused_memory();
533
Ryan Prichard8f639a42018-10-01 23:10:05 -0700534 ElfW(Addr) entry = exe_info.entry_point;
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700535 TRACE("[ Ready to execute \"%s\" @ %p ]", si->get_realpath(), reinterpret_cast<void*>(entry));
536 return entry;
537}
538
539/* Compute the load-bias of an existing executable. This shall only
540 * be used to compute the load bias of an executable or shared library
541 * that was loaded by the kernel itself.
542 *
543 * Input:
544 * elf -> address of ELF header, assumed to be at the start of the file.
545 * Return:
546 * load bias, i.e. add the value of any p_vaddr in the file to get
547 * the corresponding address in memory.
548 */
549static ElfW(Addr) get_elf_exec_load_bias(const ElfW(Ehdr)* elf) {
550 ElfW(Addr) offset = elf->e_phoff;
551 const ElfW(Phdr)* phdr_table =
552 reinterpret_cast<const ElfW(Phdr)*>(reinterpret_cast<uintptr_t>(elf) + offset);
553 const ElfW(Phdr)* phdr_end = phdr_table + elf->e_phnum;
554
555 for (const ElfW(Phdr)* phdr = phdr_table; phdr < phdr_end; phdr++) {
556 if (phdr->p_type == PT_LOAD) {
557 return reinterpret_cast<ElfW(Addr)>(elf) + phdr->p_offset - phdr->p_vaddr;
558 }
559 }
560 return 0;
561}
562
Ryan Prichard9729f352018-07-13 22:40:26 -0700563/* Find the load bias and base address of an executable or shared object loaded
564 * by the kernel. The ELF file's PHDR table must have a PT_PHDR entry.
565 *
566 * A VDSO doesn't have a PT_PHDR entry in its PHDR table.
567 */
568static void get_elf_base_from_phdr(const ElfW(Phdr)* phdr_table, size_t phdr_count,
569 ElfW(Addr)* base, ElfW(Addr)* load_bias) {
570 for (size_t i = 0; i < phdr_count; ++i) {
571 if (phdr_table[i].p_type == PT_PHDR) {
572 *load_bias = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_vaddr;
573 *base = reinterpret_cast<ElfW(Addr)>(phdr_table) - phdr_table[i].p_offset;
574 return;
575 }
576 }
577 async_safe_fatal("Could not find a PHDR: broken executable?");
578}
579
Vic Yang1bf62b22019-08-13 14:53:28 -0700580/*
581 * Set anonymous VMA name for .bss section. For DSOs loaded by the linker, this
582 * is done by ElfReader. This function is here for DSOs loaded by the kernel,
583 * namely the linker itself and the main executable.
584 */
585static void set_bss_vma_name(soinfo* si) {
586 for (size_t i = 0; i < si->phnum; ++i) {
587 auto phdr = &si->phdr[i];
588
589 if (phdr->p_type != PT_LOAD) {
590 continue;
591 }
592
593 ElfW(Addr) seg_start = phdr->p_vaddr + si->load_bias;
Peter Collingbournebb11ee62022-05-02 12:26:16 -0700594 ElfW(Addr) seg_page_end = page_end(seg_start + phdr->p_memsz);
595 ElfW(Addr) seg_file_end = page_end(seg_start + phdr->p_filesz);
Vic Yang1bf62b22019-08-13 14:53:28 -0700596
597 if (seg_page_end > seg_file_end) {
598 prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME,
599 reinterpret_cast<void*>(seg_file_end), seg_page_end - seg_file_end,
600 ".bss");
601 }
602 }
603}
604
Ryan Prichard249757b2019-11-01 17:18:28 -0700605#if defined(USE_RELA)
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700606using RelType = ElfW(Rela);
607const unsigned kRelTag = DT_RELA;
608const unsigned kRelSzTag = DT_RELASZ;
Ryan Prichard249757b2019-11-01 17:18:28 -0700609#else
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700610using RelType = ElfW(Rel);
611const unsigned kRelTag = DT_REL;
612const unsigned kRelSzTag = DT_RELSZ;
613#endif
Ryan Prichard249757b2019-11-01 17:18:28 -0700614
Mitch Phillipse8139f52022-11-23 15:18:01 -0800615BIONIC_USED_BEFORE_LINKER_RELOCATES extern __LIBC_HIDDEN__ ElfW(Ehdr) __ehdr_start;
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700616
617static void call_ifunc_resolvers_for_section(RelType* begin, RelType* end) {
618 auto ehdr = reinterpret_cast<ElfW(Addr)>(&__ehdr_start);
619 for (RelType *r = begin; r != end; ++r) {
620 if (ELFW(R_TYPE)(r->r_info) != R_GENERIC_IRELATIVE) {
621 continue;
622 }
623 ElfW(Addr)* offset = reinterpret_cast<ElfW(Addr)*>(ehdr + r->r_offset);
624#if defined(USE_RELA)
625 ElfW(Addr) resolver = ehdr + r->r_addend;
626#else
627 ElfW(Addr) resolver = ehdr + *offset;
628#endif
Ryan Prichard249757b2019-11-01 17:18:28 -0700629 *offset = __bionic_call_ifunc_resolver(resolver);
630 }
631}
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700632
633static void call_ifunc_resolvers() {
634 // Find the IRELATIVE relocations using the DT_JMPREL and DT_PLTRELSZ, or DT_RELA? and DT_RELA?SZ
635 // dynamic tags.
636 auto ehdr = reinterpret_cast<ElfW(Addr)>(&__ehdr_start);
637 auto* phdr = reinterpret_cast<ElfW(Phdr)*>(ehdr + __ehdr_start.e_phoff);
638 for (size_t i = 0; i != __ehdr_start.e_phnum; ++i) {
639 if (phdr[i].p_type != PT_DYNAMIC) {
640 continue;
641 }
642 auto *dyn = reinterpret_cast<ElfW(Dyn)*>(ehdr + phdr[i].p_vaddr);
643 ElfW(Addr) pltrel = 0, pltrelsz = 0, rel = 0, relsz = 0;
644 for (size_t j = 0, size = phdr[i].p_filesz / sizeof(ElfW(Dyn)); j != size; ++j) {
645 if (dyn[j].d_tag == DT_JMPREL) {
646 pltrel = dyn[j].d_un.d_ptr;
647 } else if (dyn[j].d_tag == DT_PLTRELSZ) {
648 pltrelsz = dyn[j].d_un.d_ptr;
649 } else if (dyn[j].d_tag == kRelTag) {
650 rel = dyn[j].d_un.d_ptr;
651 } else if (dyn[j].d_tag == kRelSzTag) {
652 relsz = dyn[j].d_un.d_ptr;
653 }
654 }
655 if (pltrel && pltrelsz) {
656 call_ifunc_resolvers_for_section(reinterpret_cast<RelType*>(ehdr + pltrel),
657 reinterpret_cast<RelType*>(ehdr + pltrel + pltrelsz));
658 }
659 if (rel && relsz) {
660 call_ifunc_resolvers_for_section(reinterpret_cast<RelType*>(ehdr + rel),
661 reinterpret_cast<RelType*>(ehdr + rel + relsz));
662 }
663 }
664}
Ryan Prichard249757b2019-11-01 17:18:28 -0700665
Ryan Prichard94a8e852019-11-05 14:19:18 -0800666// Usable before ifunc resolvers have been called. This function is compiled with -ffreestanding.
667static void linker_memclr(void* dst, size_t cnt) {
668 for (size_t i = 0; i < cnt; ++i) {
669 reinterpret_cast<char*>(dst)[i] = '\0';
670 }
671}
672
Mitch Phillipse8139f52022-11-23 15:18:01 -0800673// Remapping MTE globals segments happens before the linker relocates itself, and so can't use
674// memcpy() from string.h. This function is compiled with -ffreestanding.
675void linker_memcpy(void* dest, const void* src, size_t n) {
676 char* dest_bytes = reinterpret_cast<char*>(dest);
677 const char* src_bytes = reinterpret_cast<const char*>(src);
678 for (size_t i = 0; i < n; ++i) {
679 dest_bytes[i] = src_bytes[i];
680 }
681}
682
Ryan Prichard1990ba52019-02-07 21:31:31 -0800683// Detect an attempt to run the linker on itself. e.g.:
684// /system/bin/linker64 /system/bin/linker64
685// Use priority-1 to run this constructor before other constructors.
686__attribute__((constructor(1))) static void detect_self_exec() {
687 // Normally, the linker initializes the auxv global before calling its
688 // constructors. If the linker loads itself, though, the first loader calls
689 // the second loader's constructors before calling __linker_init.
690 if (__libc_shared_globals()->auxv != nullptr) {
691 return;
692 }
693#if defined(__i386__)
694 // We don't have access to the auxv struct from here, so use the int 0x80
695 // fallback.
696 __libc_sysinfo = reinterpret_cast<void*>(__libc_int0x80);
697#endif
698 __linker_error("error: linker cannot load itself\n");
699}
700
Ryan Prichard742982d2018-05-30 22:32:17 -0700701static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700702__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700703
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700704/*
705 * This is the entry point for the linker, called from begin.S. This
706 * method is responsible for fixing the linker's own relocations, and
707 * then calling __linker_init_post_relocation().
708 *
709 * Because this method is called before the linker has fixed it's own
710 * relocations, any attempt to reference an extern variable, extern
711 * function, or other GOT reference will generate a segfault.
712 */
713extern "C" ElfW(Addr) __linker_init(void* raw_args) {
Ryan Prichard67e8f222023-08-18 16:21:48 -0700714 // Unlock the loader mutex immediately before transferring to the executable's
715 // entry point. This must happen after destructors are called in this function
716 // (e.g. ~soinfo), so declare this variable very early.
717 struct DlMutexUnlocker {
718 ~DlMutexUnlocker() { pthread_mutex_unlock(&g_dl_mutex); }
719 } unlocker;
720
Ryan Prichard9cfca862018-11-22 02:44:09 -0800721 // Initialize TLS early so system calls and errno work.
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700722 KernelArgumentBlock args(raw_args);
Ryan Prichard94a8e852019-11-05 14:19:18 -0800723 bionic_tcb temp_tcb __attribute__((uninitialized));
724 linker_memclr(&temp_tcb, sizeof(temp_tcb));
Ryan Prichard45d13492019-01-03 02:51:30 -0800725 __libc_init_main_thread_early(args, &temp_tcb);
Ryan Prichard27475b52018-05-17 17:14:18 -0700726
Ryan Prichard8f639a42018-10-01 23:10:05 -0700727 // When the linker is run by itself (rather than as an interpreter for
728 // another program), AT_BASE is 0.
Ryan Prichard07440a82018-11-22 03:16:06 -0800729 ElfW(Addr) linker_addr = getauxval(AT_BASE);
Ryan Prichard9729f352018-07-13 22:40:26 -0700730 if (linker_addr == 0) {
Ryan Prichard1990ba52019-02-07 21:31:31 -0800731 // The AT_PHDR and AT_PHNUM aux values describe this linker instance, so use
732 // the phdr to find the linker's base address.
Ryan Prichard9729f352018-07-13 22:40:26 -0700733 ElfW(Addr) load_bias;
734 get_elf_base_from_phdr(
Ryan Prichard07440a82018-11-22 03:16:06 -0800735 reinterpret_cast<ElfW(Phdr)*>(getauxval(AT_PHDR)), getauxval(AT_PHNUM),
Ryan Prichard9729f352018-07-13 22:40:26 -0700736 &linker_addr, &load_bias);
737 }
George Burgess IV70591002017-06-27 16:23:45 -0700738
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700739 ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
740 ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
741
Ryan Prichard249757b2019-11-01 17:18:28 -0700742 // string.h functions must not be used prior to calling the linker's ifunc resolvers.
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700743 call_ifunc_resolvers();
Ryan Prichard249757b2019-11-01 17:18:28 -0700744
Ryan Prichard04896452018-08-20 17:44:42 -0700745 soinfo tmp_linker_so(nullptr, nullptr, nullptr, 0, 0);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700746
Ryan Prichard04896452018-08-20 17:44:42 -0700747 tmp_linker_so.base = linker_addr;
748 tmp_linker_so.size = phdr_table_get_load_size(phdr, elf_hdr->e_phnum);
Peter Collingbourne1583cd22021-08-18 17:04:23 -0700749 tmp_linker_so.load_bias = get_elf_exec_load_bias(elf_hdr);
Ryan Prichard04896452018-08-20 17:44:42 -0700750 tmp_linker_so.dynamic = nullptr;
751 tmp_linker_so.phdr = phdr;
752 tmp_linker_so.phnum = elf_hdr->e_phnum;
753 tmp_linker_so.set_linker_flag();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700754
755 // Prelink the linker so we can access linker globals.
Ryan Prichard04896452018-08-20 17:44:42 -0700756 if (!tmp_linker_so.prelink_image()) __linker_cannot_link(args.argv[0]);
Ryan Prichard339ecef2020-01-02 16:36:06 -0800757 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 -0700758
Ryan Prichard04896452018-08-20 17:44:42 -0700759 return __linker_init_post_relocation(args, tmp_linker_so);
Ryan Prichard742982d2018-05-30 22:32:17 -0700760}
761
762/*
763 * This code is called after the linker has linked itself and fixed its own
764 * GOT. It is safe to make references to externs and other non-local data at
765 * this point. The compiler sometimes moves GOT references earlier in a
766 * function, so avoid inlining this function (http://b/80503879).
767 */
768static ElfW(Addr) __attribute__((noinline))
Ryan Prichard04896452018-08-20 17:44:42 -0700769__linker_init_post_relocation(KernelArgumentBlock& args, soinfo& tmp_linker_so) {
Ryan Prichard9cfca862018-11-22 02:44:09 -0800770 // Finish initializing the main thread.
Ryan Prichard07440a82018-11-22 03:16:06 -0800771 __libc_init_main_thread_late();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700772
773 // We didn't protect the linker's RELRO pages in link_image because we
774 // couldn't make system calls on x86 at that point, but we can now...
Ryan Prichard04896452018-08-20 17:44:42 -0700775 if (!tmp_linker_so.protect_relro()) __linker_cannot_link(args.argv[0]);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700776
Vic Yang1bf62b22019-08-13 14:53:28 -0700777 // And we can set VMA name for the bss section now
778 set_bss_vma_name(&tmp_linker_so);
779
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700780 // Initialize the linker's static libc's globals
Ryan Prichard07440a82018-11-22 03:16:06 -0800781 __libc_init_globals();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700782
Ryan Prichard67e8f222023-08-18 16:21:48 -0700783 // A constructor could spawn a thread that calls into the loader, so as soon
784 // as we've called a constructor, we need to hold the lock until transferring
785 // to the entry point.
786 pthread_mutex_lock(&g_dl_mutex);
787
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700788 // Initialize the linker's own global variables
Ryan Prichard04896452018-08-20 17:44:42 -0700789 tmp_linker_so.call_constructors();
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700790
Ryan Prichardbb1e3732021-01-12 23:09:10 -0800791 // Setting the linker soinfo's soname can allocate heap memory, so delay it until here.
792 for (const ElfW(Dyn)* d = tmp_linker_so.dynamic; d->d_tag != DT_NULL; ++d) {
793 if (d->d_tag == DT_SONAME) {
794 tmp_linker_so.set_soname(tmp_linker_so.get_string(d->d_un.d_val));
795 }
796 }
797
Ryan Prichard8f639a42018-10-01 23:10:05 -0700798 // When the linker is run directly rather than acting as PT_INTERP, parse
799 // arguments and determine the executable to load. When it's instead acting
800 // as PT_INTERP, AT_ENTRY will refer to the loaded executable rather than the
801 // linker's _start.
802 const char* exe_to_load = nullptr;
Ryan Prichard07440a82018-11-22 03:16:06 -0800803 if (getauxval(AT_ENTRY) == reinterpret_cast<uintptr_t>(&_start)) {
Elliott Hughes90f96b92019-05-09 15:56:39 -0700804 if (args.argc == 3 && !strcmp(args.argv[1], "--list")) {
805 // We're being asked to behave like ldd(1).
806 g_is_ldd = true;
807 exe_to_load = args.argv[2];
808 } else if (args.argc <= 1 || !strcmp(args.argv[1], "--help")) {
Ryan Prichard8f639a42018-10-01 23:10:05 -0700809 async_safe_format_fd(STDOUT_FILENO,
Elliott Hughes90f96b92019-05-09 15:56:39 -0700810 "Usage: %s [--list] PROGRAM [ARGS-FOR-PROGRAM...]\n"
811 " %s [--list] path.zip!/PROGRAM [ARGS-FOR-PROGRAM...]\n"
Ryan Prichard8f639a42018-10-01 23:10:05 -0700812 "\n"
813 "A helper program for linking dynamic executables. Typically, the kernel loads\n"
814 "this program because it's the PT_INTERP of a dynamic executable.\n"
815 "\n"
816 "This program can also be run directly to load and run a dynamic executable. The\n"
817 "executable can be inside a zip file if it's stored uncompressed and at a\n"
Elliott Hughes90f96b92019-05-09 15:56:39 -0700818 "page-aligned offset.\n"
819 "\n"
820 "The --list option gives behavior equivalent to ldd(1) on other systems.\n",
Ryan Prichard8f639a42018-10-01 23:10:05 -0700821 args.argv[0], args.argv[0]);
Elliott Hughes90f96b92019-05-09 15:56:39 -0700822 _exit(EXIT_SUCCESS);
823 } else {
824 exe_to_load = args.argv[1];
825 __libc_shared_globals()->initial_linker_arg_count = 1;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700826 }
Dimitry Ivanov9b1cc4b2017-03-23 16:17:15 -0700827 }
828
Ryan Prichard8f639a42018-10-01 23:10:05 -0700829 // store argc/argv/envp to use them for calling constructors
Ryan Prichardabf736a2018-11-22 02:40:17 -0800830 g_argc = args.argc - __libc_shared_globals()->initial_linker_arg_count;
831 g_argv = args.argv + __libc_shared_globals()->initial_linker_arg_count;
Ryan Prichard8f639a42018-10-01 23:10:05 -0700832 g_envp = args.envp;
Ryan Prichard48b11592018-11-22 02:41:36 -0800833 __libc_shared_globals()->init_progname = g_argv[0];
Ryan Prichard8f639a42018-10-01 23:10:05 -0700834
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700835 // Initialize static variables. Note that in order to
836 // get correct libdl_info we need to call constructors
837 // before get_libdl_info().
Ryan Prichardcf9ed122019-06-04 20:56:56 -0700838 sonext = solist = solinker = get_libdl_info(tmp_linker_so);
Ryan Prichard04896452018-08-20 17:44:42 -0700839 g_default_namespace.add_soinfo(solinker);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700840
Ryan Prichard8f639a42018-10-01 23:10:05 -0700841 ElfW(Addr) start_address = linker_main(args, exe_to_load);
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700842
Elliott Hughes90f96b92019-05-09 15:56:39 -0700843 if (g_is_ldd) _exit(EXIT_SUCCESS);
844
Dimitry Ivanov3f660572016-09-09 10:00:39 -0700845 INFO("[ Jumping to _start (%p)... ]", reinterpret_cast<void*>(start_address));
846
847 // Return the address that the calling assembly stub should jump to.
848 return start_address;
849}